public bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullUrl, long _speed) { try { FileStream myFile = new FileStream(_fullUrl, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader br = new BinaryReader(myFile); try { _Response.AddHeader("Accept-Ranges", "bytes"); _Response.Buffer = false; long fileLength = myFile.Length; long startBytes = 0; int pack = 10240; //10K bytes int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1; if (_Request.Headers["Range"] != null) { _Response.StatusCode = 206; string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' }); startBytes = Convert.ToInt64(range[1]); } _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); if (startBytes != 0) { _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); } _Response.AddHeader("Connection", "Keep-Alive"); _Response.ContentType = "application/octet-stream"; _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin); int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1; for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(pack)); Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; }
public HttpResponse GetResponse() { var response = new HttpResponse(Request.ProtocolVersion, GetStatusCode(), GetContent(), HighQualityCodeExamPointsProvider.GetContentType()); foreach (var responseHeader in ResponseHeaders) { response.AddHeader(responseHeader.Key, responseHeader.Value); } return response; }
public HttpResponse GetResponse() { var response = new HttpResponse(this.Request.ProtocolVersion, this.GetStatusCode(), this.GetContent(), this.GetContentType()); foreach (var responseHeader in this.ResponseHeaders) { response.AddHeader(responseHeader.Key, responseHeader.Value); } return response; }
public HttpResponse GetResponse() { var response = new HttpResponse(this.Request.ProtocolVersion, HttpStatusCode.OK, this.model.ToString(), ContentType); foreach (var responseHeader in this.ResponseHeaders) { response.AddHeader(responseHeader.Key, responseHeader.Value); } return response; }
/// <summary> /// The get response. /// </summary> /// <returns> /// The <see cref="HttpResponse" />. /// </returns> public HttpResponse GetResponse() { var response = new HttpResponse(this.Request.ProtocolVersion, HttpStatusCode.Redirect, string.Empty); foreach (var responseHeader in this.ResponseHeaders) { response.AddHeader(responseHeader.Key, responseHeader.Value); } return response; }
protected static void ExportCSV(HttpResponse response, string fileText, string fileName) { byte[] buffer = GetBytes(fileText); try { response.Clear(); response.ContentType = "text/plain"; response.OutputStream.Write(buffer, 0, buffer.Length); response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); response.End(); } catch (System.Web.HttpException ex) { // ignore exception where user closed the download box if (!ex.Message.StartsWith("The remote host closed the connection. The error code is")) throw; } }
public void Write(HttpResponse response, bool inline) { response.Clear(); response.ContentType = "application/pdf"; response.AddHeader("Content-Disposition", (inline ? "inline" : "attachment") + "; filename=Map.pdf"); // create the PDF document Configuration config = AppContext.GetConfiguration(); Configuration.PrintTemplateRow printTemplate = config.PrintTemplate.First(o => o.TemplateID == _templateId); float pageWidth = Convert.ToSingle(printTemplate.PageWidth * PointsPerInch); float pageHeight = Convert.ToSingle(printTemplate.PageHeight * PointsPerInch); Rectangle pageSize = new Rectangle(pageWidth, pageHeight); pageSize.BackgroundColor = new Color(System.Drawing.Color.White); Document document = new Document(pageSize); PdfWriter writer = PdfWriter.GetInstance(document, response.OutputStream); document.Open(); PdfContentByte content = writer.DirectContent; // get the extent of the main map and fit it to the proportions of // the map box on the page double mapScale = 0; Configuration.PrintTemplateContentRow mapElement = printTemplate.GetPrintTemplateContentRows().FirstOrDefault(o => o.ContentType == "map"); if (mapElement != null) { if (_preserveMode == PreserveMode.Extent) { _appState.Extent.Reaspect(mapElement.Width, mapElement.Height); } else { IPoint c = new Point(_appState.Extent.Centre); double dx; double dy; if (_preserveMode == PreserveMode.Scale) { double ratio = _appState.Extent.Width * 96 / _originalWidth; dx = mapElement.Width * ratio * 0.5; dy = mapElement.Height * ratio * 0.5; } else { dx = _appState.Extent.Width * 0.5; dy = dx * mapElement.Height / mapElement.Width; } _appState.Extent = new Envelope(new Coordinate(c.Coordinate.X - dx, c.Coordinate.Y - dy), new Coordinate(c.Coordinate.X + dx, c.Coordinate.Y + dy)); } double conversion = AppSettings.MapUnits == "feet" ? 1 : Constants.FeetPerMeter; mapScale = _appState.Extent.Width * conversion / mapElement.Width; _pixelSize = _appState.Extent.Width / (mapElement.Width * PixelsPerInch); } int inputIndex = 0; // get the page template elements and draw each one to the page foreach (Configuration.PrintTemplateContentRow element in printTemplate.GetPrintTemplateContentRows()) { switch (element.ContentType) { case "box": CreatePdfBox(content, element); break; case "date": CreatePdfText(content, element, DateTime.Now.ToString("MMMM d, yyyy")); break; case "image": CreatePdfImage(content, element); break; case "legend": CreatePdfLegend(content, element); break; case "map": CreatePdfMap(content, element); break; case "overviewmap": CreatePdfOverviewMap(content, element); break; case "scale": if (mapScale > 0) { CreatePdfText(content, element, "1\" = " + mapScale.ToString("0") + " ft"); } break; case "scalefeet": if (mapScale > 0) { CreatePdfText(content, element, mapScale.ToString("0") + " ft"); } break; case "tabdata": CreatePdfTabData(content, element); break; case "text": if (!element.IsTextNull()) { CreatePdfText(content, element, element.Text); } else if (!element.IsFileNameNull()) { string fileName = HttpContext.Current.Server.MapPath("Text/Print") + "\\" + element.FileName; if (File.Exists(fileName)) { string text = File.ReadAllText(fileName); CreatePdfText(content, element, text); } } break; case "input": if (inputIndex < _input.Count) { CreatePdfText(content, element, _input[inputIndex]); ++inputIndex; } break; } } document.Close(); response.End(); }
public void StyleExport(int id) { GgcmsStyles sinfo = Dbctx.GgcmsStyles.Where(x => x.Id == id).FirstOrDefault(); string templateDir = ConfigurationManager.AppSettings["TemplateDir"].ToString(); string staticDir = ConfigurationManager.AppSettings["StaticDir"].ToString(); string styleDir = ConfigurationManager.AppSettings["StyleDir"].ToString(); string uploadDir = ConfigurationManager.AppSettings["UploadDir"].ToString(); //模板目录 string viewPath = "Views/" + templateDir + "/" + sinfo.Folder; string viewDir = HttpContext.Current.Server.MapPath("~/" + viewPath); //风格目录 string stylePath = staticDir + "/" + styleDir + "/" + sinfo.Folder; string sDir = HttpContext.Current.Server.MapPath("~/" + stylePath); //模板要复制的临时目录 string tmplPath = HttpContext.Current.Server.MapPath("~/" + stylePath + "/template"); if (!Directory.Exists(tmplPath)) { Directory.CreateDirectory(tmplPath); } else { Directory.Delete(tmplPath, true); Directory.CreateDirectory(tmplPath); } string[] tmplFiles = Directory.GetFiles(viewDir); foreach (string f in tmplFiles) { string fn = Path.GetFileName(f); File.Copy(f, tmplPath + "/" + fn); } //生成的zip文件 string zipFilePath = staticDir + "/" + uploadDir + "/temp/" + Path.GetFileName(Tools.getRandString(8)) + ".zip"; string zipFile = HttpContext.Current.Server.MapPath("~/" + zipFilePath); while (File.Exists(zipFile)) { zipFilePath = staticDir + "/" + uploadDir + "/temp/" + Path.GetFileName(Tools.getRandString(8)) + ".zip"; zipFile = HttpContext.Current.Server.MapPath("~/" + zipFilePath); } string extDir = Path.GetDirectoryName(zipFile); if (!Directory.Exists(extDir)) { Directory.CreateDirectory(extDir); } ZipFile.CreateFromDirectory(sDir, zipFile); Directory.Delete(tmplPath, true); HttpResponse Response = HttpContext.Current.Response; FileInfo downfile = new FileInfo(zipFile); Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment; filename=" + sinfo.Folder + ".zip"); Response.AddHeader("Content-Length", downfile.Length.ToString()); Response.ContentType = "application/x-zip-compressed"; Response.Flush(); Response.TransmitFile(zipFile); Response.End(); }
public void ProcessRequest(HttpContext context) { HttpResponse Response = context.Response; HttpRequest Request = context.Request; System.IO.Stream iStream = null; byte[] buffer = new Byte[10240]; int length; long dataToRead; System.Data.OleDb.OleDbConnection dbConnection = null; string sFileName = Request["fn"]; string sFilePath = HttpContext.Current.Server.MapPath("~/") + sFileName; //待下载的文件路径 try { if (sFileName != null)//按文件名下载指定文件 { iStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); } else//下载debug报表 { ExcelPackage pck = new ExcelPackage(); BuildExcelReport(ref pck, ref dbConnection, ref context, ref sFileName); iStream = new System.IO.MemoryStream(pck.GetAsByteArray()); } Response.Clear(); dataToRead = iStream.Length; long p = 0; if (Request.Headers["Range"] != null) { Response.StatusCode = 206; p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", "")); } if (p != 0) { Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString()); } Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString()); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode( System.Text.Encoding.GetEncoding(65001).GetBytes(System.IO.Path.GetFileName(sFileName)))); iStream.Position = p; dataToRead = dataToRead - p; while (dataToRead > 0) { if (Response.IsClientConnected) { length = iStream.Read(buffer, 0, 10240); Response.OutputStream.Write(buffer, 0, length); Response.Flush(); buffer = new Byte[10240]; dataToRead = dataToRead - length; } else { dataToRead = -1; } } //Response.End(); HttpContext.Current.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { Response.Write("Error : " + context.Server.HtmlEncode(ex.Message)); string sHtml = "<script type=\"text/javascript\">" + "if(parent.lblError) parent.lblError.innerHTML=unescape(\"" + Microsoft.JScript.GlobalObject.escape(ex.Message.Replace("\n", "<br>")) + "\");" + "</script>"; Response.Write(sHtml); } finally { if (iStream != null) { iStream.Close(); } if (dbConnection != null) { dbConnection.Dispose(); } } }
private void ExportToCSV(string exportContent, HttpResponse response) { response.Clear(); response.AddHeader("content-disposition", "attachment;filename=" + fileName); response.Charset = ""; response.ContentType = "application/octet-stream"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); response.Write(exportContent); response.End(); }
/* goodB2G1() - use badsource and goodsink by changing second PrivateReturnsTrue() to PrivateReturnsFalse() */ private void GoodB2G1(HttpRequest req, HttpResponse resp) { string data; if (PrivateReturnsTrue()) { data = ""; /* Initialize data */ /* Read data using a listening tcp connection */ { TcpListener listener = null; try { listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543); listener.Start(); using (TcpClient tcpConn = listener.AcceptTcpClient()) { /* read input from socket */ using (StreamReader sr = new StreamReader(tcpConn.GetStream())) { /* POTENTIAL FLAW: Read data using a listening tcp connection */ data = sr.ReadLine(); } } } catch (IOException exceptIO) { IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading"); } finally { if (listener != null) { try { listener.Stop(); } catch (SocketException se) { IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener"); } } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } if (PrivateReturnsFalse()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.WriteLine("Benign, fixed string"); } else { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ if (data != null) { data = HttpUtility.UrlEncode("", Encoding.UTF8); resp.AddHeader("Location", "/author.jsp?lang=" + data); } } }
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed) { try { FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader br = new BinaryReader(myFile); try { _Response.AddHeader("Accept-Ranges", "bytes"); _Response.Buffer = false; long fileLength = myFile.Length; long startBytes = 0; int pack = 10240; //10K bytes int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1; if (_Request.Headers["Range"] != null) { _Response.StatusCode = 206; string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' }); startBytes = Convert.ToInt64(range[1]); } _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); if (startBytes != 0) { _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); } _Response.AddHeader("Connection", "Keep-Alive"); _Response.ContentType = "application/octet-stream"; _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin); int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1; for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(pack)); Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return(false); } finally { br.Close(); myFile.Close(); } } catch { return(false); } return(true); }
private void ExportToExcel(string nameReport, List <InformeProduccionM> lista, string Area, string Maquina, string fInicio) { HttpResponse response = Response; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); Page pageToRender = new Page(); HtmlForm form = new HtmlForm(); Label la = new Label(); string Titulo = "<div align='center'>Informe SobreImpresión<br/>"; if (Area != "") { Titulo += "Area : " + Area; } if (Maquina != "") { Titulo += " Maquina : " + Maquina; } if (fInicio != "") { Titulo += " Fecha : " + fInicio; } la.Text = Titulo + "</div><br />"; form.Controls.Add(la); #region ConversionListaGrilla int contado = 0; int TotalRotCantPlan = 0; int TotalRotCantPlanSobre = 0; int TotalRotCantProdSobre = 0; int TotalRotCantDifSobre = 0; double RotPorceCantDifSobre = 0; int TotalRotCantPlanBajo = 0; int TotalRotCantProdBajo = 0; int TotalRotCantDifBajo = 0; double RotPorceCantDifBajo = 0; int TotalPlaCantPlan = 0; int TotalPlaCantPlanSobre = 0; int TotalPlaCantProdSobre = 0; int TotalPlaCantDifSobre = 0; double PlaPorceCantDifSobre = 0; int TotalPlaCantPlanBajo = 0; int TotalPlaCantProdBajo = 0; int TotalPlaCantDifbajo = 0; double PlaPorceCantDifBajo = 0; foreach (string maquinasProd in lista.Select(o => o.Maquina).Distinct()) { GridView gv = new GridView(); gv.DataSource = lista.Where(o => o.Maquina == maquinasProd); gv.DataBind(); gv.HeaderStyle.BackColor = System.Drawing.Color.Blue; gv.HeaderStyle.ForeColor = System.Drawing.Color.White; gv.HeaderRow.Cells[0].Text = "Maquina"; gv.HeaderRow.Cells[1].Text = "OT"; gv.HeaderRow.Cells[2].Text = "NombreOT"; gv.HeaderRow.Cells[3].Text = "Pliego"; gv.HeaderRow.Cells[4].Text = "Cant. Planificado"; gv.HeaderRow.Cells[5].Text = "Cant. Producida"; gv.HeaderRow.Cells[6].Text = "Dif."; gv.HeaderRow.Cells[7].Text = "% "; if (Session["Usuario"].ToString().Trim() == "apaillaqueo" || Session["Usuario"].ToString().Trim() == "mandrade") { gv.HeaderRow.Cells[8].Visible = false; gv.HeaderRow.Cells[10].Visible = false; } else { gv.HeaderRow.Cells[8].Text = "Control Wip"; gv.HeaderRow.Cells[10].Text = "Operador"; } //gv.HeaderRow.Cells[8].Text = "Control Wip"; gv.HeaderRow.Cells[9].Text = "Papeles"; gv.HeaderRow.Cells[9].Visible = false; //gv.HeaderRow.Cells[10].Text = "Operador"; gv.HeaderRow.Cells[11].Visible = false; gv.HeaderRow.Cells[12].Visible = false; gv.HeaderRow.Cells[13].Visible = false; gv.HeaderRow.Cells[14].Visible = false; gv.HeaderRow.Cells[15].Visible = false; gv.HeaderRow.Cells[16].Visible = false; gv.HeaderRow.Cells[17].Visible = false; gv.HeaderRow.Cells[18].Visible = false; gv.HeaderRow.Cells[19].Visible = false; gv.HeaderRow.Cells[20].Visible = false; int CantPlanSobre = 0; int CantProdSobre = 0; int CantPlanBajo = 0; int CantProdBajo = 0; int TotalPlanificado = 0; for (int contador = 0; contador < gv.Rows.Count; contador++) { GridViewRow row = gv.Rows[contador]; if (Session["Usuario"].ToString().Trim() == "apaillaqueo" || Session["Usuario"].ToString().Trim() == "mandrade") { row.Cells[8].Visible = false; row.Cells[10].Visible = false; } else { row.Cells[8].Text = row.Cells[11].Text; row.Cells[10].Text = row.Cells[9].Text; } //row.Cells[8].Text = row.Cells[11].Text; //row.Cells[10].Text = row.Cells[9].Text; row.Cells[9].Visible = false; row.Cells[9].Text = row.Cells[18].Text; string Maquinagv = row.Cells[7].Text; row.Cells[7].Text = row.Cells[4].Text + "%"; row.Cells[6].Text = row.Cells[17].Text; row.Cells[5].Text = row.Cells[13].Text; row.Cells[4].Text = row.Cells[3].Text; row.Cells[3].Text = row.Cells[2].Text; row.Cells[2].Text = row.Cells[1].Text; row.Cells[1].Text = row.Cells[0].Text; row.Cells[0].Text = Maquinagv; row.Cells[11].Visible = false; row.Cells[12].Visible = false; row.Cells[13].Visible = false; row.Cells[14].Visible = false; row.Cells[15].Visible = false; row.Cells[16].Visible = false; row.Cells[17].Visible = false; row.Cells[18].Visible = false; row.Cells[19].Visible = false; row.Cells[20].Visible = false; TotalPlanificado += Convert.ToInt32(row.Cells[4].Text); if (Convert.ToInt32(row.Cells[5].Text) >= Convert.ToInt32(row.Cells[4].Text)) { CantPlanSobre += Convert.ToInt32(row.Cells[4].Text); CantProdSobre += Convert.ToInt32(row.Cells[5].Text); if (row.Cells[20].Text == "Rotativas") { TotalRotCantPlan += Convert.ToInt32(row.Cells[4].Text); TotalRotCantPlanSobre += Convert.ToInt32(row.Cells[4].Text); TotalRotCantProdSobre += Convert.ToInt32(row.Cells[5].Text); } else { TotalPlaCantPlan += Convert.ToInt32(row.Cells[4].Text); TotalPlaCantPlanSobre += Convert.ToInt32(row.Cells[4].Text); TotalPlaCantProdSobre += Convert.ToInt32(row.Cells[5].Text); } } else { if (row.Cells[20].Text == "Rotativas") { TotalRotCantPlan += Convert.ToInt32(row.Cells[4].Text); CantPlanBajo += Convert.ToInt32(row.Cells[4].Text); TotalRotCantPlanBajo += Convert.ToInt32(row.Cells[4].Text); CantProdBajo += Convert.ToInt32(row.Cells[5].Text); TotalRotCantProdBajo += Convert.ToInt32(row.Cells[5].Text); } else { TotalPlaCantPlan += Convert.ToInt32(row.Cells[4].Text); CantPlanBajo += Convert.ToInt32(row.Cells[4].Text); TotalPlaCantPlanBajo += Convert.ToInt32(row.Cells[4].Text); CantProdBajo += Convert.ToInt32(row.Cells[5].Text); TotalPlaCantProdBajo += Convert.ToInt32(row.Cells[5].Text); } } } string CantidadDif = (CantProdSobre - CantPlanSobre).ToString(); string PorcenProd = (Convert.ToDouble(Convert.ToDouble(CantidadDif) / Convert.ToDouble(CantPlanSobre)) * 100).ToString("N2") + "%"; Label TablaMaquinaTotal = new Label(); string Negativo = ""; if (CantPlanBajo > 0) { string CantidadDifNeg = (CantProdBajo - CantPlanBajo).ToString(); string PorcenProdNeg = (Convert.ToDouble(Convert.ToDouble(CantidadDifNeg) / Convert.ToDouble(CantPlanBajo)) * 100).ToString("N2") + "%"; Negativo = "<tr><td colspan ='8'></td><td style='border:1px solid black;'>Cant. Plan. Bajo</td>" + "<td style='border:1px solid black;'>" + CantPlanBajo.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Prod. Bajo</td>" + "<td style='border:1px solid black;'>" + CantProdBajo.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Diferencia Bajo</td>" + "<td style='border:1px solid black;'>" + CantidadDifNeg + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>% Bajo</td>" + "<td style='border:1px solid black;'>" + PorcenProdNeg + "</td></tr>"; } TablaMaquinaTotal.Text = "<br/><div align='right'><table><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Total Cant. Plan.</td>" + "<td style='border:1px solid black;'>" + TotalPlanificado.ToString() + "</div></td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Plan. Sobre</td>" + "<td style='border:1px solid black;'>" + CantPlanSobre.ToString() + "</div></td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Prod. Sobre</td>" + "<td style='border:1px solid black;'>" + CantProdSobre.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Diferencia Sobre</td>" + "<td style='border:1px solid black;'>" + CantidadDif + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>% Sobre</td>" + "<td style='border:1px solid black;'>" + PorcenProd.Replace("NaN", "0") + "</td></tr>" + Negativo + "</table></div>"; Label Maquina1 = new Label(); if (contado == 0) { Maquina1.Text = "<div align='left'>" + maquinasProd + " </div><br/>"; } else { Maquina1.Text = "<br/><div align='left'>" + maquinasProd + " </div><br/>"; } form.Controls.Add(Maquina1); form.Controls.Add(gv); form.Controls.Add(TablaMaquinaTotal); contado++; } #endregion Label TablaMaquinaRot = new Label(); TotalRotCantDifSobre = (TotalRotCantProdSobre - TotalRotCantPlanSobre); RotPorceCantDifSobre = Convert.ToDouble(Convert.ToDouble(TotalRotCantDifSobre) / Convert.ToDouble(TotalRotCantPlanSobre)) * 100; TotalRotCantDifBajo = (TotalRotCantPlanBajo - TotalRotCantProdBajo); string RotNegativoBajo = ""; if (TotalRotCantDifBajo > 0) { RotPorceCantDifBajo = Convert.ToDouble(Convert.ToDouble(TotalRotCantDifBajo) / Convert.ToDouble(TotalRotCantPlanBajo)) * 100; RotNegativoBajo = "<tr><td colspan ='8'></td><td style='border:1px solid black;'>Cant. Plan. Bajo</td>" + "<td style='border:1px solid black;'>" + TotalRotCantPlanBajo.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Prod. Bajo</td>" + "<td style='border:1px solid black;'>" + TotalRotCantProdBajo.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Diferencia Bajo</td>" + "<td style='border:1px solid black;'>" + TotalRotCantDifBajo.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>% Bajo</td>" + "<td style='border:1px solid black;'>" + RotPorceCantDifBajo.ToString() + "%</td></tr>"; } TablaMaquinaRot.Text = "<br/><br/><br/><div align='right'><table><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'colspan ='2'>Rotativa</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Total Cant. Plan.</td>" + "<td style='border:1px solid black;'>" + TotalRotCantPlan.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Plan. Sobre</td>" + "<td style='border:1px solid black;'>" + TotalRotCantPlanSobre.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Prod. Sobre</td>" + "<td style='border:1px solid black;'>" + TotalRotCantProdSobre.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Diferencia Sobre</td>" + "<td style='border:1px solid black;'>" + TotalRotCantDifSobre + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>% Sobre</td>" + "<td style='border:1px solid black;'>" + RotPorceCantDifSobre.ToString("N2").Replace("NaN", "0") + "%</td></tr>" + RotNegativoBajo + "</table></div>"; form.Controls.Add(TablaMaquinaRot); Label TablaMaquinaPla = new Label(); TotalPlaCantDifSobre = (TotalPlaCantProdSobre - TotalPlaCantPlanSobre); TotalPlaCantDifbajo = (TotalPlaCantPlanBajo - TotalPlaCantProdBajo); PlaPorceCantDifSobre = Convert.ToDouble(Convert.ToDouble(TotalPlaCantDifSobre) / Convert.ToDouble(TotalPlaCantPlanSobre)) * 100; string PlaNegativoBajo = ""; if (TotalPlaCantDifbajo > 0) { PlaPorceCantDifBajo = Convert.ToDouble(Convert.ToDouble(TotalPlaCantDifbajo) / Convert.ToDouble(TotalPlaCantPlanBajo)) * 100; PlaNegativoBajo = "<tr><td colspan ='8'></td><td style='border:1px solid black;'>Cant. Plan. Bajo</td>" + "<td style='border:1px solid black;'>" + TotalPlaCantPlanBajo.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Prod. Bajo</td>" + "<td style='border:1px solid black;'>" + TotalPlaCantProdBajo.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Diferencia Bajo</td>" + "<td style='border:1px solid black;'>" + TotalPlaCantDifbajo.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>% Bajo</td>" + "<td style='border:1px solid black;'>" + PlaPorceCantDifBajo.ToString() + "%</td></tr>"; } TablaMaquinaPla.Text = "<br/><div align='right'><table><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;' colspan ='2'>Plana</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Total Cant. Plan.</td>" + // colspan ='2' "<td style='border:1px solid black;'>" + TotalPlaCantPlan.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Plan. Sobre</td>" + // colspan ='2' "<td style='border:1px solid black;'>" + TotalPlaCantPlanSobre.ToString() + "</div></td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Cant. Prod. Sobre</td>" + "<td style='border:1px solid black;'>" + TotalPlaCantProdSobre.ToString() + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>Diferencia Sobre</td>" + "<td style='border:1px solid black;'>" + TotalPlaCantDifSobre + "</td></tr><tr>" + "<td colspan ='8'></td><td style='border:1px solid black;'>% Sobre</td>" + "<td style='border:1px solid black;'>" + PlaPorceCantDifSobre.ToString("N2") + "%</td></tr>" + PlaNegativoBajo + "</table></div>"; form.Controls.Add(TablaMaquinaPla); pageToRender.Controls.Add(form); response.Clear(); response.Buffer = true; response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment;filename=" + nameReport + ".xls"); response.Charset = "UTF-8"; response.ContentEncoding = Encoding.Default; pageToRender.RenderControl(htw); response.Write(sw.ToString()); response.End(); }
public void OnBeginRequest(object s, EventArgs e) { _forumId = -1; _tabId = -1; _moduleId = -1; _topicId = -1; _page = 1; _contentId = -1; _archived = 0; _forumgroupId = -1; _mainSettings = null; _categoryId = -1; _tagId = -1; HttpApplication app = (HttpApplication)s; HttpServerUtility Server = app.Server; HttpRequest Request = app.Request; HttpResponse Response = app.Response; string requestedPath = app.Request.Url.AbsoluteUri; HttpContext Context = ((HttpApplication)s).Context; int PortalId = -1; DotNetNuke.Entities.Portals.PortalAliasInfo objPortalAliasInfo = null; string sUrl = HttpContext.Current.Request.RawUrl.Replace("http://", string.Empty).Replace("https://", string.Empty); objPortalAliasInfo = PortalAliasController.Instance.GetPortalAlias(HttpContext.Current.Request.Url.Host); if (Request.RawUrl.ToLowerInvariant().Contains("404.aspx")) { string sEx = ".jpg,.gif,.png,.swf,.js,.css,.html,.htm,desktopmodules,portals,.ashx,.ico,.txt,.doc,.docx,.pdf,.xml,.xls,.xlsx,.ppt,.pptx,.csv,.zip,.asmx,.aspx"; foreach (string sn in sEx.Split(',')) { if (sUrl.Contains(sn)) { // IO.File.AppendAllText(sPath, Request.RawUrl & "165<br />") return; } } } if (Request.Url.LocalPath.ToLower().Contains("scriptresource.axd") || Request.Url.LocalPath.ToLower().Contains("webresource.axd") || Request.Url.LocalPath.ToLower().Contains("viewer.aspx") || Request.Url.LocalPath.ToLower().Contains("cb.aspx") || Request.Url.LocalPath.ToLower().Contains("filesupload.aspx") || Request.Url.LocalPath.ToLower().Contains(".gif") || Request.Url.LocalPath.ToLower().Contains(".jpg") || Request.Url.LocalPath.ToLower().Contains(".css") || Request.Url.LocalPath.ToLower().Contains(".png") || Request.Url.LocalPath.ToLower().Contains(".swf") || Request.Url.LocalPath.ToLower().Contains(".htm") || Request.Url.LocalPath.ToLower().Contains(".html") || Request.Url.LocalPath.ToLower().Contains(".ashx") || Request.Url.LocalPath.ToLower().Contains(".cur") || Request.Url.LocalPath.ToLower().Contains(".ico") || Request.Url.LocalPath.ToLower().Contains(".txt") || Request.Url.LocalPath.ToLower().Contains(".pdf") || Request.Url.LocalPath.ToLower().Contains(".xml") || Request.Url.LocalPath.ToLower().Contains("/portals/") || Request.Url.LocalPath.ToLower().Contains("/desktopmodules/") || Request.Url.LocalPath.ToLower().Contains("evexport.aspx") || Request.Url.LocalPath.ToLower().Contains("signupjs.aspx") || Request.Url.LocalPath.ToLower().Contains("evsexport.aspx") || Request.Url.LocalPath.ToLower().Contains("fbcomm.aspx") || Request.Url.LocalPath.ToLower().Contains(".aspx") || Request.Url.LocalPath.ToLower().Contains(".js")) { return; } if (Request.Url.LocalPath.ToLower().Contains("install.aspx") || Request.Url.LocalPath.ToLower().Contains("installwizard.aspx") || Request.Url.LocalPath.ToLower().Contains("captcha.aspx") || Request.RawUrl.Contains("viewer.aspx") || Request.RawUrl.Contains("blank.html") || Request.RawUrl.Contains("default.htm") || Request.RawUrl.Contains("autosuggest.aspx")) { return; } PortalId = objPortalAliasInfo.PortalID; string searchURL = sUrl; searchURL = searchURL.Replace(objPortalAliasInfo.HTTPAlias, string.Empty); if (searchURL.Length < 2) { return; } string query = string.Empty; if (searchURL.Contains("?")) { query = searchURL.Substring(searchURL.IndexOf("?")); searchURL = searchURL.Substring(0, searchURL.IndexOf("?") - 1); } string newSearchURL = string.Empty; foreach (string up in searchURL.Split('/')) { if (!(string.IsNullOrEmpty(up))) { if (!(SimulateIsNumeric.IsNumeric(up))) { newSearchURL += up + "/"; } } } bool canContinue = false; Data.Common db = new Data.Common(); string tagName = string.Empty; string catName = string.Empty; if (newSearchURL.Contains("/category/") || newSearchURL.Contains("/tag/")) { if (newSearchURL.Contains("/category/")) { string cat = "/category/"; int iEnd = newSearchURL.IndexOf("/", newSearchURL.IndexOf(cat) + cat.Length + 1); string catString = newSearchURL.Substring(newSearchURL.IndexOf(cat), iEnd - newSearchURL.IndexOf(cat)); catName = catString.Replace(cat, string.Empty); catName = catName.Replace("/", string.Empty); newSearchURL = newSearchURL.Replace(catString, string.Empty); } if (newSearchURL.Contains("/tag/")) { string tag = "/tag/"; int iEnd = newSearchURL.IndexOf("/", newSearchURL.IndexOf(tag) + tag.Length + 1); string tagString = newSearchURL.Substring(newSearchURL.IndexOf(tag), iEnd - newSearchURL.IndexOf(tag)); tagName = tagString.Replace(tag, string.Empty); tagName = tagName.Replace("/", string.Empty); newSearchURL = newSearchURL.Replace(tagString, string.Empty); } } if ((sUrl.Contains("afv") && sUrl.Contains("post")) | (sUrl.Contains("afv") && sUrl.Contains("confirmaction")) | (sUrl.Contains("afv") && sUrl.Contains("sendto")) | (sUrl.Contains("afv") && sUrl.Contains("modreport")) | (sUrl.Contains("afv") && sUrl.Contains("search")) | sUrl.Contains("dnnprintmode") || sUrl.Contains("asg") || (sUrl.Contains("afv") && sUrl.Contains("modtopics"))) { return; } try { using (IDataReader dr = db.URLSearch(PortalId, newSearchURL)) { while (dr.Read()) { _tabId = int.Parse(dr["TabID"].ToString()); _moduleId = int.Parse(dr["ModuleId"].ToString()); _forumgroupId = int.Parse(dr["ForumGroupId"].ToString()); _forumId = int.Parse(dr["ForumId"].ToString()); _topicId = int.Parse(dr["TopicId"].ToString()); _archived = int.Parse(dr["Archived"].ToString()); _otherId = int.Parse(dr["OtherId"].ToString()); _urlType = int.Parse(dr["UrlType"].ToString()); canContinue = true; } dr.Close(); } } catch (Exception ex) { } if (!(string.IsNullOrEmpty(catName))) { _categoryId = db.Tag_GetIdByName(PortalId, _moduleId, catName, true); _otherId = _categoryId; _urlType = 2; } if (!(string.IsNullOrEmpty(tagName))) { _tagId = db.Tag_GetIdByName(PortalId, _moduleId, tagName, false); _otherId = _tagId; _urlType = 3; } if (_archived == 1) { sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1); if (!(string.IsNullOrEmpty(sUrl))) { string sHost = objPortalAliasInfo.HTTPAlias; if (sUrl.StartsWith("/")) { sUrl = sUrl.Substring(1); } if (!(sHost.EndsWith("/"))) { sHost += "/"; } sUrl = sHost + sUrl; if (!(sUrl.EndsWith("/"))) { sUrl += "/"; } if (!(sUrl.StartsWith("http"))) { if (Request.IsSecureConnection) { sUrl = "https://" + sUrl; } else { sUrl = "http://" + sUrl; } } Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", sUrl); Response.End(); } } if (_moduleId > 0) { Entities.Modules.ModuleController objModules = new Entities.Modules.ModuleController(); SettingsInfo objSettings = new SettingsInfo(); objSettings.MainSettings = objModules.GetModuleSettings(_moduleId); _mainSettings = objSettings; // DataCache.MainSettings(_moduleId) } if (_mainSettings == null) { return; } if (!_mainSettings.URLRewriteEnabled) { return; } if (!canContinue && (Request.RawUrl.Contains(ParamKeys.TopicId) || Request.RawUrl.Contains(ParamKeys.ForumId) || Request.RawUrl.Contains(ParamKeys.GroupId))) { sUrl = HandleOldUrls(Request.RawUrl, objPortalAliasInfo.HTTPAlias); if (!(string.IsNullOrEmpty(sUrl))) { if (!(sUrl.StartsWith("http"))) { if (Request.IsSecureConnection) { sUrl = "https://" + sUrl; } else { sUrl = "http://" + sUrl; } } Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", sUrl); Response.End(); } } if (!canContinue) { string topicUrl = string.Empty; if (newSearchURL.EndsWith("/")) { newSearchURL = newSearchURL.Substring(0, newSearchURL.Length - 1); } if (newSearchURL.Contains("/")) { topicUrl = newSearchURL.Substring(newSearchURL.LastIndexOf("/")); } topicUrl = topicUrl.Replace("/", string.Empty); if (!(string.IsNullOrEmpty(topicUrl))) { Data.Topics topicsDb = new Data.Topics(); _topicId = topicsDb.TopicIdByUrl(PortalId, _moduleId, topicUrl.ToLowerInvariant()); if (_topicId > 0) { sUrl = db.GetUrl(_moduleId, _forumgroupId, _forumId, _topicId, _userId, -1); } else { sUrl = string.Empty; } if (!(string.IsNullOrEmpty(sUrl))) { string sHost = objPortalAliasInfo.HTTPAlias; if (sHost.EndsWith("/") && sUrl.StartsWith("/")) { sUrl = sHost.Substring(0, sHost.Length - 1) + sUrl; } else if (!(sHost.EndsWith("/")) && !(sUrl.StartsWith("/"))) { sUrl = sHost + "/" + sUrl; } else { sUrl = sHost + sUrl; } if (sUrl.StartsWith("/")) { sUrl = sUrl.Substring(1); } if (!(sUrl.StartsWith("http"))) { if (Request.IsSecureConnection) { sUrl = "https://" + sUrl; } else { sUrl = "http://" + sUrl; } } if (!(string.IsNullOrEmpty(sUrl))) { Response.Clear(); Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", sUrl); Response.End(); } } } } if (canContinue) { if (searchURL != newSearchURL) { string urlTail = searchURL.Replace(newSearchURL, string.Empty); if (urlTail.StartsWith("/")) { urlTail = urlTail.Substring(1); } if (urlTail.EndsWith("/")) { urlTail = urlTail.Substring(0, urlTail.Length - 1); } if (urlTail.Contains("/")) { urlTail = urlTail.Substring(0, urlTail.IndexOf("/") - 1); } if (SimulateIsNumeric.IsNumeric(urlTail)) { _page = Convert.ToInt32(urlTail); } } string sPage = string.Empty; sPage = "&afpg=" + _page.ToString(); string qs = string.Empty; if (sUrl.Contains("?")) { qs = "&" + sUrl.Substring(sUrl.IndexOf("?") + 1); } string catQS = string.Empty; if (_categoryId > 0) { catQS = "&act=" + _categoryId.ToString(); } string sendTo = string.Empty; if ((_topicId > 0) || (_forumId > 0) || (_forumgroupId > 0)) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + (_forumgroupId > 0 ? "&afg=" + _forumgroupId : string.Empty) + (_forumId > 0 ? "&aff=" + _forumId : string.Empty) + (_topicId > 0 ? "&aft=" + _topicId : string.Empty) + sPage + qs + ((_forumgroupId > 0 || _forumId > 0) ? catQS : string.Empty)); } else if (_urlType == 2 && _otherId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&act=" + _otherId + sPage + qs); } else if (_urlType == 3 && _otherId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=tags&aftg=" + _otherId + sPage + qs); } else if (_urlType == 1) { string v = string.Empty; switch (_otherId) { case 1: v = "unanswered"; break; case 2: v = "notread"; break; case 3: v = "mytopics"; break; case 4: v = "activetopics"; break; case 5: v = "afprofile"; break; } sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + "&afv=grid&afgt=" + v + sPage + qs); } else if (_tabId > 0) { sendTo = ResolveUrl(app.Context.Request.ApplicationPath, "~/default.aspx?tabid=" + _tabId + sPage + qs); } RewriteUrl(app.Context, sendTo); } }
private static void SetHeadersAndContentType(HttpResponse response, string contentType, string attachment) { response.AddHeader("Pragma", "public"); response.AddHeader("content-disposition", attachment); response.ContentType = contentType; }
public override void SendResponse(HttpResponse response) { this.CheckConnector(); response.ClearHeaders(); response.Clear(); response.ContentType = "application/octet-stream"; try { this.CheckRequest(); } catch (ConnectorException connectorException) { response.AddHeader("X-CKFinder-Error", (connectorException.Number).ToString()); if (connectorException.Number == Errors.FolderNotFound) { response.StatusCode = 404; } else { response.StatusCode = 403; } response.End(); return; } catch { response.AddHeader("X-CKFinder-Error", ((int)Errors.Unknown).ToString()); response.StatusCode = 403; response.End(); return; } if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileView)) { response.StatusCode = 403; response.End(); return; } string fileName = HttpContext.Current.Request["FileName"]; string filePath = System.IO.Path.Combine(this.CurrentFolder.ServerPath, fileName); if (!this.CurrentFolder.ResourceTypeInfo.CheckExtension(System.IO.Path.GetExtension(fileName))) { response.StatusCode = 403; response.End(); return; } if (!System.IO.File.Exists(filePath) || Config.Current.CheckIsHiddenFile(fileName)) { response.AddHeader("Content-Disposition", "attachment; filename=\"File not found - Please refresh and try again\""); response.StatusCode = 404; response.End(); return; } response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName.Replace("\"", "\\\"") + "\""); // Buffer to read 10K bytes in chunk: byte[] aBuffer = new Byte[10000]; System.IO.Stream oStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: long iDataToRead = oStream.Length; // Read the bytes. while (iDataToRead > 0) { // Verify that the client is connected. if (response.IsClientConnected) { // Read the data in buffer. int iLength = oStream.Read(aBuffer, 0, 10000); // Write the data to the current output stream. response.OutputStream.Write(aBuffer, 0, iLength); // Flush the data to the HTML output. response.Flush(); aBuffer = new Byte[10000]; iDataToRead = iDataToRead - iLength; } else { //prevent infinite loop if user disconnects iDataToRead = -1; } } response.End(); }
/// <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(); } } }
protected void cgvActivityItems_RowCommand(object sender, GridViewCommandEventArgs e) { try { if (e.CommandName == "download") { //LinkButton lnkdownload = (LinkButton)e.CommandSource; //GridViewRow gvrow = lnkdownload.NamingContainer as GridViewRow; ////string fileName = gvNRCore.DataKeys[gvrow.RowIndex].Value.ToString(); //string filePath = "~/Upload/ApoDocuments/" + lnkdownload.Text; //Response.ContentType = "application/octet-stream"; //Response.AddHeader("Content-Disposition", "attachment;filename=\"" + lnkdownload.Text + "\""); //Response.TransmitFile(Server.MapPath(filePath)); //Response.End(); //LinkButton lnkdownload = (LinkButton)e.CommandSource; //GridViewRow gvrow = lnkdownload.NamingContainer as GridViewRow; ////string fileName = cgvActivityItems.DataKeys[gvrow.RowIndex].Value.ToString(); //if (lnkdownload.Text.ToUpper().Contains(".XLS") || lnkdownload.Text.ToUpper().Contains(".XLSX")) //{ // string filePath = "~/Upload/ApoDocuments/" + lnkdownload.Text; // Response.AddHeader("Content-Type", "application/Excel"); // Response.ContentType = "application/vnd.ms-excel"; // Response.AddHeader("Content-Disposition", "attachment;filename=\"" + lnkdownload.Text + "\""); // Response.TransmitFile(Server.MapPath(filePath)); // Response.End(); //} LinkButton lbtnDocumentFile = (LinkButton)e.CommandSource; GridViewRow gvrow = lbtnDocumentFile.NamingContainer as GridViewRow; //string filePath = "~/Upload/ApoDocuments/"; if (lbtnDocumentFile.Text != string.Empty) { WebClient req = new WebClient(); HttpResponse response = HttpContext.Current.Response; //filePath = filePath + lbtnDocumentFile.Text; string filePath = "~/Upload/ApoDocuments/" + lbtnDocumentFile.Text; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.Buffer = true; response.AddHeader("Content-Disposition", "attachment;filename='" + lbtnDocumentFile.Text + "'"); byte[] data = req.DownloadData(Server.MapPath(filePath)); response.BinaryWrite(data); //UpdatePanel2.Update(); Response.Flush(); response.End(); } } } catch (FileNotFoundException ex) { string strInvalid = ex.Message; return; } }
internal override void RewriteUrl(object sender, EventArgs e) { var app = (HttpApplication)sender; HttpServerUtility server = app.Server; HttpRequest request = app.Request; HttpResponse response = app.Response; HttpContext context = app.Context; string requestedPath = app.Request.Url.AbsoluteUri; if (RewriterUtils.OmitFromRewriteProcessing(request.Url.LocalPath)) { return; } //'Carry out first time initialization tasks Initialize.Init(app); if (!Initialize.ProcessHttpModule(request, false, false)) { return; } //URL validation //check for ".." escape characters commonly used by hackers to traverse the folder tree on the server //the application should always use the exact relative location of the resource it is requesting var strURL = request.Url.AbsolutePath; var strDoubleDecodeURL = server.UrlDecode(server.UrlDecode(request.RawUrl)) ?? ""; if (Globals.FileEscapingRegex.Match(strURL).Success || Globals.FileEscapingRegex.Match(strDoubleDecodeURL).Success) { DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request); } try { //fix for ASP.NET canonicalization issues http://support.microsoft.com/?kbid=887459 if ((request.Path.IndexOf("\\", StringComparison.Ordinal) >= 0 || Path.GetFullPath(request.PhysicalPath) != request.PhysicalPath)) { DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request); } } catch (Exception exc) { //DNN 5479 //request.physicalPath throws an exception when the path of the request exceeds 248 chars. //example to test: http://localhost/dotnetnuke_2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/default.aspx Logger.Error(exc); } String domainName; RewriteUrl(app, out domainName); //blank DomainName indicates RewriteUrl couldn't locate a current portal //reprocess url for portal alias if auto add is an option if (domainName == "" && CanAutoAddPortalAlias()) { domainName = Globals.GetDomainName(app.Request, true); } //from this point on we are dealing with a "standard" querystring ( ie. http://www.domain.com/default.aspx?tabid=## ) //if the portal/url was succesfully identified int tabId = Null.NullInteger; int portalId = Null.NullInteger; string portalAlias = null; PortalAliasInfo portalAliasInfo = null; bool parsingError = false; // get TabId from querystring ( this is mandatory for maintaining portal context for child portals ) if (!string.IsNullOrEmpty(request.QueryString["tabid"])) { if (!Int32.TryParse(request.QueryString["tabid"], out tabId)) { tabId = Null.NullInteger; parsingError = true; } } // get PortalId from querystring ( this is used for host menu options as well as child portal navigation ) if (!string.IsNullOrEmpty(request.QueryString["portalid"])) { if (!Int32.TryParse(request.QueryString["portalid"], out portalId)) { portalId = Null.NullInteger; parsingError = true; } } if (parsingError) { //The tabId or PortalId are incorrectly formatted (potential DOS) DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request); } try { //alias parameter can be used to switch portals if (request.QueryString["alias"] != null) { // check if the alias is valid string childAlias = request.QueryString["alias"]; if (!Globals.UsePortNumber()) { childAlias = childAlias.Replace(":" + request.Url.Port, ""); } if (PortalAliasController.Instance.GetPortalAlias(childAlias) != null) { //check if the domain name contains the alias if (childAlias.IndexOf(domainName, StringComparison.OrdinalIgnoreCase) == -1) { //redirect to the url defined in the alias response.Redirect(Globals.GetPortalDomainName(childAlias, request, true), true); } else //the alias is the same as the current domain { portalAlias = childAlias; } } } //PortalId identifies a portal when set if (portalAlias == null) { if (portalId != Null.NullInteger) { portalAlias = PortalAliasController.GetPortalAliasByPortal(portalId, domainName); } } //TabId uniquely identifies a Portal if (portalAlias == null) { if (tabId != Null.NullInteger) { //get the alias from the tabid, but only if it is for a tab in that domain portalAlias = PortalAliasController.GetPortalAliasByTab(tabId, domainName); if (String.IsNullOrEmpty(portalAlias)) { //if the TabId is not for the correct domain //see if the correct domain can be found and redirect it portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(domainName); if (portalAliasInfo != null && !request.Url.LocalPath.ToLower().EndsWith("/linkclick.aspx")) { if (app.Request.Url.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) { strURL = "https://" + portalAliasInfo.HTTPAlias.Replace("*.", ""); } else { strURL = "http://" + portalAliasInfo.HTTPAlias.Replace("*.", ""); } if (strURL.IndexOf(domainName, StringComparison.InvariantCultureIgnoreCase) == -1) { strURL += app.Request.Url.PathAndQuery; } response.Redirect(strURL, true); } } } } //else use the domain name if (String.IsNullOrEmpty(portalAlias)) { portalAlias = domainName; } //using the DomainName above will find that alias that is the domainname portion of the Url //ie. dotnetnuke.com will be found even if zzz.dotnetnuke.com was entered on the Url portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias); if (portalAliasInfo != null) { portalId = portalAliasInfo.PortalID; } //if the portalid is not known if (portalId == Null.NullInteger) { bool autoAddPortalAlias = CanAutoAddPortalAlias(); if (!autoAddPortalAlias && !request.Url.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) { // allows requests for aspx pages in custom folder locations to be processed return; } if (autoAddPortalAlias) { AutoAddAlias(context); } } } catch (ThreadAbortException exc) { //Do nothing if Thread is being aborted - there are two response.redirect calls in the Try block Logger.Debug(exc); } catch (Exception ex) { //500 Error - Redirect to ErrorPage Logger.Error(ex); strURL = "~/ErrorPage.aspx?status=500&error=" + server.UrlEncode(ex.Message); HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer(strURL); } if (portalId != -1) { //load the PortalSettings into current context var portalSettings = new PortalSettings(tabId, portalAliasInfo); app.Context.Items.Add("PortalSettings", portalSettings); // load PortalSettings and HostSettings dictionaries into current context // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way app.Context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalId)); app.Context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary()); if (portalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.Redirect && portalAliasInfo != null && !portalAliasInfo.IsPrimary && !string.IsNullOrWhiteSpace(portalSettings.DefaultPortalAlias) // don't redirect if no primary alias is defined ) { //Permanently Redirect response.StatusCode = 301; var redirectAlias = Globals.AddHTTP(portalSettings.DefaultPortalAlias); var checkAlias = Globals.AddHTTP(portalAliasInfo.HTTPAlias); var redirectUrl = string.Concat(redirectAlias, request.RawUrl); if (redirectUrl.StartsWith(checkAlias, StringComparison.InvariantCultureIgnoreCase)) { redirectUrl = string.Concat(redirectAlias, redirectUrl.Substring(checkAlias.Length)); } response.AppendHeader("Location", redirectUrl); } //manage page URL redirects - that reach here because they bypass the built-in navigation //ie Spiders, saved favorites, hand-crafted urls etc if (!String.IsNullOrEmpty(portalSettings.ActiveTab.Url) && request.QueryString["ctl"] == null && request.QueryString["fileticket"] == null) { //Target Url string redirectUrl = portalSettings.ActiveTab.FullUrl; if (portalSettings.ActiveTab.PermanentRedirect) { //Permanently Redirect response.StatusCode = 301; response.AppendHeader("Location", redirectUrl); } else { //Normal Redirect response.Redirect(redirectUrl, true); } } //manage secure connections if (request.Url.AbsolutePath.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase)) { //request is for a standard page strURL = ""; //if SSL is enabled if (portalSettings.SSLEnabled) { //if page is secure and connection is not secure orelse ssloffload is enabled and server value exists if ((portalSettings.ActiveTab.IsSecure && !request.IsSecureConnection) && (IsSSLOffloadEnabled(request) == false)) { //switch to secure connection strURL = requestedPath.Replace("http://", "https://"); strURL = FormatDomain(strURL, portalSettings.STDURL, portalSettings.SSLURL); } } //if SSL is enforced if (portalSettings.SSLEnforced) { //if page is not secure and connection is secure if ((!portalSettings.ActiveTab.IsSecure && request.IsSecureConnection)) { //check if connection has already been forced to secure orelse ssloffload is disabled if (request.QueryString["ssl"] == null) { strURL = requestedPath.Replace("https://", "http://"); strURL = FormatDomain(strURL, portalSettings.SSLURL, portalSettings.STDURL); } } } //if a protocol switch is necessary if (!String.IsNullOrEmpty(strURL)) { if (strURL.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) { //redirect to secure connection response.RedirectPermanent(strURL); } else //when switching to an unsecure page, use a clientside redirector to avoid the browser security warning { response.Clear(); //add a refresh header to the response response.AddHeader("Refresh", "0;URL=" + strURL); //add the clientside javascript redirection script response.Write("<html><head><title></title>"); response.Write("<!-- <script language=\"javascript\">window.location.replace(\"" + strURL + "\")</script> -->"); response.Write("</head><body></body></html>"); //send the response response.End(); } } } } else { //alias does not exist in database //and all attempts to find another have failed //this should only happen if the HostPortal does not have any aliases //404 Error - Redirect to ErrorPage strURL = "~/ErrorPage.aspx?status=404&error=" + domainName; HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer(strURL); } if (app.Context.Items["FirstRequest"] != null) { app.Context.Items.Remove("FirstRequest"); //Process any messages in the EventQueue for the Application_Start_FirstRequest event EventQueueController.ProcessMessages("Application_Start_FirstRequest"); } }
public void ProcessRequest(HttpContext context) { var cnn = context.Request.QueryString["cnn"]; var mvx = new CMvx(); mvx.RegisterSingleton <IConfiguracionDeConexion, frmMainMenu.ConfiguracionDeConexion>(new frmMainMenu.ConfiguracionDeConexion(cnn)); mvx.RegisterType <IBaseDeDatosServicio, BaseDeDatosServicio>(); mvx.RegisterType <IManifiestoServicio, ManifiestoServicio>(); XLWorkbook workbook = new XLWorkbook(); IXLWorksheet worksheet = workbook.Worksheets.Add("Cargar Manifiesto"); worksheet.Protect("Mobility2016$$"); var servicio = mvx.Resolve <IManifiestoServicio>(); var templateExcel = servicio.GenerarColumnasParaTemplate(); int i = 1; foreach (var columna in templateExcel) { XLCellValues tipo = XLCellValues.Text; object defaultValue = string.Empty; if (columna.VALUE.Trim() == "Fecha visita") { tipo = XLCellValues.DateTime; defaultValue = DateTime.Now.Date; } else if (columna.VALUE == "Hora recomendada visita") { tipo = XLCellValues.TimeSpan; defaultValue = new TimeSpan(); } else if (columna.VALUE == "Cantidad") { tipo = XLCellValues.Number; defaultValue = 0; } else if (columna.VALUE == "Número documento") { tipo = XLCellValues.Number; defaultValue = 0; } else if (columna.VALUE == "GPS cliente") { tipo = XLCellValues.Text; defaultValue = ""; } for (int j = 2; j < 3; j++) { worksheet.Cell(j, i).DataType = tipo; worksheet.Cell(j, i).Value = defaultValue; } worksheet.Cell(1, i).DataType = XLCellValues.Text; worksheet.Cell(1, i).Value = columna.VALUE; worksheet.Cell(1, i).Style.Font.Bold = true; worksheet.Cell(1, i).Style.Fill.BackgroundColor = XLColor.BabyBlueEyes; worksheet.Cell(1, i).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center); worksheet.Column(i).Style.Protection.SetLocked(false); worksheet.Column(i).Width = 20; i++; } worksheet.Row(1).Style.Protection.SetLocked(true); MemoryStream s = (MemoryStream)GetStream(workbook); HttpResponse response = HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=Load_Manifest.xlsx;"); response.BinaryWrite(s.ToArray()); response.Flush(); response.End(); }
public static void exportHEDISSummary(string documentTitle, string documentDescription, int iHeight, int iWidth, DataSet ds, HttpResponse oResponse) { Document document = new Document(new iTextSharp.text.Rectangle(iWidth, iHeight), 25, 25, 65, 55); PdfWriter pdfDoc = PdfWriter.GetInstance(document, oResponse.OutputStream); //pdfDoc.PageEvent = new itextEvents(documentTitle, false, "Appointment"); document.Open(); /* Headers */ document.AddTitle(documentTitle); document.AddCreator("Tectical Management Inc."); document.AddKeywords("Document generated by Tectical Management Inc. online portal."); document.AddHeader("Company Name", "Tectical Management Inc."); document.AddHeader("Creation Date", DateTime.Now.ToLongDateString()); document.AddHeader("Creation Time", DateTime.Now.ToLongTimeString()); /* Creating cover page */ //create iTextSharp.text Image object using local image path iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\imgs\\pdf\\tmi.png"); logo.ScalePercent(60); PdfPTable pdfTabFooter = new PdfPTable(2); PdfPCell pdfCellRight = new PdfPCell(new Paragraph(documentTitle, new Font(Font.FontFamily.HELVETICA, 25, 1, new BaseColor(System.Drawing.Color.Black)))); PdfPCell pdfCellLeft = new PdfPCell(logo); pdfCellRight.HorizontalAlignment = Element.ALIGN_BOTTOM; pdfCellLeft.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellLeft.Border = 0; pdfCellRight.Border = 0; pdfTabFooter.AddCell(pdfCellLeft); pdfTabFooter.AddCell(pdfCellRight); pdfTabFooter.TotalWidth = document.PageSize.Width - 40; pdfTabFooter.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 10, pdfDoc.DirectContent); PdfPTable pdfTabChart = new PdfPTable(new float[] { 65, 5, 30 }); pdfTabChart.TotalWidth = 950; PdfPCell pdfCellTitle = new PdfPCell(new Paragraph("HEDIS Provider Summary", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.DarkGreen)))); PdfPCell pdfCellEmpty = new PdfPCell(); PdfPCell pdfCellTitle2 = new PdfPCell(); pdfCellTitle.Border = 0; pdfCellEmpty.Border = 0; pdfTabChart.AddCell(pdfCellTitle); pdfTabChart.AddCell(pdfCellEmpty); pdfTabChart.AddCell(pdfCellEmpty); DataTable dt = ds.Tables[0]; for (int i = 0; i < dt.Rows.Count; i++) { //30 *100/200 int iPercent = lib.cInt(Math.Ceiling(lib.cFloat(dt.Rows[i]["ConfirmedMeasures"]) * 100 / lib.cFloat(dt.Rows[i]["TotalQuestions"]))); iTextSharp.text.Image imBar1 = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\imgs\\pdf\\bar1.png"); imBar1.ScaleAbsoluteWidth(iPercent * 2); PdfPCell pdfCellText = new PdfPCell(new Paragraph(lib.cStr(dt.Rows[i]["Lastname"]) + " " + lib.cStr(dt.Rows[i]["Firstname"]) + "\n(" + lib.cStr(dt.Rows[i]["Vendor_ID"]) + ")", new Font(Font.FontFamily.HELVETICA, 12, 1, new BaseColor(System.Drawing.Color.Black)))); PdfPCell pdfCellValue = new PdfPCell(new Paragraph(iPercent.ToString() + "%", new Font(Font.FontFamily.HELVETICA, 10, 1, new BaseColor(System.Drawing.Color.Black)))); PdfPCell pdfCellImage = new PdfPCell(imBar1); pdfCellText.Border = 0; pdfCellValue.Border = 0; pdfCellImage.Border = 0; pdfTabChart.AddCell(pdfCellText); pdfTabChart.AddCell(pdfCellValue); pdfTabChart.AddCell(pdfCellImage); } document.Add(pdfTabChart); //Provider Measure Summary dt = ds.Tables[1]; string vendor = ""; for (int i = 0; i < dt.Rows.Count; i++) { if (vendor != lib.cStr(dt.Rows[i]["vendor_pk"])) { if (i != 0) { document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.DarkBlue)))); document.Add(pdfTabChart); } pdfTabChart = new PdfPTable(new float[] { 80, 5, 15 }); pdfTabChart.TotalWidth = 950; vendor = lib.cStr(dt.Rows[i]["vendor_pk"]); pdfCellTitle = new PdfPCell(new Paragraph(lib.cStr(dt.Rows[i]["Lastname"]) + " " + lib.cStr(dt.Rows[i]["Firstname"]) + " (" + lib.cStr(dt.Rows[i]["Vendor_ID"]) + ")", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.DarkBlue)))); pdfCellEmpty = new PdfPCell(); pdfCellTitle.Border = 0; pdfCellEmpty.Border = 0; pdfCellTitle.PaddingBottom = 5; pdfTabChart.AddCell(pdfCellTitle); pdfTabChart.AddCell(pdfCellEmpty); pdfTabChart.AddCell(pdfCellEmpty); } int iPercent = lib.cInt(Math.Ceiling(lib.cFloat(dt.Rows[i]["ConfirmedMeasures"]) * 100 / lib.cFloat(dt.Rows[i]["TotalQuestions"]))); iTextSharp.text.Image imBar1 = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\imgs\\pdf\\bar1.png"); imBar1.ScaleAbsoluteWidth(iPercent); PdfPCell pdfCellText = new PdfPCell(new Paragraph(lib.cStr(dt.Rows[i]["measure_description"]), new Font(Font.FontFamily.HELVETICA, 11, 1, new BaseColor(System.Drawing.Color.Black)))); PdfPCell pdfCellValue = new PdfPCell(new Paragraph(iPercent.ToString() + "%", new Font(Font.FontFamily.HELVETICA, 10, 1, new BaseColor(System.Drawing.Color.Black)))); PdfPCell pdfCellImage = new PdfPCell(imBar1); pdfCellText.Border = 0; pdfCellValue.Border = 0; pdfCellImage.Border = 0; pdfCellImage.Padding = 2; pdfTabChart.AddCell(pdfCellText); pdfTabChart.AddCell(pdfCellValue); pdfTabChart.AddCell(pdfCellImage); } if (vendor != "") { document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.DarkBlue)))); document.Add(pdfTabChart); } //Provider/Member Measuer Summary dt = ds.Tables[2]; string member = ""; for (int i = 0; i < dt.Rows.Count; i++) { if (member != lib.cStr(dt.Rows[i]["member_pk"]) + 'X' + lib.cStr(dt.Rows[i]["vendor_pk"])) { if (i != 0) { document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.DarkBlue)))); document.Add(pdfTabChart); } pdfTabChart = new PdfPTable(new float[] { 12, 84, 4 }); pdfTabChart.TotalWidth = 950; member = lib.cStr(dt.Rows[i]["member_pk"]) + 'X' + lib.cStr(dt.Rows[i]["vendor_pk"]); pdfCellTitle2 = new PdfPCell(new Paragraph("Provider: ", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.Black)))); pdfCellTitle = new PdfPCell(new Paragraph(lib.cStr(dt.Rows[i]["Lastname"]) + " " + lib.cStr(dt.Rows[i]["Firstname"]) + " (" + lib.cStr(dt.Rows[i]["Vendor_ID"]) + ")", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.DarkBlue)))); pdfCellEmpty = new PdfPCell(); pdfCellTitle.Border = 0; pdfCellEmpty.Border = 0; pdfCellTitle2.Border = 0; pdfCellTitle.PaddingBottom = 5; pdfTabChart.AddCell(pdfCellTitle2); pdfTabChart.AddCell(pdfCellTitle); pdfTabChart.AddCell(pdfCellEmpty); pdfCellTitle2 = new PdfPCell(new Paragraph("Member: ", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.Black)))); pdfCellTitle = new PdfPCell(new Paragraph(lib.cStr(dt.Rows[i]["MemberName"]) + " (" + lib.cStr(dt.Rows[i]["Member_ID"]) + ")", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.DarkRed)))); pdfCellEmpty = new PdfPCell(); pdfCellTitle.Border = 0; pdfCellEmpty.Border = 0; pdfCellTitle2.Border = 0; pdfCellTitle.PaddingBottom = 5; pdfTabChart.AddCell(pdfCellTitle2); pdfTabChart.AddCell(pdfCellTitle); pdfTabChart.AddCell(pdfCellEmpty); } //int iPercent = lib.cInt(Math.Ceiling(lib.cFloat(dt.Rows[i]["ConfirmedMeasures"]) * 100 / lib.cFloat(dt.Rows[i]["TotalQuestions"]))); PdfPCell pdfCellText = new PdfPCell(new Paragraph(lib.cStr(dt.Rows[i]["measure_description"]), new Font(Font.FontFamily.HELVETICA, 11, 1, new BaseColor(System.Drawing.Color.Black)))); PdfPCell pdfCellValue; if (lib.cInt(dt.Rows[i]["ConfirmedMeasures"]) == 1) { pdfCellValue = new PdfPCell(new Paragraph("YES", new Font(Font.FontFamily.HELVETICA, 10, 1, new BaseColor(System.Drawing.Color.Black)))); } else { pdfCellValue = new PdfPCell(new Paragraph("NO", new Font(Font.FontFamily.HELVETICA, 10, 1, new BaseColor(System.Drawing.Color.White)))); pdfCellValue.BackgroundColor = new BaseColor(System.Drawing.Color.DarkRed); } pdfCellEmpty = new PdfPCell(); pdfCellEmpty.Border = 0; pdfCellText.Border = 0; pdfCellValue.Border = 5; pdfCellValue.BorderColor = new BaseColor(System.Drawing.Color.White); pdfTabChart.AddCell(pdfCellEmpty); pdfTabChart.AddCell(pdfCellText); pdfTabChart.AddCell(pdfCellValue); } if (vendor != "") { document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 15, 1, new BaseColor(System.Drawing.Color.DarkBlue)))); document.Add(pdfTabChart); } document.Close(); oResponse.ContentType = "application/pdf"; oResponse.AddHeader("content-disposition", "attachment;filename=" + documentTitle.Replace(" ", "_").Replace(",", "") + ".pdf"); oResponse.End(); }
public static void Export(DataView vw, string sModuleName, string sExportFormat, string sExportRange, int nCurrentPage, int nPageSize, string[] arrID) { int nStartRecord = 0; int nEndRecord = vw.Count; switch (sExportRange) { case "Page": nStartRecord = nCurrentPage * nPageSize; nEndRecord = Math.Min(nStartRecord + nPageSize, vw.Count); break; case "Selected": { // 10/17/2006 Paul. There must be one selected record to continue. if (arrID == null) { L10N L10n = HttpContext.Current.Items["L10n"] as L10N; throw(new Exception(L10n.Term(".LBL_LISTVIEW_NO_SELECTED"))); } StringBuilder sbIDs = new StringBuilder(); int nCount = 0; foreach (string item in arrID) { if (nCount > 0) { sbIDs.Append(" or "); } sbIDs.Append("ID = \'" + item.Replace("\'", "\'\'") + "\'" + ControlChars.CrLf); nCount++; } //vw.RowFilter = "ID in (" + sbIDs.ToString() + ")"; // 11/03/2006 Paul. A filter might already exist, so make sure to maintain the existing filter. if (vw.RowFilter.Length > 0) { vw.RowFilter = " and (" + sbIDs.ToString() + ")"; } else { vw.RowFilter = sbIDs.ToString(); } nEndRecord = vw.Count; break; } } HttpResponse Response = HttpContext.Current.Response; StringBuilder sb = new StringBuilder(); switch (sExportFormat) { case "csv": Response.ContentType = "text/csv"; Response.AddHeader("Content-Disposition", "attachment;filename=" + sModuleName + ".csv"); ExportDelimited(Response.OutputStream, vw, sModuleName.ToLower(), nStartRecord, nEndRecord, ','); Response.End(); break; case "tab": Response.ContentType = "text/txt"; Response.AddHeader("Content-Disposition", "attachment;filename=" + sModuleName + ".txt"); ExportDelimited(Response.OutputStream, vw, sModuleName.ToLower(), nStartRecord, nEndRecord, '\t'); Response.End(); break; case "xml": Response.ContentType = "text/xml"; Response.AddHeader("Content-Disposition", "attachment;filename=" + sModuleName + ".xml"); ExportXml(Response.OutputStream, vw, sModuleName.ToLower(), nStartRecord, nEndRecord); Response.End(); break; //case "Excel": default: Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=" + sModuleName + ".xlb"); ExportExcel(Response.OutputStream, vw, sModuleName.ToLower(), nStartRecord, nEndRecord); Response.End(); break; } //vw.RowFilter = null; }
public static void exportDashboard(string project, string user, string channel, string title, HttpResponse oResponse) { Document document = new Document(new iTextSharp.text.Rectangle(1618, 1250), 80, 80, 20, 25); PdfWriter pdfDoc = PdfWriter.GetInstance(document, oResponse.OutputStream); document.Open(); /* Headers */ document.AddTitle(title); document.AddCreator("MedHealth Solutions."); document.AddKeywords("Document generated by MedHealth Solutions. online portal."); document.AddHeader("Company Name", "MedHealth Solutions."); document.AddHeader("Creation Date", DateTime.Now.ToLongDateString()); document.AddHeader("Creation Time", DateTime.Now.ToLongTimeString()); //create iTextSharp.text Image object using local image path iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\imgs\\pdf\\logo.png"); ////pdfDoc.Add(logo); //document.Add(logo); //////////////////////////////////////////////////////////////////////////// // Page 2 //////////////////////////////////////////////////////////////////////////// PdfPTable pdfTabHeader = new PdfPTable(2); PdfPCell pdfCellRight = new PdfPCell(new Paragraph("\n" + title, new Font(Font.FontFamily.HELVETICA, 40, 0))); PdfPCell pdfCellLeft = new PdfPCell(logo); pdfCellRight.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCellLeft.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellRight.Border = 0; pdfCellLeft.Border = 0; pdfTabHeader.AddCell(pdfCellLeft); pdfTabHeader.AddCell(pdfCellRight); pdfTabHeader.TotalWidth = document.PageSize.Width - 60; pdfTabHeader.WriteSelectedRows(0, -1, 30, document.PageSize.Height - 20, pdfDoc.DirectContent); PdfContentByte cb = pdfDoc.DirectContent; cb.MoveTo(1, pdfDoc.PageSize.Height - 115); cb.LineTo(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height - 115); cb.Stroke(); cb.MoveTo(1, 50); cb.LineTo(pdfDoc.PageSize.Width, 50); cb.Stroke(); PdfPTable pdfTabFooter = new PdfPTable(2); PdfPCell pdfCellRightF = new PdfPCell(new Paragraph("Printed on " + DateTime.Now.ToString("MM-dd-yyyy HH:mm"), new Font(Font.FontFamily.HELVETICA, 14, 0))); PdfPCell pdfCellLeftF = new PdfPCell(new Paragraph("©" + DateTime.Now.ToString("yyyy") + " MedHealth", new Font(Font.FontFamily.HELVETICA, 14, 0))); pdfCellRightF.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCellLeftF.HorizontalAlignment = Element.ALIGN_LEFT; pdfCellRightF.Border = 0; pdfCellLeftF.Border = 0; pdfTabFooter.AddCell(pdfCellLeftF); pdfTabFooter.AddCell(pdfCellRightF); pdfTabFooter.TotalWidth = document.PageSize.Width - 60; pdfTabFooter.WriteSelectedRows(0, -1, 25, 48, pdfDoc.DirectContent); document.Add(new Paragraph("\n\n\n", new Font(Font.FontFamily.HELVETICA, 25, 0))); if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RAP_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Retrospective Progress", new Font(Font.FontFamily.HELVETICA, 25, 0))); iTextSharp.text.Image imRAP = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RAP_" + project + "_" + user + "_" + channel + ".png")); document.Add(imRAP); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSBD_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Burn Down of Retrospective Pursuit", new Font(Font.FontFamily.HELVETICA, 25, 0))); iTextSharp.text.Image imRSBD = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSBD_" + project + "_" + user + "_" + channel + ".png")); document.Add(imRSBD); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCS_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Office Schedule and Contact Status", new Font(Font.FontFamily.HELVETICA, 25, 0))); document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 10, 0))); PdfPTable pdfOSCS = new PdfPTable(3); iTextSharp.text.Image imOSCS1 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCS_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfOSCS1 = new PdfPCell(imOSCS1); pdfOSCS1.Border = 0; pdfOSCS.AddCell(pdfOSCS1); if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCSD1_" + project + "_" + user + "_" + channel + ".png"))) { iTextSharp.text.Image imOSCS2 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCSD1_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfOSCS2 = new PdfPCell(imOSCS2); pdfOSCS2.Border = 0; pdfOSCS.AddCell(pdfOSCS2); } else { PdfPCell pdfOSCS2 = new PdfPCell(new Paragraph(" ")); pdfOSCS2.Border = 0; pdfOSCS.AddCell(pdfOSCS2); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCSD2_" + project + "_" + user + "_" + channel + ".png"))) { iTextSharp.text.Image imOSCS3 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\OSCSD2_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfOSCS3 = new PdfPCell(imOSCS3); pdfOSCS3.Border = 0; pdfOSCS.AddCell(pdfOSCS3); } else { PdfPCell pdfOSCS3 = new PdfPCell(new Paragraph(" ")); pdfOSCS3.Border = 0; pdfOSCS.AddCell(pdfOSCS3); } document.Add(pdfOSCS); } //////////////////////////////////////////////////////////////////////////// // Page 2 //////////////////////////////////////////////////////////////////////////// document.NewPage(); pdfTabHeader.WriteSelectedRows(0, -1, 30, document.PageSize.Height - 20, pdfDoc.DirectContent); cb.MoveTo(1, pdfDoc.PageSize.Height - 115); cb.LineTo(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height - 115); cb.Stroke(); cb.MoveTo(1, 50); cb.LineTo(pdfDoc.PageSize.Width, 50); cb.Stroke(); pdfTabFooter.WriteSelectedRows(0, -1, 25, 48, pdfDoc.DirectContent); document.Add(new Paragraph("\n\n\n", new Font(Font.FontFamily.HELVETICA, 25, 0))); if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\QA_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Coding Quality Assurance (QA)", new Font(Font.FontFamily.HELVETICA, 25, 0))); document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 10, 0))); PdfPTable pdfQA = new PdfPTable(2); iTextSharp.text.Image imQA1 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\QA_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfQA1 = new PdfPCell(imQA1); pdfQA1.Border = 0; pdfQA.AddCell(pdfQA1); if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\QAD_" + project + "_" + user + "_" + channel + ".png"))) { iTextSharp.text.Image imQA2 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\QAD_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfQA2 = new PdfPCell(imQA2); pdfQA2.Border = 0; pdfQA.AddCell(pdfQA2); } document.Add(pdfQA); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSVS_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Validation Status", new Font(Font.FontFamily.HELVETICA, 25, 0))); document.Add(new Paragraph(" ", new Font(Font.FontFamily.HELVETICA, 10, 0))); PdfPTable pdfRSVS = new PdfPTable(2); iTextSharp.text.Image imRSVS1 = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSVS_" + project + "_" + user + "_" + channel + ".png")); PdfPCell pdfRSVS1 = new PdfPCell(imRSVS1); pdfRSVS1.Border = 0; pdfRSVS.AddCell(pdfRSVS1); //if (File.Exists(HttpRuntime.AppDomainAppPath + "charts\\RSVD_" + project + "_" + user + "_" + channel + ".png")) //{ // iTextSharp.text.Image imRSVS2 = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "charts\\RSVD_" + project + "_" + user + "_" + channel + ".png"); // PdfPCell pdfRSVS2 = new PdfPCell(imRSVS2); // pdfRSVS2.Border = 0; // pdfRSVS.AddCell(pdfRSVS2); //} PdfPCell pdfRSVS2 = new PdfPCell(); for (int im = 0; im < 7; im++) { if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RSVD_" + im + "_" + project + "_" + user + "_" + channel + ".png"))) { iTextSharp.text.Image imRSVS2 = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "charts\\RSVD_" + im + "_" + project + "_" + user + "_" + channel + ".png"); pdfRSVS2.AddElement(imRSVS2); } } pdfRSVS2.Border = 0; pdfRSVS.AddCell(pdfRSVS2); document.Add(pdfRSVS); } if (File.Exists(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RS15H_" + project + "_" + user + "_" + channel + ".png"))) { document.Add(new Paragraph("Top 15 Validated HCC", new Font(Font.FontFamily.HELVETICA, 25, 0))); iTextSharp.text.Image imRS15H = iTextSharp.text.Image.GetInstance(Path.Combine(HttpRuntime.AppDomainAppPath, "charts\\RS15H_" + project + "_" + user + "_" + channel + ".png")); document.Add(imRS15H); } /* Closing and downloading the document*/ document.Close(); oResponse.ContentType = "application/pdf"; oResponse.AddHeader("content-disposition", "attachment;filename=" + title.Replace(" ", "_").Replace(",", "") + ".pdf"); oResponse.End(); }
public override async Task ProcessRequestAsync(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; byte[] data = null; string mediaName = ""; int frameId = request.IntOrZero("frame"); int contentId = request.IntOrZero("content"); int trace = request.IntOrZero("trace"); try { Video video = new Video(frameId); VideoAlternative va = new VideoAlternative(video, contentId); if (va.ContentId != 0) { data = await HttpRuntime.Cache.GetOrAddAbsoluteAsync( va.CacheKey, async (expire) => { expire.When = DateTime.Now.AddMinutes(video.CacheInterval); Content content = await Content.GetDataAsync(va.ContentId); if (content == null) { return(null); } mediaName = content.Name; return(content.Data); }); } } catch (Exception ex) { if (trace == 0) { throw new HttpException(500, ex.Message); } else { throw new HttpException(500, ex.ToString()); } } if (data == null) { throw new HttpException(404, "File is empty"); } else { string mimeType = null; try { if (null == (mimeType = MimeTypeParser.GetMimeTypeRaw(data))) { if (null == (mimeType = MimeTypeParser.GetMimeTypeFromRegistry(mediaName))) { if (null == (mimeType = MimeTypeParser.GetMimeTypeFromList(mediaName))) { mimeType = "application/octet-stream"; } } } } catch { mimeType = "application/octet-stream"; } response.ContentType = mimeType; response.AddHeader("Content-Disposition", string.Format( "attachment; filename=\"{0}\"", mediaName )); response.AddHeader("Content-Length", data.Length.ToString()); } response.BinaryWrite(data); response.Flush(); }
public static void prepareChaseListTable4PDF(DataTable[] dt, int is_one_page_per_patient, Document document, HttpResponse oResponse, string file_name, string documentTitle, PdfWriter oPdfWriter, int include_BAA) { iTextSharp.text.Image checkbox = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\imgs\\checkbox.png"); /* Tables */ for (int iTab = 0; iTab < dt.Length; iTab++) { if (is_one_page_per_patient == 0) { //With Effective Date //iTextSharp.text.pdf.PdfPTable tbl = new iTextSharp.text.pdf.PdfPTable(new float[] {5,5,13,13,40,12,12}); //Without effective date iTextSharp.text.pdf.PdfPTable tbl; if (dt[iTab].Columns.Count == 5) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 16, 16, 46, 17 }); } else if (dt[iTab].Columns.Count == 6) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 13, 13, 30, 12, 27 }); } else if (dt[iTab].Columns.Count == 7) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 13, 13, 30, 12, 15, 12 }); } else if (dt[iTab].Columns.Count == 8) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 15, 15, 24, 11, 10, 10, 10 }); } else if (dt[iTab].Columns.Count == 9) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 14, 14, 16, 11, 10, 10, 10, 10 }); } else { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 10, 10, 14, 11, 10, 10, 10, 10, 10 }); } tbl.WidthPercentage = 100; tbl.HeaderRows = 1; if (dt[iTab].TableName != "") { string[] arHeaders = dt[iTab].TableName.Split('~'); for (int iHeader = 0; iHeader < arHeaders.Length; iHeader++) { if (iHeader > 0) { PdfPCell objCellTitle; if (iHeader == 1) { objCellTitle = new PdfPCell(new Phrase(2, arHeaders[iHeader], new Font(Font.FontFamily.HELVETICA, 14, 1))); objCellTitle.PaddingTop = 10; } else { objCellTitle = new PdfPCell(new Phrase(2, arHeaders[iHeader], new Font(Font.FontFamily.HELVETICA, 13, 0))); objCellTitle.PaddingTop = 4; } objCellTitle.Colspan = dt[iTab].Columns.Count; objCellTitle.PaddingBottom = 5; objCellTitle.BorderWidth = 0; tbl.AddCell(objCellTitle); tbl.HeaderRows++; } } } for (int iCol = 0; iCol < dt[iTab].Columns.Count; iCol++) { PdfPCell objCell = new PdfPCell(new Phrase(2, dt[iTab].Columns[iCol].ColumnName, new Font(Font.FontFamily.HELVETICA, 14, 1))); objCell.Padding = 4; tbl.AddCell(objCell); } for (int iRow = 0; iRow < dt[iTab].Rows.Count; iRow++) { for (int iCol = 0; iCol < dt[iTab].Columns.Count; iCol++) { if (iCol == 0) { PdfPCell objCell = new PdfPCell(checkbox); objCell.Padding = 2; tbl.AddCell(objCell); } else { PdfPCell objCell = new PdfPCell(new Phrase(2, lib.cStr(dt[iTab].Rows[iRow][iCol]), new Font(Font.FontFamily.HELVETICA, 13))); objCell.Padding = 3; tbl.AddCell(objCell); } } } document.Add(tbl); if (is_one_page_per_patient == 1) { document.NewPage(); } } else { //************************************************** // One Page Per Patient //************************************************** for (int iRow = 0; iRow < dt[iTab].Rows.Count; iRow++) { iTextSharp.text.pdf.PdfPTable tbl; if (dt[iTab].Columns.Count == 5) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 16, 16, 46, 17 }); } else if (dt[iTab].Columns.Count == 6) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 13, 13, 30, 12, 27 }); } else if (dt[iTab].Columns.Count == 7) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 13, 13, 30, 12, 15, 12 }); } else if (dt[iTab].Columns.Count == 8) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 15, 15, 24, 11, 10, 10, 10 }); } else if (dt[iTab].Columns.Count == 9) { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 14, 14, 16, 11, 10, 10, 10, 10 }); } else { tbl = new iTextSharp.text.pdf.PdfPTable(new float[] { 5, 10, 10, 14, 11, 10, 10, 10, 10, 10 }); } tbl.WidthPercentage = 100; tbl.HeaderRows = 1; if (dt[iTab].TableName != "") { string[] arHeaders = dt[iTab].TableName.Replace(" list", " member " + (iRow + 1)).Split('~'); for (int iHeader = 0; iHeader < arHeaders.Length; iHeader++) { if (iHeader > 0) { PdfPCell objCellTitle; if (iHeader == 1) { objCellTitle = new PdfPCell(new Phrase(2, arHeaders[iHeader], new Font(Font.FontFamily.HELVETICA, 14, 1))); objCellTitle.PaddingTop = 10; } else { objCellTitle = new PdfPCell(new Phrase(2, arHeaders[iHeader], new Font(Font.FontFamily.HELVETICA, 13, 0))); objCellTitle.PaddingTop = 4; } objCellTitle.Colspan = dt[iTab].Columns.Count; objCellTitle.PaddingBottom = 5; objCellTitle.BorderWidth = 0; tbl.AddCell(objCellTitle); tbl.HeaderRows++; } } } for (int iCol = 0; iCol < dt[iTab].Columns.Count; iCol++) { PdfPCell objCell = new PdfPCell(new Phrase(2, dt[iTab].Columns[iCol].ColumnName, new Font(Font.FontFamily.HELVETICA, 14, 1))); objCell.Padding = 4; tbl.AddCell(objCell); } for (int iCol = 0; iCol < dt[iTab].Columns.Count; iCol++) { PdfPCell objCell = new PdfPCell(new Phrase(2, lib.cStr(dt[iTab].Rows[iRow][iCol]), new Font(Font.FontFamily.HELVETICA, 13))); objCell.Padding = 3; tbl.AddCell(objCell); } document.Add(tbl); document.NewPage(); } } } //BAA Insert Starts////////////////////////////////////////////////////// if (include_BAA == 1) { string baa_filename = Path.Combine(HttpRuntime.AppDomainAppPath, "imgs\\pdf\\BAA.pdf"); PdfReader reader = new PdfReader(baa_filename); PdfContentByte cb = oPdfWriter.DirectContent; for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++) { document.SetPageSize(reader.GetPageSizeWithRotation(1)); document.NewPage(); //Insert to Destination on the first page if (pageNumber == 1) { Chunk fileRef = new Chunk(" "); fileRef.SetLocalDestination(baa_filename); document.Add(fileRef); } PdfImportedPage page = oPdfWriter.GetImportedPage(reader, pageNumber); int rotation = reader.GetPageRotation(pageNumber); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } } //BAA Insert Ends////////////////////////////////////////////////////// /* Closing and downloading the document*/ document.Close(); if (file_name == "") { document.Close(); oResponse.ContentType = "application/pdf"; oResponse.AddHeader("content-disposition", "attachment;filename=" + documentTitle.Replace(" ", "_").Replace(",", "") + ".pdf"); oResponse.AddHeader("content-disposition", "attachment;filename=" + documentTitle.Replace(" ", "_").Replace(",", "") + ".pdf"); oResponse.End(); } }
private void ExportToExcel(string nameReport, List <InformeProduccionM> lista, string fInicio, string fTermino) { HttpResponse response = Response; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); Page pageToRender = new Page(); HtmlForm form = new HtmlForm(); Label la = new Label(); string Titulo = "<div align='center'>Informe Mensual SobreImpresión<br/>"; if (fInicio != "") { Titulo += " Fecha : " + fInicio; } if (fTermino != "") { Titulo += " a " + fTermino; } la.Text = Titulo + "</div><br />"; form.Controls.Add(la); #region ConversionListaGrilla int contado = 0; int TotalCantPlanCE = 0; int TotalCantProdCE = 0; int TotalCantDifCE = 0; int TotalCantPlanCS = 0; int TotalCantProdCS = 0; int TotalCantDifCS = 0; int TotalCantPlanCB = 0; int TotalCantProdCB = 0; int TotalCantDifCB = 0; int TotalPlinificadoFinal = 0; foreach (string Clasificacion in lista.Select(o => o.Clasificacion).Distinct()) { GridView gv = new GridView(); gv.DataSource = lista.Where(o => o.Clasificacion == Clasificacion); gv.DataBind(); gv.HeaderStyle.BackColor = System.Drawing.Color.Blue; gv.HeaderStyle.ForeColor = System.Drawing.Color.White; gv.HeaderRow.Cells[0].Text = "Sector"; gv.HeaderRow.Cells[1].Text = "Maquina"; gv.HeaderRow.Cells[2].Text = "Planificado Total"; gv.HeaderRow.Cells[3].Text = "Planificado Cons. Esperado"; gv.HeaderRow.Cells[4].Text = "Producido Cons. Esperado"; gv.HeaderRow.Cells[5].Text = "Diferencia"; gv.HeaderRow.Cells[6].Text = "%"; gv.HeaderRow.Cells[7].Text = "Planificado Cons. Sobre"; gv.HeaderRow.Cells[8].Text = "Producida Cons. Sobre"; gv.HeaderRow.Cells[9].Text = "Diferencia"; gv.HeaderRow.Cells[10].Text = "%"; gv.HeaderRow.Cells[11].Text = "Planificado Cons. Bajo"; gv.HeaderRow.Cells[12].Text = "Producida Cons. Bajo"; gv.HeaderRow.Cells[13].Text = "Diferencia"; gv.HeaderRow.Cells[14].Text = "%"; gv.HeaderRow.Cells[15].Visible = false; gv.HeaderRow.Cells[16].Visible = false; gv.HeaderRow.Cells[17].Visible = false; gv.HeaderRow.Cells[18].Visible = false; gv.HeaderRow.Cells[19].Visible = false; gv.HeaderRow.Cells[20].Visible = false; int TotSectorCantPlanCE = 0; int TotSectorCantProdCE = 0; int TotSectorCantDifeCE = 0; string TotSectorProceCE = ""; int TotSectorCantPlanCS = 0; int TotSectorCantProdCS = 0; int TotSectorCantDifeCS = 0; string TotSectorProceCS = ""; int TotSectorCantPlanCB = 0; int TotSectorCantProdCB = 0; int TotSectorCantDifeCB = 0; string TotSectorProceCB = ""; int TotalCantPlan = 0; for (int contador = 0; contador < gv.Rows.Count; contador++) { GridViewRow row = gv.Rows[contador]; row.Cells[0].Text = row.Cells[20].Text; string M = row.Cells[7].Text; row.Cells[7].Text = row.Cells[1].Text; row.Cells[1].Text = M; row.Cells[2].Text = row.Cells[9].Text; row.Cells[10].Text = row.Cells[5].Text; row.Cells[5].Text = row.Cells[14].Text; row.Cells[6].Text = row.Cells[11].Text; row.Cells[9].Text = row.Cells[8].Text; row.Cells[8].Text = row.Cells[15].Text; row.Cells[11].Text = row.Cells[16].Text; row.Cells[12].Text = row.Cells[17].Text; row.Cells[13].Text = row.Cells[18].Text; row.Cells[14].Text = row.Cells[19].Text; row.Cells[15].Visible = false; row.Cells[16].Visible = false; row.Cells[17].Visible = false; row.Cells[18].Visible = false; row.Cells[19].Visible = false; row.Cells[20].Visible = false; //Consumo Esperado TotSectorCantPlanCE += Convert.ToInt32(row.Cells[3].Text.Replace(",", "").Replace(".", "")); TotalCantPlanCE += Convert.ToInt32(row.Cells[3].Text.Replace(",", "").Replace(".", "")); TotSectorCantProdCE += Convert.ToInt32(row.Cells[4].Text.Replace(",", "").Replace(".", "")); TotalCantProdCE += Convert.ToInt32(row.Cells[4].Text.Replace(",", "").Replace(".", "")); TotSectorCantDifeCE += Convert.ToInt32(row.Cells[5].Text.Replace(",", "").Replace(".", "")); TotalCantDifCE += Convert.ToInt32(row.Cells[5].Text.Replace(",", "").Replace(".", "")); //Consumo Sobre TotSectorCantPlanCS += Convert.ToInt32(row.Cells[7].Text.Replace(",", "").Replace(".", "")); TotalCantPlanCS += Convert.ToInt32(row.Cells[7].Text.Replace(",", "").Replace(".", "")); TotSectorCantProdCS += Convert.ToInt32(row.Cells[8].Text.Replace(",", "").Replace(".", "")); TotalCantProdCS += Convert.ToInt32(row.Cells[8].Text.Replace(",", "").Replace(".", "")); TotSectorCantDifeCS += Convert.ToInt32(row.Cells[9].Text.Replace(",", "").Replace(".", "")); TotalCantDifCS += Convert.ToInt32(row.Cells[9].Text.Replace(",", "").Replace(".", "")); //Consumo Bajo TotSectorCantPlanCB += Convert.ToInt32(row.Cells[11].Text.Replace(",", "").Replace(".", "")); TotalCantPlanCB += Convert.ToInt32(row.Cells[11].Text.Replace(",", "").Replace(".", "")); TotSectorCantProdCB += Convert.ToInt32(row.Cells[12].Text.Replace(",", "").Replace(".", "")); TotalCantProdCB += Convert.ToInt32(row.Cells[12].Text.Replace(",", "").Replace(".", "")); TotSectorCantDifeCB += Convert.ToInt32(row.Cells[13].Text.Replace(",", "").Replace(".", "")); TotalCantDifCB += Convert.ToInt32(row.Cells[13].Text.Replace(",", "").Replace(".", "")); //Total TotalCantPlan += (Convert.ToInt32(row.Cells[3].Text.Replace(",", "").Replace(".", "")) + Convert.ToInt32(row.Cells[7].Text.Replace(",", "").Replace(".", "")) + Convert.ToInt32(row.Cells[11].Text.Replace(",", "").Replace(".", ""))); } TotSectorProceCE = (Convert.ToDouble(Convert.ToDouble(TotSectorCantDifeCE) / Convert.ToDouble(TotSectorCantPlanCE)) * 100).ToString("N2") + "%"; TotSectorProceCS = (Convert.ToDouble(Convert.ToDouble(TotSectorCantDifeCS) / Convert.ToDouble(TotSectorCantPlanCS)) * 100).ToString("N2") + "%"; TotSectorProceCB = (Convert.ToDouble(Convert.ToDouble(TotSectorCantDifeCB) / Convert.ToDouble(TotSectorCantPlanCB)) * 100).ToString("N2") + "%"; TotalPlinificadoFinal += TotalCantPlan; Label TablaMaquinaTotal = new Label(); TablaMaquinaTotal.Text = "<table><tr>" + "<td style='border:1px solid black;' colspan='2'>Totales " + Clasificacion + "</td>" + "<td style='border:1px solid black;'>" + TotalCantPlan.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantPlanCE.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantProdCE.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantDifeCE.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorProceCE.Replace("NaN", "0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantPlanCS.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantProdCS.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantDifeCS.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorProceCS.Replace("NaN", "0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantPlanCB.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantProdCB.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorCantDifeCB.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotSectorProceCB.Replace("NaN", "0").Replace(",", "").Replace(".", "") + "</td></tr></table><br />"; form.Controls.Add(gv); form.Controls.Add(TablaMaquinaTotal); contado++; } #endregion Label TablaTotal = new Label(); string PorceDifCE = (Convert.ToDouble(Convert.ToDouble(TotalCantDifCE) / Convert.ToDouble(TotalCantPlanCE)) * 100).ToString("N2") + "%"; string PorceDifCS = (Convert.ToDouble(Convert.ToDouble(TotalCantDifCS) / Convert.ToDouble(TotalCantPlanCS)) * 100).ToString("N2") + "%"; string PorceDifCB = (Convert.ToDouble(Convert.ToDouble(TotalCantDifCB) / Convert.ToDouble(TotalCantPlanCB)) * 100).ToString("N2") + "%"; TablaTotal.Text = "<table><tr>" + "<td style='border:1px solid black;' colspan='2'>Total</td>" + "<td style='border:1px solid black;'>" + TotalPlinificadoFinal.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantPlanCE.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantProdCE.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantDifCE.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + PorceDifCE.Replace("NaN", "0") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantPlanCS.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantProdCS.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantDifCS.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + PorceDifCS.Replace("NaN", "0") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantPlanCB.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantProdCB.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + TotalCantDifCB.ToString("N0").Replace(",", "").Replace(".", "") + "</td>" + "<td style='border:1px solid black;'>" + PorceDifCB.Replace("NaN", "0") + "</td></tr></table>"; form.Controls.Add(TablaTotal); pageToRender.Controls.Add(form); response.Clear(); response.Buffer = true; response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", "attachment;filename=" + nameReport + ".xls"); response.Charset = "UTF-8"; response.ContentEncoding = Encoding.Default; pageToRender.RenderControl(htw); response.Write(sw.ToString()); response.End(); }
private void context_EndRequest(object sender, EventArgs e) { HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; // // Check for the X-Send headers // string filePath = response.Headers.Get("X-Sendfile"); if (filePath == null) { filePath = response.Headers.Get("X-Accel-Redirect"); } if (filePath != null) { // // Determine the file path and ready the response // if (ConfigurationManager.AppSettings["XSendDir"] != null) { filePath = Path.Combine(ConfigurationManager.AppSettings["XSendDir"], filePath); // if there is a base path set (file will be located above this) } else if (ConfigurationManager.AppSettings["XAccelLocation"] != null) { filePath = filePath.Replace(ConfigurationManager.AppSettings["XAccelLocation"], ConfigurationManager.AppSettings["XAccelRoot"]); } response.Clear(); // Clears output buffer response.Headers.Remove("X-Sendfile"); // Remove unwanted headers response.Headers.Remove("X-Accel-Redirect"); // // Set the cache policy // if (ConfigurationManager.AppSettings["XSendCache"] == null) { response.Cache.SetCacheability(HttpCacheability.NoCache); } else if (ConfigurationManager.AppSettings["XSendCache"] == "Public") { response.Cache.SetCacheability(HttpCacheability.Public); } else { response.Cache.SetCacheability(HttpCacheability.Private); } // // Get the file information and set headers appropriately // if (!FileUtil.FileExists(filePath)) { throw new HttpException(404, "File_does_not_exist"); } if (filePath[filePath.Length - 1] == '.') { throw new HttpException(404, "File_does_not_exist"); } FileInfo file = new FileInfo(filePath); response.Cache.SetLastModified(file.LastWriteTimeUtc); response.Headers.Remove("Content-Length"); DateTime dateTime = new DateTime(file.LastWriteTime.Year, file.LastWriteTime.Month, file.LastWriteTime.Day, file.LastWriteTime.Hour, file.LastWriteTime.Minute, file.LastWriteTime.Second, 0); DateTime now = DateTime.Now; string range = request.Headers["Range"]; // // Call into .net static file handler to do the heavy lifting for us // Massive hacks. Should work for all version of .net // // http://dotnetinside.com/framework/v2.0.50727/System.Web/StaticFileHandler // http://typedescriptor.net/browse/types/7243-System.Web.StaticFileHandler // http://stackoverflow.com/questions/7829478/how-to-execute-a-private-static-method-with-optional-parameters-via-reflection // // var genEtag = typeof(System.Web.StaticFileHandler).GetMethod("GenerateETag", BindingFlags.Static | BindingFlags.NonPublic); string etag = genEtag.Invoke(obj: null, parameters: new object[] { HttpContext.Current, dateTime, now }); var rangeRequest = typeof(System.Web.StaticFileHandler).GetMethod("ProcessRangeRequest", BindingFlags.Static | BindingFlags.NonPublic); if (StringUtil.StringStartsWithIgnoreCase(range, "bytes") && rangeRequest.Invoke(obj: null, parameters: new object[] { HttpContext.Current, filePath, file.Length, range, etag, dateTime })) { return; } response.AddHeader("Content-Length", file.Length.ToString()); response.AppendHeader("Accept-Ranges", "bytes"); response.Cache.SetIgnoreRangeRequests(); // // Check if we want to detect the mime type of the current content // if (ConfigurationManager.AppSettings["XSendMime"] == null) { Microsoft.Web.Administration.ConfigurationSection staticContentSection = WebConfigurationManager.GetSection(HttpContext.Current, "system.webServer/staticContent"); Microsoft.Web.Administration.ConfigurationElementCollection staticContentCollection = staticContentSection.GetCollection(); var mt = staticContentCollection.Where( a => a.Attributes["fileExtension"].Value.ToString().ToLower() == file.Extension.ToLower() ).FirstOrDefault(); if (mt != null) { response.ContentType = mt.GetAttributeValue("mimeType").ToString(); } else { response.ContentType = "application/octet-stream"; } } // // Set a content disposition if it is not already set by the application // if (response.Headers["Content-Disposition"] == null) { response.AppendHeader("Content-Disposition", "inline;filename=" + file.Name); } // // Send the file without loading it into memory // response.TransmitFile(file.FullName); } }
public override void SetLength(long value) { res.AddHeader("Content-Length", value.ToString(CultureInfo.InvariantCulture)); }
protected void dlOrderList_ItemCommand(object source, RepeaterCommandEventArgs e) { string command = e.CommandName; int Index = e.Item.ItemIndex; switch (command) { case "Exp_Col": { RepeaterItem item = dlOrderList.Items[Index]; //Label test = item.FindControl("lblC_P") as Label; ImageButton img = item.FindControl("ibtnNOExpColap") as ImageButton; if (img.ImageUrl == "~/images/expand.JPG") { ((ImageButton)dlOrderList.Items[Index].FindControl("ibtnNOExpColap")).ImageUrl = "~/images/collapse.JPG"; ((GridView)dlOrderList.Items[Index].FindControl("gvOrder")).Visible = true; } else if (img.ImageUrl == "~/images/collapse.JPG") { ((ImageButton)dlOrderList.Items[Index].FindControl("ibtnNOExpColap")).ImageUrl = "~/images/expand.JPG"; ((GridView)dlOrderList.Items[Index].FindControl("gvOrder")).Visible = false; } } break; case "BranchOrder": { Session["sOrderID"] = Encrypt_Decrypt.Encrypt(((LinkButton)dlOrderList.Items[Index].FindControl("lbtnOrderID")).Text, true); if (Session["RoleName_s"].ToString().Trim().ToLower() == LoginType.Admin.ToLower()) { Response.Redirect("~/mudar/UpdateAdminOrder.aspx"); } else if (Session["RoleName_s"].ToString().Trim().ToLower() == LoginType.Branch.ToLower() || Session["RoleName_s"].ToString().Trim().ToLower() == LoginType.Supplier.ToLower()) { Response.Redirect("~/mudar/UpdateOrderNew.aspx"); //Response.Redirect("~/mudar/Copy of UpdateOrderNew.aspx"); } } break; case "Display": { string str = ((HiddenField)dlOrderList.Items[Index].FindControl("hfOrderPdf")).Value.ToString(); //ifOrderPdf.Attributes.Add("src", str); //ifOrderPdf.Attributes.Add("src", "../Attachments/OrderPDF/1015/1015_PO201296.pdf"); } break; case "Download": { string str = ((HiddenField)dlOrderList.Items[Index].FindControl("hfOrderPdf")).Value.ToString(); WebClient req = new WebClient(); HttpResponse response = HttpContext.Current.Response; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.Buffer = true; response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(str) + "\""); byte[] data = req.DownloadData(Server.MapPath(str)); response.BinaryWrite(data); response.End(); } break; } }
public void ProcessRequest(HttpContext context) { Response = context.Response; string appId = context.Request.QueryString["app"]; int groupId; if (!String.IsNullOrEmpty(appId) && Int32.TryParse(context.Request.QueryString["group"], out groupId)) { Response.Clear(); List<String> placemarks = new List<String>(); Dictionary<String, String> styles = new Dictionary<String, String>(); string appName = null; string groupName = null; using (OleDbConnection connection = AppContext.GetDatabaseConnection()) { string sql = String.Format("update {0}MarkupGroup set DateLastAccessed = ? where GroupID = ?", AppSettings.ConfigurationTablePrefix); using (OleDbCommand command = new OleDbCommand(sql, connection)) { command.Parameters.Add("@1", OleDbType.Date).Value = DateTime.Now; command.Parameters.Add("@2", OleDbType.Integer).Value = groupId; command.ExecuteNonQuery(); command.CommandText = String.Format("select Shape, Color, Text from {0}Markup where GroupID = ? and Deleted = 0", AppSettings.ConfigurationTablePrefix); command.Parameters.Clear(); command.Parameters.Add("@1", OleDbType.Integer).Value = groupId; WKTReader wktReader = new WKTReader(); using (OleDbDataReader reader = command.ExecuteReader()) { while (reader.Read()) { IGeometry geometry = wktReader.Read(reader.GetString(0)); string coordinates = GetCoordinates(geometry); string color = reader.GetString(1); bool isText = !reader.IsDBNull(2); string styleId = GetStyle(geometry.OgcGeometryType, color, isText, styles); switch (geometry.OgcGeometryType) { case OgcGeometryType.Point: string name = isText ? String.Format("<name>{0}</name>", reader.GetString(2)) : ""; placemarks.Add(String.Format("<Placemark>{0}<styleUrl>#{1}</styleUrl><Point>{2}</Point></Placemark>", name, styleId, coordinates)); break; case OgcGeometryType.LineString: placemarks.Add(String.Format("<Placemark><styleUrl>#{0}</styleUrl><LineString>{1}</LineString></Placemark>", styleId, coordinates)); break; case OgcGeometryType.Polygon: placemarks.Add(String.Format("<Placemark><styleUrl>#{0}</styleUrl><Polygon><outerBoundaryIs><LinearRing>{1}</LinearRing></outerBoundaryIs></Polygon></Placemark>", styleId, coordinates)); break; } } } Configuration config = AppContext.GetConfiguration(); Configuration.ApplicationRow application = config.Application.Select(String.Format("ApplicationID = '{0}'", appId))[0] as Configuration.ApplicationRow; appName = application.DisplayName; command.CommandText = String.Format("select DisplayName from {0}MarkupGroup where GroupID = ?", AppSettings.ConfigurationTablePrefix); groupName = command.ExecuteScalar() as string; } } string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmssff"); string kmzName = String.Format("Markup_{0}.kmz", timeStamp); string kmlName = String.Format("Markup_{0}.kml", timeStamp); string kml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <kml xmlns=""http://earth.google.com/kml/2.2""> <Folder> <name>{0}</name> <Document> <name>Markup: {1}</name> {2} {3} </Document> </Folder> </kml>"; string[] styleArray = new string[styles.Values.Count]; styles.Values.CopyTo(styleArray, 0); kml = String.Format(kml, appName, groupName, String.Join("", styleArray), String.Join("", placemarks.ToArray())); Response.ContentType = "application/vnd.google-earth.kmz"; Response.AddHeader("Content-Disposition", "attachment; filename=" + kmzName); ZipOutputStream zipStream = new ZipOutputStream(Response.OutputStream); MemoryStream memoryStream = new MemoryStream(); byte[] buffer = (new UTF8Encoding()).GetBytes(kml); ZipEntry entry = new ZipEntry(kmlName); entry.Size = buffer.Length; zipStream.PutNextEntry(entry); zipStream.Write(buffer, 0, buffer.Length); zipStream.Finish(); Response.End(); } }
public static void SetNoCache(HttpResponse response) { response.Buffer = true; response.CacheControl = "no-cache"; response.AddHeader("Pragma", "no-cache"); response.Expires = -1441; }
/// <summary> /// Adds an HTTP Response Header /// </summary> /// <remarks> /// This method is used to store the Response Headers in a private, member variable, /// InternalResponseHeaders, so that the Response Headers may be accesed in the /// LogResponseHttpHeaders method, if needed. The Response.Headers property can only /// be accessed directly when using IIS 7's Integrated Pipeline mode. This workaround /// permits logging of Response Headers when using Classic mode or a web server other /// than IIS 7. /// </remarks> protected void AddHeader(HttpResponse response, string name, string value) { //_internalResponseHeaders.Add(name, value); response.AddHeader(name, value); }
protected void ex(DataTable dataTable, string fileName) { DataSet dsExport = new DataSet(); System.IO.StringWriter tw = new System.IO.StringWriter(); //System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); DataGrid dgGrid = new DataGrid(); dgGrid.DataSource = dataTable; // Report Header // hw.WriteLine("<b><u><font size='5'> JVVNL " + fileName + " </font></u></b>"); // Get the HTML for the control. //dgGrid.HeaderStyle.Font.Bold = true; //dgGrid.DataBind(); //dgGrid.RenderControl(hw); // Write the HTML back to the browser. //Response.AddHeader("Content-Disposition", "attachment; filename =\"" + fileName + ".xls"); //Response.ContentType = "application/vnd.ms-excel"; //string style = @"<style> .textmode { mso-number-format:\@; } </style>"; //Response.Write(style); //this.EnableViewState = false; //Response.Write(tw.ToString()); //Response.End(); HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Charset = ""; // set the response mime type for excel if ((fileName + "-").ToLower().Contains(".xlsx-")) { response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } else { response.ContentType = "application/vnd.ms-excel"; } response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); // create a string writer using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // instantiate a datagrid GridView gvExport = new GridView(); gvExport.DataSource = dataTable; gvExport.DataBind(); //(start): require for date format issue HtmlTextWriter hw = new HtmlTextWriter(sw); foreach (GridViewRow r in gvExport.Rows) { if (r.RowType == DataControlRowType.DataRow) { for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++) { r.Cells[columnIndex].Attributes.Add("class", "text"); } } } //(end): require for date format issue gvExport.RenderControl(htw); //(start): require for date format issue System.Text.StringBuilder style = new System.Text.StringBuilder(); style.Append("<style>"); style.Append("." + "text" + " { mso-number-format:" + "\\@;" + " }"); style.Append("</style>"); response.Clear(); Response.Buffer = true; //response.Charset = ""; //response.Write(sw.ToString()); Response.Write(style.ToString()); Response.Output.Write(sw.ToString()); Response.Flush(); //(end): require for date format issue try { response.End(); } catch (Exception err) { } //HttpContext.Current.ApplicationInstance.CompleteRequest(); } } }
/// <summary> /// The get response. /// </summary> /// <returns> /// The <see cref="HttpResponse" />. /// </returns> public HttpResponse GetResponse() { var response = new HttpResponse( this.Request.ProtocolVersion, HttpStatusCode.OK, this.model.ToString(), "text/plain; charset=utf-8"); foreach (var responseHeader in this.ResponseHeaders) { response.AddHeader(responseHeader.Key, responseHeader.Value); } return response; }
public static void DownloadDocument(HttpResponse httpResponse, byte[] fileContents, string fileName) { try { string contentType = "application/octet-stream"; try { contentType = Utilities.GetMimeType(System.IO.Path.GetExtension(fileName)); } catch (Exception) { } httpResponse.Clear(); httpResponse.ClearHeaders(); // add cooke so that javascript can detect when file downloaded is done and started if it want's to // do something (such as letter print page to deselect leter to print) httpResponse.Cookies["fileDownloaded"].Value = "true"; httpResponse.Cookies["fileDownloaded"].Expires = DateTime.Now.AddHours(3); httpResponse.ContentType = contentType; httpResponse.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); httpResponse.OutputStream.Write(fileContents, 0, fileContents.Length); httpResponse.Flush(); httpResponse.End(); } catch (System.Web.HttpException ex) { // ignore exception where user closed the download box if (!ex.Message.StartsWith("The remote host closed the connection. The error code is")) throw; } }
private static void OutputClientSireSelectionSheetsToPDF(LocalReport localReport, string fileName, bool landscape, bool legal, HttpResponse response) { const string reportType = "PDF"; string mimeType; string encoding; string fileNameExtension; // The DeviceInfo settings should be changed based on the reportType // http://msdn2.microsoft.com/en-us/library/ms155397.aspx string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>" + (landscape ? (legal ? "14" : "11") : "8.5") + "in</PageWidth>" + " <PageHeight>" + (landscape ? "8.5" : (legal ? "14" : "11")) + "in</PageHeight>" + " <MarginTop>0.3in</MarginTop>" + " <MarginLeft>1.25in</MarginLeft>" + " <MarginRight>0.25in</MarginRight>" + " <MarginBottom>0.3in</MarginBottom>" + "</DeviceInfo>"; /* other attributes for the DeviceInfo are StartPage - The first page of the report to render. A value of 0 indicates that all pages are rendered. The default value is 1. Columns - The number of columns to set for the report. This value overrides the report's original settings. ColumnSpacing - The column spacing to set for the report. This value overrides the report's original settings. EndPage - The last page of the report to render. The default value is the value for StartPage. */ Warning[] warnings; string[] streams; //Render the report byte[] renderedBytes = localReport.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); // Clear the response stream and write the bytes to the outputstream // Set content-disposition to "attachment" so that user is prompted to take an action // on the file (open or save) response.Clear(); response.ContentType = mimeType; response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + fileNameExtension); response.BinaryWrite(renderedBytes); response.End(); }
internal void NotifyServerCallExit(HttpResponse response) { try { if (NotifySink == null) return; IntPtr bufferPtr; int bufferSize = 0; CallId callId = new CallId(null, 0, (IntPtr)0, 0, null, null); TraceMethod method = Tracing.On ? new TraceMethod(this, "NotifyServerCallExit") : null; if (Tracing.On) Tracing.Enter("RemoteDebugger", method); UnsafeNativeMethods.OnSyncCallExit(NotifySink, callId, out bufferPtr, ref bufferSize); if (Tracing.On) Tracing.Exit("RemoteDebugger", method); if (bufferPtr == IntPtr.Zero) return; byte[] buffer = null; try { buffer = new byte[bufferSize]; Marshal.Copy(bufferPtr, buffer, 0, bufferSize); } finally { Marshal.FreeCoTaskMem(bufferPtr); } string stringBuffer = Convert.ToBase64String(buffer); response.AddHeader(debuggerHeader, stringBuffer); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Warning, typeof(RemoteDebugger), "NotifyServerCallExit", e); } this.Close(); }
public void ProcessRequest(HttpContext context) { HttpResponse Response = context.Response; HttpRequest Request = context.Request; System.IO.Stream iStream = null; System.Data.OleDb.OleDbConnection dbConnection = null; string sFileName = Request["fn"]; string sSql = ""; try { string sFilePath = HttpContext.Current.Server.MapPath("~/upload/pispdfinfo/" + sFileName + ".png"); //待下载的文件路径 if (sFileName != null) //按文件名下载指定文件 { iStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); if (!string.IsNullOrEmpty(context.Request["tb"])) { System.Drawing.Image img = System.Drawing.Image.FromStream(iStream); img = img.GetThumbnailImage(200, (int)(img.Height / (img.Width / 200.0)), delegate() { return(false); }, IntPtr.Zero); iStream = new MemoryStream(); img.Save(iStream, System.Drawing.Imaging.ImageFormat.Png); } sFileName = System.IO.Path.GetFileName(sFileName); Response.AddHeader("Content-Disposition", "filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(sFileName))); sFileName = System.IO.Path.GetExtension(sFileName); string mimeType = Microsoft.Win32.Registry.GetValue(@"HKEY_CLASSES_ROOT\" + sFileName, "Content Type", null) as string; Response.ContentType = mimeType; } else { //using (SqlConnection dbConn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServer"].ConnectionString)) { string sPisID = context.Request["pis"]; if (!string.IsNullOrEmpty(sPisID)) { sFileName = "PisChart" + sPisID; sSql = "SELECT * FROM pispdf WHERE boardid=" + sPisID; } else { string sSN = context.Request["sn"]; sSN = string.IsNullOrEmpty(sSN) ? "NULL" : "'" + sSN.Replace("'", "''") + "'"; sSql = string.Format("EXEC usp_Get_Profile @Line='{0}',@StartTime='{1}',@SN={2}", context.Request["line"], context.Request["time"], sSN); } //DataSet dataSet = new DataSet(); DataSet dataSet = Common.DAL.ExecuteDataSet(sSql); //dbConn.Open(); //SqlDataAdapter adp = new SqlDataAdapter(sSql, dbConn); //adp.Fill(dataSet); DataRow row = null; if (dataSet.Tables.Count > 1 && dataSet.Tables[1].Rows.Count > 0) { row = dataSet.Tables[1].Rows[0]; } else if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0) { row = dataSet.Tables[0].Rows[0]; } if (row != null) { if (!string.IsNullOrEmpty(context.Request["tb"])) { byte[] theBytes = (byte[])row["pdfinfo"]; if (theBytes == null) { throw new Exception("Can't get bytes form field !"); } System.IO.MemoryStream mStream = new System.IO.MemoryStream(theBytes); if (mStream == null) { throw new Exception("mStream Is NULL !"); } mStream.Seek(0, SeekOrigin.Begin); System.Drawing.Image img = System.Drawing.Image.FromStream(mStream); img = img.GetThumbnailImage(200, (int)(img.Height / (img.Width / 200.0)), delegate() { return(false); }, IntPtr.Zero); iStream = new MemoryStream(); img.Save(iStream, System.Drawing.Imaging.ImageFormat.Png); } else if (!string.IsNullOrEmpty(context.Request["tm"])) { System.Drawing.Image img = System.Drawing.Image.FromStream(new System.IO.MemoryStream((byte[])row["pdfinfo"])); img = img.GetThumbnailImage(1150, (int)(img.Height / (img.Width / 1150.0)), delegate() { return(false); }, IntPtr.Zero); iStream = new MemoryStream(); img.Save(iStream, System.Drawing.Imaging.ImageFormat.Png); } else { iStream = new MemoryStream((byte[])row["pdfinfo"]); } Response.ContentType = "image/png"; sFileName = Path.GetFileNameWithoutExtension(sFileName) + ".png"; //Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition",//"attachment;" "filename=" + System.Web.HttpUtility.UrlEncode( System.Text.Encoding.GetEncoding(65001).GetBytes(sFileName))); } } } Response.Clear(); try { long p = 0; long dataToRead = iStream.Length; if (Request.Headers["Range"] != null) { Response.StatusCode = 206; p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", "")); } if (p != 0) { Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString()); } Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString()); iStream.Position = p; } catch (Exception ex) { } //Response.ContentType = "application/pdf"; //Response.ContentType = "application/octet-stream"; //Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode( // System.Text.Encoding.GetEncoding(65001).GetBytes(System.IO.Path.GetFileName(sFileName)))); byte[] buffer = new Byte[10240]; int length = 0; while ((length = iStream.Read(buffer, 0, 10240)) > 0) { if (Response.IsClientConnected) { Response.OutputStream.Write(buffer, 0, length); Response.Flush(); } } //Response.End(); HttpContext.Current.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { Response.ContentType = "text/html"; Response.Write("<html><body>"); Response.Write("sSql : " + context.Server.HtmlEncode(sSql)); Response.Write("<br>Error : " + context.Server.HtmlEncode(ex.Message)); Response.Write("<br>StackTrace : " + context.Server.HtmlEncode(ex.StackTrace).Replace("\n", "<br>")); //生成关闭登录窗口的脚本 string sHtml = "<script type=\"text/javascript\">" + "if(parent.lblError) parent.lblError.innerHTML=unescape(\"" + Microsoft.JScript.GlobalObject.escape(ex.Message.Replace("\n", "<br>")) + Microsoft.JScript.GlobalObject.escape(ex.StackTrace.Replace("\n", "<br>")) + "\");" + "</script>"; Response.Write(sHtml); Response.Write("</body></html>"); } finally { if (iStream != null) { iStream.Close(); } if (dbConnection != null) { dbConnection.Dispose(); } } }
/// <summary> /// Xuất ra file excel /// </summary> /// <param name="dsInput">DataSet có data muốn xuất</param> /// <param name="filename">Tên file</param> /// <param name="SheetName">Tên Sheet trên file Excel</param> /// <param name="filetype">Loại file muốn xuất</param> public static void ToExcel(DataSet dsInput, string filename, string SheetName, FileType filetype) { DataTable da = dsInput.Tables[0]; // Create excel file. ExcelFile ef = new ExcelFile(); string[] ListSheetName = SheetName.Trim().Split(';'); int i = 0; foreach (DataTable table in dsInput.Tables) { ExcelWorksheet ws = ef.Worksheets.Add(ListSheetName[i]); ws.InsertDataTable(table, 0, 0, true); i++; //foreach (ExcelColumn cl in ws.Columns) //{ // cl.AutoFit(); //} } HttpResponse Response = HttpContext.Current.Response; Response.Clear(); // Stream file to browser, in required type. switch (filetype.GetStringValue()) { case "XLS": Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename.Trim()); ef.SaveXls(Response.OutputStream); break; case "XLSX": Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename.Replace("XLSX", "XLS").Trim()); ef.SaveXls(Response.OutputStream); break; case "CSV": Response.ContentType = "text/csv"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename.Trim()); ef.SaveCsv(Response.OutputStream, CsvType.CommaDelimited); break; //case "XLSX": // Response.ContentType = "application/vnd.openxmlformats"; // Response.AddHeader("Content-Disposition", "attachment; filename=" + filename.Trim()); // // With XLSX it is a bit more complicated as MS Packaging API can't write // // directly to Response.OutputStream. Therefore we use temporary MemoryStream. // MemoryStream ms = new MemoryStream(); // ef.SaveXlsx(ms); // ms.WriteTo(Response.OutputStream); // break; case "ODS": Response.ContentType = "application/vnd.oasis.opendocument.spreadsheet"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename.Trim()); ef.SaveOds(Response.OutputStream); break; case "HTML": Response.ContentType = "text/html"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename.Trim()); XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, new UTF8Encoding(false)); ef.SaveHtml(writer, null, true); writer.Close(); break; } Response.End(); }
protected override void UpdateResponse(HttpResponse response) { response.AddHeader("Cache-Control", "private, max-age=0, no-cache"); }
/// <summary> /// 设置客户端保存缓存 /// </summary> /// <param name="response"></param> /// <param name="etag"></param> public static void SetClientCache(HttpResponse response, string etag) { response.AddHeader("ETag", "\"" + etag + "\""); }
/// <summary> /// Method that process the Uri. /// </summary> /// <param name="request">Information sent by the browser about the request</param> /// <param name="response">Information that is being sent back to the client.</param> /// <param name="session">Session used to </param> /// <exception cref="InternalServerException">Failed to find file extension</exception> /// <exception cref="ForbiddenException">File type is forbidden.</exception> public override bool Process(HttpRequest request, HttpResponse response, IHttpSession session) { if (!CanHandle(request.Uri)) return false; try { string path = GetPath(request.Uri); string extension = GetFileExtension(path); if (extension == null) throw new InternalServerException("Failed to find file extension"); if (MimeTypes.ContainsKey(extension)) response.ContentType = MimeTypes[extension]; else throw new ForbiddenException("Forbidden file type: " + extension); using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { if (!string.IsNullOrEmpty(request.Headers["if-modified-since"])) { DateTime lastRequest = DateTime.Parse(request.Headers["if-modified-since"]); if (lastRequest.CompareTo(File.GetLastWriteTime(path)) <= 0) response.Status = HttpStatusCode.NotModified; } if (_useLastModifiedHeader) response.AddHeader("Last-modified", File.GetLastWriteTime(path).ToString("r")); response.ContentLength = stream.Length; response.SendHeaders(); if (request.Method != "Headers" && response.Status != HttpStatusCode.NotModified) { byte[] buffer = new byte[8192]; int bytesRead = stream.Read(buffer, 0, 8192); while (bytesRead > 0) { response.SendBody(buffer, 0, bytesRead); bytesRead = stream.Read(buffer, 0, 8192); } } } } catch (FileNotFoundException err) { throw new InternalServerException("Failed to proccess file.", err); } return true; }
protected void btnExport_Click(object sender, EventArgs e) { try { string namePlantilla = string.Empty; int tipoCliente = Convert.ToInt32(hdTipoProveedor.Value); namePlantilla = tipoCliente.Equals((int)TipoCliente.Juridico) ? "Plantilla Ficha Proveedor Juridico.xlsx" : "Plantilla Ficha Proveedor Natural.xlsx"; var workbook = new XLWorkbook(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Plantillas Excel\", namePlantilla)); var worksheet = workbook.Worksheet(1); /* Cabecera */ worksheet.Cell("E6").Value = FolioDoc.Text; worksheet.Cell("Q6").Value = CantActualizacion.Text; worksheet.Cell("E7").Value = TxtFechaEmision.Text; worksheet.Cell("Q7").Value = TxtFechaActualizacion.Text; string pathImage = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Imagenes\logo_impex.jpg"); var image = worksheet.AddPicture(pathImage) .MoveTo(worksheet.Cell("M1")) .WithSize(309, 80); /* Body */ if (tipoCliente == (int)TipoCliente.Natural) { #region Datos Proveedor Natural var _dirFacturacion = new Direccion { pais = txtNatPais.Text, region = txtNatRegion.Text, ciudad = txtNatCiudad.Text, direccion = txtNatDireccion.Text, zip = txtNatZip.Text, giro_actividad = TxtNatGiroActividad.Text }; var _cli = new Cliente { id_tipo_cliente = tipoCliente, // id_codigo_folio = numeroFolio.idFolio, nombre = txtNatNombre.Text, rut = txtNatRut.Text, area_profesion = txtNatProfesion.Text, identidad = cmboNatIdentidad.Text, fecha_nacimiento = Convert.ToDateTime(txtNatFechaNac.Text), contacto1 = txtNatFono.Text, contacto2 = txtNatEmail.Text, NombreEntidad = NombreEntidad.Proveedor.ToString() }; var _infoFact = new Informacion_Facturacion { nombre_cuenta = txtCtaFactNatNombre.Text, rut = txtCtaFactNatRUT.Text, banco = txtCtaFactNatBanco.Text, tipo_cuenta = txtCtaFactNatTipoCta.Text, numero_cuenta = txtCtaFactNatNumCta.Text, correo_confirmacion = txtCtaFactNatEmailConfirm.Text }; string direccionFacturacion = "(1.) País:" + _dirFacturacion.pais + ";" + "(1.1.) Estado / Región: " + _dirFacturacion.region + "; (1.2.) Ciudad: " + _dirFacturacion.ciudad + ";" + "(1.2.) Dirección: " + _dirFacturacion.direccion + "; (1.3.) Código Postal: " + _dirFacturacion.zip; string cuentaBancaria = "(1.) Nombre: " + _infoFact.nombre_cuenta + "; (1.1.) RUT (DNI, Tax – ID): " + _infoFact.rut + "; (1.2.) Banco: " + _infoFact.banco + "; (1.3.) Tipo de cuenta: " + _infoFact.tipo_cuenta + "; (1.4.) Número de cuenta: " + _infoFact.numero_cuenta + "; (2.) Correo de confirmación: " + _infoFact.correo_confirmacion; #endregion worksheet.Cell("E9").Value = _cli.nombre; worksheet.Cell("I9").Value = _cli.area_profesion; worksheet.Cell("Q9").Value = _cli.rut; worksheet.Cell("E10").Value = _cli.identidad; worksheet.Cell("I10").Value = _cli.fecha_nacimiento.Value.ToString("yyyy-MM-dd"); worksheet.Cell("Q10").Value = _cli.contacto1; worksheet.Cell("U10").Value = _cli.contacto2; worksheet.Cell("E11").Value = direccionFacturacion; worksheet.Cell("E13").Value = cuentaBancaria; worksheet.Cell("A17").Value = DatosEmisor.Text; } else { #region Proveedor Juridico var _dir = new Direccion { pais = txtPais.Text, region = txtRegion.Text, ciudad = txtCiudad.Text, direccion = TxtDirección.Text, zip = txtCodigoPostal.Text }; var _cli = new Cliente { id_tipo_cliente = tipoCliente, nombre = TxtRepreNombre.Text, rut = TxtRepreRutID.Text, area_profesion = TxtRepreProfesion.Text, identidad = cmboIdentidad.Text, fecha_nacimiento = Convert.ToDateTime(TxtRepreCumple.Text), contacto1 = TxtRepreTelefono.Text, contacto2 = TxtRepreEmail.Text, NombreEntidad = NombreEntidad.Proveedor.ToString() }; var _infoEmpresa = new Informacion_Empresa { rut = TxtInfCompIDRUT.Text, razon_social = TxtInfCompRazonSocial.Text, nombre_fantasia = TxtInfCompNombreFantasia.Text, fecha_fundacion = Convert.ToDateTime(TxtInfCompFechaFundacion.Text), pagina_web = TxtInfCompPaginaWeb.Text, contacto_corp1 = TxtInfCompTelefono.Text, contacto_corp2 = TxtInfCompEmail.Text }; var _dirFacturacion = new Direccion { pais = TxtFactPais.Text, region = TxtFactEstadoRegion.Text, ciudad = TxtFactCiudad.Text, direccion = TxtFactDir.Text, zip = TxtFactCodPostal.Text, giro_actividad = TxtFactGiroActividad.Text }; var _infoFact = new Informacion_Facturacion { nombre_cuenta = txtCtaFactNombre.Text, rut = txtCtaFactRUTID.Text, banco = txtCtaFactBanco.Text, tipo_cuenta = txtCtaFactTipoCuenta.Text, numero_cuenta = txtCtaFactNumCta.Text, correo_confirmacion = txtCtaFactEmail.Text }; string direccionPersonal = "(1.) País:" + _dir.pais + ";" + "(1.1.) Estado / Región: " + _dir.region + "; (1.2.) Ciudad: " + _dir.ciudad + ";" + "(1.2.) Dirección: " + _dir.direccion + "; (1.3.) Código Postal: " + _dir.zip; string direccionFacturacion = "(1.) País:" + _dirFacturacion.pais + ";" + "(1.1.) Estado / Región: " + _dirFacturacion.region + "; (1.2.) Ciudad: " + _dirFacturacion.ciudad + ";" + "(1.2.) Dirección: " + _dirFacturacion.direccion + "; (1.3.) Código Postal: " + _dirFacturacion.zip; string cuentaBancaria = "(1.) Nombre: " + _infoFact.nombre_cuenta + "; (1.1.) RUT (DNI, Tax – ID): " + _infoFact.rut + "; (1.2.) Banco: " + _infoFact.banco + "; (1.3.) Tipo de cuenta: " + _infoFact.tipo_cuenta + "; (1.4.) Número de cuenta: " + _infoFact.numero_cuenta + "; (2.) Correo de confirmación: " + _infoFact.correo_confirmacion; #endregion worksheet.Cell("E9").Value = _cli.nombre; worksheet.Cell("I9").Value = _cli.area_profesion; worksheet.Cell("Q9").Value = _cli.rut; worksheet.Cell("E10").Value = _cli.identidad; worksheet.Cell("I10").Value = _cli.fecha_nacimiento.Value.ToString("yyyy-MM-dd"); worksheet.Cell("Q10").Value = _cli.contacto1; worksheet.Cell("U10").Value = _cli.contacto2; worksheet.Cell("E11").Value = direccionPersonal; worksheet.Cell("E14").Value = _infoEmpresa.rut; worksheet.Cell("Q14").Value = _infoEmpresa.razon_social; worksheet.Cell("E15").Value = _infoEmpresa.nombre_fantasia; worksheet.Cell("Q15").Value = _infoEmpresa.fecha_fundacion.ToString("yyyy-MM-dd"); worksheet.Cell("E16").Value = _infoEmpresa.pagina_web; worksheet.Cell("Q16").Value = _infoEmpresa.contacto_corp1; worksheet.Cell("U16").Value = _infoEmpresa.contacto_corp2; worksheet.Cell("E17").Value = direccionFacturacion; worksheet.Cell("E19").Value = cuentaBancaria; worksheet.Cell("A23").Value = DatosEmisor.Text; } string myName = Server.UrlEncode("Ficha_Proveedor_" + ((TipoCliente)tipoCliente).ToString() + "_" + DateTime.Now.ToShortDateString() + ".xlsx"); HttpResponse httpResponse = Response; httpResponse.Clear(); httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; httpResponse.AddHeader("content-disposition", "attachment;filename=" + myName); // Flush the workbook to the Response.OutputStream using (MemoryStream memoryStream = new MemoryStream()) { workbook.SaveAs(memoryStream); memoryStream.WriteTo(httpResponse.OutputStream); memoryStream.Close(); } httpResponse.End(); } catch (Exception ex) { (this.Master as NavContenido).MostrarError("Ha ocurrido un error ", "Error", ex); } }
protected override void UpdateResponse(HttpResponse response) { response.AddHeader("Access-Control-Allow-Origin", this.corsSettings); }
public static bool DownloadFile(HttpRequest _Request, HttpResponse _Response, string _fullPath, long _speed) { string fileName = DirFile.GetFileName(false, _fullPath); try { FileStream fileStream = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader binaryReader = new BinaryReader(fileStream); try { _Response.AddHeader("Accept-Ranges", "bytes"); _Response.Buffer = false; long length = fileStream.Length; long num = 0L; double num2 = 10240.0; int millisecondsTimeout = (int)Math.Floor(1000.0 * num2 / (double)_speed) + 1; if (_Request.Headers["Range"] != null) { _Response.StatusCode = 206; string[] array = _Request.Headers["Range"].Split(new char[] { '=', '-' }); num = Convert.ToInt64(array[1]); } _Response.AddHeader("Content-Length", (length - num).ToString()); _Response.AddHeader("Connection", "Keep-Alive"); _Response.ContentType = "application/octet-stream"; _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8)); binaryReader.BaseStream.Seek(num, SeekOrigin.Begin); int num3 = (int)Math.Floor((double)(length - num) / num2) + 1; for (int i = 0; i < num3; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(binaryReader.ReadBytes(int.Parse(num2.ToString()))); Thread.Sleep(millisecondsTimeout); } else { i = num3; } } } catch { bool result = false; return(result); } finally { binaryReader.Close(); fileStream.Close(); } } catch { bool result = false; return(result); } return(true); }
/// <summary> /// Method that process the url /// </summary> /// <param name="request">Information sent by the browser about the request</param> /// <param name="response">Information that is being sent back to the client.</param> /// <param name="session">Session used to </param> /// <returns>true if this module handled the request.</returns> public override bool Process(HttpRequest request, HttpResponse response, IHttpSession session) { if(!CanHandle(request)) return false; string path = request.Uri.AbsolutePath; string contentType; Stream resourceStream = GetResourceStream(path, out contentType); if(resourceStream == null) return false; response.ContentType = contentType; DateTime modifiedTime = DateTime.MinValue; if (!string.IsNullOrEmpty(request.Headers["if-modified-since"])) { DateTime lastRequest = DateTime.Parse(request.Headers["if-modified-since"]); if (lastRequest.CompareTo(modifiedTime) <= 0) response.Status = HttpStatusCode.NotModified; } response.AddHeader("Last-modified", modifiedTime.ToString("r")); response.ContentLength = resourceStream.Length; response.SendHeaders(); if (request.Method != "Headers" && response.Status != HttpStatusCode.NotModified) { byte[] buffer = new byte[8192]; int bytesRead = resourceStream.Read(buffer, 0, 8192); while (bytesRead > 0) { response.SendBody(buffer, 0, bytesRead); bytesRead = resourceStream.Read(buffer, 0, 8192); } } return true; }
protected void ibExcel_Click(object sender, ImageClickEventArgs e) { //DateTime f1 = new DateTime(); string f1 = ""; if (txtFechaInicio.Text != "") { string fechaI = txtFechaInicio.Text; string[] str = fechaI.Split('/'); string dia = str[0]; string mes = str[1]; string año = str[2]; año = año.Substring(0, 4); //string fechaInicio = mes + "/" + dia + "/" + año; f1 = año + "-" + mes + "-" + dia;//Convert.ToDateTime(fechaInicio).ToString(); //txtCliente.Text = mes + "/" + dia + "/" + año; } else { f1 = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); } List <Bobina_Excel> lista = controlbob.ListBobina_WarRom(f1); List <Bobina_Excel> listaDimen = lista.Where(o => o.Maquina == "Dimensionadora").ToList(); List <Bobina_Excel> listaM600 = lista.Where(o => o.Maquina == "M600").ToList(); List <Bobina_Excel> listaLitho = lista.Where(o => o.Maquina == "Lithoman").ToList(); List <Bobina_Excel> listaWeb1 = lista.Where(o => o.Maquina == "WEB 1").ToList(); Bobina_Excel bob = new Bobina_Excel(); GridView wControl = new GridView(); wControl.DataSource = listaLitho; wControl.DataBind(); wControl.HeaderStyle.BackColor = System.Drawing.Color.Blue; wControl.HeaderStyle.ForeColor = System.Drawing.Color.White; GridView GridM600 = new GridView(); GridM600.DataSource = listaM600; GridM600.DataBind(); GridM600.HeaderStyle.BackColor = System.Drawing.Color.Blue; GridM600.HeaderStyle.ForeColor = System.Drawing.Color.White; GridView GridDimen = new GridView(); GridDimen.DataSource = listaDimen; GridDimen.DataBind(); GridDimen.HeaderStyle.BackColor = System.Drawing.Color.Blue; GridDimen.HeaderStyle.ForeColor = System.Drawing.Color.White; GridView GridWeb1 = new GridView(); GridWeb1.DataSource = listaWeb1; GridWeb1.DataBind(); GridWeb1.HeaderStyle.BackColor = System.Drawing.Color.Blue; GridWeb1.HeaderStyle.ForeColor = System.Drawing.Color.White; //Inicio del Excel if (wControl.Rows.Count > 0) { wControl.HeaderRow.Cells[0].Text = "Código Bobina"; wControl.HeaderRow.Cells[1].Visible = false; wControl.HeaderRow.Cells[2].Text = "Nombre Papel"; wControl.HeaderRow.Cells[3].Text = "Gramaje"; wControl.HeaderRow.Cells[4].Text = "Peso Bobina"; wControl.HeaderRow.Cells[5].Text = "Estado Bobina"; wControl.HeaderRow.Cells[6].Text = "Origen Daño"; wControl.HeaderRow.Cells[7].Text = "Causa Daño"; wControl.HeaderRow.Cells[8].Text = "Kilos Escarpe"; wControl.HeaderRow.Cells[9].Text = "% Perdida"; wControl.HeaderRow.Cells[10].Visible = false; wControl.HeaderRow.Cells[11].Visible = false; wControl.HeaderRow.Cells[12].Visible = false; wControl.HeaderRow.Cells[13].Visible = false; wControl.HeaderRow.Cells[14].Visible = false; } if (GridM600.Rows.Count > 0) { GridM600.HeaderRow.Cells[0].Text = "Código Bobina"; GridM600.HeaderRow.Cells[1].Visible = false; GridM600.HeaderRow.Cells[2].Text = "Nombre Papel"; GridM600.HeaderRow.Cells[3].Text = "Gramaje"; GridM600.HeaderRow.Cells[4].Text = "Peso Bobina"; GridM600.HeaderRow.Cells[5].Text = "Estado Bobina"; GridM600.HeaderRow.Cells[6].Text = "Origen Daño"; GridM600.HeaderRow.Cells[7].Text = "Causa Daño"; GridM600.HeaderRow.Cells[8].Text = "Kilos Escarpe"; GridM600.HeaderRow.Cells[9].Text = "% Perdida"; GridM600.HeaderRow.Cells[10].Visible = false; GridM600.HeaderRow.Cells[11].Visible = false; GridM600.HeaderRow.Cells[12].Visible = false; GridM600.HeaderRow.Cells[13].Visible = false; GridM600.HeaderRow.Cells[14].Visible = false; } if (GridDimen.Rows.Count > 0) { GridDimen.HeaderRow.Cells[0].Text = "Código Bobina"; GridDimen.HeaderRow.Cells[1].Visible = false; GridDimen.HeaderRow.Cells[2].Text = "Nombre Papel"; GridDimen.HeaderRow.Cells[3].Text = "Gramaje"; GridDimen.HeaderRow.Cells[4].Text = "Peso Bobina"; GridDimen.HeaderRow.Cells[5].Text = "Estado Bobina"; GridDimen.HeaderRow.Cells[6].Text = "Origen Daño"; GridDimen.HeaderRow.Cells[7].Text = "Causa Daño"; GridDimen.HeaderRow.Cells[8].Text = "Kilos Escarpe"; GridDimen.HeaderRow.Cells[9].Text = "% Perdida"; GridDimen.HeaderRow.Cells[10].Visible = false; GridDimen.HeaderRow.Cells[11].Visible = false; GridDimen.HeaderRow.Cells[12].Visible = false; GridDimen.HeaderRow.Cells[13].Visible = false; GridDimen.HeaderRow.Cells[14].Visible = false; } if (GridWeb1.Rows.Count > 0) { GridWeb1.HeaderRow.Cells[0].Text = "Código Bobina"; GridWeb1.HeaderRow.Cells[1].Visible = false; GridWeb1.HeaderRow.Cells[2].Text = "Nombre Papel"; GridWeb1.HeaderRow.Cells[3].Text = "Gramaje"; GridWeb1.HeaderRow.Cells[4].Text = "Peso Bobina"; GridWeb1.HeaderRow.Cells[5].Text = "Estado Bobina"; GridWeb1.HeaderRow.Cells[6].Text = "Origen Daño"; GridWeb1.HeaderRow.Cells[7].Text = "Causa Daño"; GridWeb1.HeaderRow.Cells[8].Text = "Kilos Escarpe"; GridWeb1.HeaderRow.Cells[9].Text = "% Perdida"; GridWeb1.HeaderRow.Cells[10].Visible = false; GridWeb1.HeaderRow.Cells[11].Visible = false; GridWeb1.HeaderRow.Cells[12].Visible = false; GridWeb1.HeaderRow.Cells[13].Visible = false; GridWeb1.HeaderRow.Cells[14].Visible = false; } for (int contador = 0; contador < wControl.Rows.Count; contador++) { GridViewRow row = wControl.Rows[contador]; row.Cells[1].Visible = false; row.Cells[10].Visible = false; row.Cells[11].Visible = false; row.Cells[12].Visible = false; row.Cells[13].Visible = false; row.Cells[14].Visible = false; bob.BBuenas = row.Cells[11].Text; bob.BMalas = row.Cells[12].Text; bob.BMalas_QG = row.Cells[10].Text; double PesoOriginal = Convert.ToDouble(row.Cells[4].Text); if (row.Cells[4].Text.Length > 3) { string po2 = PesoOriginal.ToString("N0").Replace(",", "."); row.Cells[4].Text = po2; } else { string po2 = PesoOriginal.ToString("N0"); row.Cells[4].Text = po2; } } for (int contador = 0; contador < GridM600.Rows.Count; contador++) { GridViewRow row = GridM600.Rows[contador]; row.Cells[1].Visible = false; row.Cells[10].Visible = false; row.Cells[11].Visible = false; row.Cells[12].Visible = false; row.Cells[13].Visible = false; row.Cells[14].Visible = false; bob.Maquina = row.Cells[11].Text; bob.NombreOT = row.Cells[12].Text; bob.OT = row.Cells[10].Text; double PesoOriginal = Convert.ToDouble(row.Cells[4].Text); if (row.Cells[4].Text.Length > 3) { string po2 = PesoOriginal.ToString("N0").Replace(",", "."); row.Cells[4].Text = po2; } else { string po2 = PesoOriginal.ToString("N0"); row.Cells[4].Text = po2; } } for (int contador = 0; contador < GridDimen.Rows.Count; contador++) { GridViewRow row = GridDimen.Rows[contador]; row.Cells[1].Visible = false; row.Cells[10].Visible = false; row.Cells[11].Visible = false; row.Cells[12].Visible = false; row.Cells[13].Visible = false; row.Cells[14].Visible = false; bob.Peso_Original = row.Cells[11].Text; bob.Pesos_Conos = row.Cells[12].Text; bob.Pesos_Envoltura = row.Cells[10].Text; double PesoOriginal = Convert.ToDouble(row.Cells[4].Text); if (row.Cells[4].Text.Length > 3) { string po2 = PesoOriginal.ToString("N0").Replace(",", "."); row.Cells[4].Text = po2; } else { string po2 = PesoOriginal.ToString("N0"); row.Cells[4].Text = po2; } } for (int contador = 0; contador < GridWeb1.Rows.Count; contador++) { GridViewRow row = GridWeb1.Rows[contador]; row.Cells[1].Visible = false; row.Cells[10].Visible = false; row.Cells[11].Visible = false; row.Cells[12].Visible = false; row.Cells[13].Visible = false; row.Cells[14].Visible = false; bob.Pesos_Escarpe = row.Cells[11].Text; bob.Pesos_Tapas = row.Cells[12].Text; bob.Porc_Buenas = row.Cells[10].Text; double PesoOriginal = Convert.ToDouble(row.Cells[4].Text); if (row.Cells[4].Text.Length > 3) { string po2 = PesoOriginal.ToString("N0").Replace(",", "."); row.Cells[4].Text = po2; } else { string po2 = PesoOriginal.ToString("N0"); row.Cells[4].Text = po2; } } HttpResponse response = Response; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); Page pageToRender = new Page(); HtmlForm form = new HtmlForm(); Label la = new Label(); string FechaTitulo; if (txtFechaInicio.Text == "") { FechaTitulo = DateTime.Now.AddDays(-1).ToShortDateString(); } else { FechaTitulo = txtFechaInicio.Text; } string Titulo = "<div align='center'>Reporte Desperdicio Papel <br/>Dia: " + txtFechaInicio.Text + " Desde:00:00 Hasta 23:59:59 </div><br />"; la.Text = Titulo; form.Controls.Add(la); if (wControl.Rows.Count > 0) { Label Maquina1 = new Label(); Maquina1.Text = "<div>Lithoman </div><br/>"; form.Controls.Add(Maquina1); form.Controls.Add(wControl); Label TaTotLitho = new Label(); TaTotLitho.Text = "<br/><div align='right'><table><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Consumidas</td>" + "<td style='border:1px solid black;'>" + bob.BBuenas.ToString() + "</div></td></tr><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Buenas</td>" + "<td style='border:1px solid black;'>" + bob.BMalas.ToString() + "</td></tr><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Malas</td>" + "<td style='border:1px solid black;'>" + bob.BMalas_QG.ToString() + "</td></tr></table></div>"; form.Controls.Add(TaTotLitho); } if (GridM600.Rows.Count > 0) { Label Maquina2 = new Label(); Maquina2.Text = "<br/><div align='left'>M600 </div><br/>"; form.Controls.Add(Maquina2); form.Controls.Add(GridM600); Label TaTotM600 = new Label(); TaTotM600.Text = "<br/><div align='right'><table><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Consumidas</td>" + "<td style='border:1px solid black;'>" + bob.Maquina.ToString() + "</td></tr><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Buenas</td>" + "<td style='border:1px solid black;'>" + bob.NombreOT.ToString() + "</td></tr><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Malas</td>" + "<td style='border:1px solid black;'>" + bob.OT.ToString() + "</td></tr></table></div>"; form.Controls.Add(TaTotM600); } if (GridDimen.Rows.Count > 0) { Label Maquina3 = new Label(); Maquina3.Text = "<br/><div align='left'>Dimensionadora </div><br/>"; form.Controls.Add(Maquina3); form.Controls.Add(GridDimen); Label TaTotDimen = new Label(); TaTotDimen.Text = "<br/><div align='right'><table><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Consumidas</td>" + "<td style='border:1px solid black;'>" + bob.Peso_Original.ToString() + "</td></tr><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Buenas</td>" + "<td style='border:1px solid black;'>" + bob.Pesos_Conos.ToString() + "</td></tr><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Malas</td>" + "<td style='border:1px solid black;'>" + bob.Pesos_Envoltura.ToString() + "</td></tr></table></div>"; form.Controls.Add(TaTotDimen); } if (GridWeb1.Rows.Count > 0) { Label Maquina4 = new Label(); Maquina4.Text = "<br/><div align='left'>Web 1 </div><br/>"; form.Controls.Add(Maquina4); form.Controls.Add(GridWeb1); Label TaTotWeb1 = new Label(); TaTotWeb1.Text = "<br/><div align='right'><table><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Consumidas</td>" + "<td style='border:1px solid black;'>" + bob.Pesos_Escarpe.ToString() + "</td></tr><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Buenas</td>" + "<td style='border:1px solid black;'>" + bob.Pesos_Tapas.ToString() + "</td></tr><tr>" + "<td colspan ='6'></td><td style='border:1px solid black;' colspan ='2'>Total Bobinas Malas</td>" + "<td style='border:1px solid black;'>" + bob.Porc_Buenas.ToString() + "</td></tr></table></div>"; form.Controls.Add(TaTotWeb1); } pageToRender.Controls.Add(form); response.Clear(); response.Buffer = true; response.ContentType = "application/vnd.ms-excel"; string fecha; if (txtFechaInicio.Text == "") { fecha = DateTime.Now.AddDays(-1).ToShortDateString(); } else { fecha = txtFechaInicio.Text; } response.AddHeader("Content-Disposition", "attachment;filename=Reporte Desperdicio Papel" + fecha + ".xls"); response.Charset = "UTF-8"; response.ContentEncoding = Encoding.Default; pageToRender.RenderControl(htw); response.Write(sw.ToString()); response.End(); //fin del excel }
public static void DownloadByOutputStreamBlock(this Stream stream, string fileName) { using (stream) { //将流的位置设置到开始位置。 stream.Position = 0; //块大小 long ChunkSize = 102400; //建立100k的缓冲区 byte[] buffer = new byte[ChunkSize]; //已读字节数 long dataLengthToRead = stream.Length; Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", HttpUtility.UrlPathEncode(fileName))); while (dataLengthToRead > 0 && Response.IsClientConnected) { int lengthRead = stream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 Response.OutputStream.Write(buffer, 0, lengthRead); Response.Flush(); Response.Clear(); dataLengthToRead -= lengthRead; } Response.Close(); } }
/* goodB2G() - use badsource and goodsink by changing the second "if" so that * both branches use the GoodSink */ private void GoodB2G(HttpRequest req, HttpResponse resp) { string data; if (IO.StaticReturnsTrueOrFalse()) { data = ""; /* Initialize data */ /* Read data from a database */ { try { /* setup the connection */ using (SqlConnection connection = IO.GetDBConnection()) { connection.Open(); /* prepare and execute a (hardcoded) query */ using (SqlCommand command = new SqlCommand(null, connection)) { command.CommandText = "select name from users where id=0"; command.Prepare(); using (SqlDataReader dr = command.ExecuteReader()) { /* POTENTIAL FLAW: Read data from a database query SqlDataReader */ data = dr.GetString(1); } } } } catch (SqlException exceptSql) { IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error with SQL statement"); } } } else { data = ""; /* Initialize data */ /* Read data from a database */ { try { /* setup the connection */ using (SqlConnection connection = IO.GetDBConnection()) { connection.Open(); /* prepare and execute a (hardcoded) query */ using (SqlCommand command = new SqlCommand(null, connection)) { command.CommandText = "select name from users where id=0"; command.Prepare(); using (SqlDataReader dr = command.ExecuteReader()) { /* POTENTIAL FLAW: Read data from a database query SqlDataReader */ data = dr.GetString(1); } } } } catch (SqlException exceptSql) { IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error with SQL statement"); } } } if (IO.StaticReturnsTrueOrFalse()) { if (data != null) { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ data = HttpUtility.UrlEncode(data, Encoding.UTF8); resp.AddHeader("Location", "/author.jsp?lang=" + data); } } else { if (data != null) { /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */ data = HttpUtility.UrlEncode(data, Encoding.UTF8); resp.AddHeader("Location", "/author.jsp?lang=" + data); } } }