/// <summary> /// Datatable数据填充如excel /// </summary> /// <param name="filename">excel文件名</param> /// <param name="dt"> 数据源</param> /// <param name="Response"> response响应</param> /// <param name="headerStr"> 表头标题</param> public static void DataTableToExcel(string filename, DataTable dt, string sheetname, HttpResponse Response, string headerStr) { MemoryStream ms = StreamData(dt, sheetname, headerStr) as MemoryStream; //as MemoryStream as用作转换,此处可以省略 try { Response.Clear(); Response.ContentType = "application/vnd.ms-excel"; Response.ContentEncoding = Encoding.UTF8; Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls")); Response.AddHeader("content-length", ms.Length.ToString()); Byte[] data = ms.ToArray(); //文件写入采用二进制流的方式。所以此处要转换为字节数组 Response.BinaryWrite(data); } catch { Response.Clear(); Response.ClearHeaders(); Response.Write("<script language=javascript>alert( '导出Excel错误'); </script>"); } Response.Flush(); Response.Close(); Response.End(); ms = null; }
private void DoExportForHishop(string csvFilename, string imagePath, System.Collections.Generic.List <ExportToLocal.ProductDetail> list) { using (System.IO.FileStream fileStream = new System.IO.FileStream(csvFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { string productCSVForEcdev = this.GetProductCSVForHishop(imagePath, list); System.Text.UnicodeEncoding unicodeEncoding = new System.Text.UnicodeEncoding(); //UTF8Encoding unicodeEncoding = new UTF8Encoding(); int byteCount = unicodeEncoding.GetByteCount(productCSVForEcdev); byte[] preamble = unicodeEncoding.GetPreamble(); byte[] array = new byte[preamble.Length + byteCount]; System.Buffer.BlockCopy(preamble, 0, array, 0, preamble.Length); unicodeEncoding.GetBytes(productCSVForEcdev.ToCharArray(), 0, productCSVForEcdev.Length, array, preamble.Length); fileStream.Write(array, 0, array.Length); } using (ZipFile zipFile = new ZipFile(System.Text.Encoding.Default)) { System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(imagePath); zipFile.CompressionLevel = CompressionLevel.Default; zipFile.AddFile(csvFilename, ""); zipFile.AddDirectory(directoryInfo.FullName, directoryInfo.Name); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ContentType = "application/x-zip-compressed"; response.ContentEncoding = this._encoding; response.AddHeader("Content-Disposition", "attachment; filename=" + directoryInfo.Name + ".zip"); response.Clear(); zipFile.Save(response.OutputStream); this._workDir.Delete(true); response.Flush(); response.Close(); } }
private int StreamFile(string FilePath, string DownloadAs) { DownloadAs = DownloadAs.Replace(" ", "_"); System.IO.FileInfo objFile = new System.IO.FileInfo(FilePath); if (!objFile.Exists) { return(0); } System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response; objResponse.ClearContent(); objResponse.ClearHeaders(); objResponse.AppendHeader("Content-Disposition", "attachment; filename=" + DownloadAs); objResponse.AppendHeader("Content-Length", objFile.Length.ToString()); string strContentType; strContentType = "application/octet-stream"; objResponse.ContentType = strContentType; WriteFile(objFile.FullName); objResponse.Flush(); objResponse.Close(); return(1); }
private void dtManageThemes_ItemCommand(object sender, System.Web.UI.WebControls.DataListCommandEventArgs e) { if (e.Item.ItemType == System.Web.UI.WebControls.ListItemType.Item || e.Item.ItemType == System.Web.UI.WebControls.ListItemType.AlternatingItem) { DisplayThemesImages displayThemesImages = (DisplayThemesImages)e.Item.FindControl("themeImg"); string text = this.Page.Request.MapPath(Globals.ApplicationPath + "/Templates/library/" + displayThemesImages.ThemeName); string text2 = this.Page.Request.MapPath(string.Concat(new string[] { Globals.ApplicationPath, "/Templates/sites/", Hidistro.Membership.Context.HiContext.Current.User.UserId.ToString(), "/", displayThemesImages.ThemeName })); if (e.CommandName == "btnUse") { this.UserTemplate(displayThemesImages.ThemeName); this.ShowMsg("成功修改了店铺模板", true); this.GetThemes(displayThemesImages.ThemeName); } if (e.CommandName == "download") { new System.IO.DirectoryInfo(text); System.Text.Encoding uTF = System.Text.Encoding.UTF8; using (ZipFile zipFile = new ZipFile()) { zipFile.CompressionLevel = CompressionLevel.Default; zipFile.AddDirectory(text2); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ContentType = "application/zip"; response.ContentEncoding = uTF; response.AddHeader("Content-Disposition", "attachment;filename=" + displayThemesImages.ThemeName + ".zip"); response.Clear(); zipFile.Save(response.OutputStream); response.Flush(); response.Close(); } } if (e.CommandName == "back") { try { if (!System.IO.Directory.Exists(text)) { this.ShowMsg("主站不存在该模板", false); } else { this.CopyDir(text, text2); this.ShowMsg("恢复店铺模板成功", true); } } catch { this.ShowMsg("恢复店铺模板失败", false); } } } }
public static void ResponseExcel <T>(System.Web.HttpResponse response, List <T> items) { try { string attachment = "attachment; filename=vauExcel.xls"; response.ClearContent(); response.AddHeader("content-disposition", attachment); response.ContentType = "application/vnd.ms-excel"; string tab = string.Empty; // Get all the properties PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { response.Write(tab + prop.Name); tab = "\t"; } response.Write("\n"); foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); if (values[i] != null) { response.Write(values[i].ToString().Trim() + "\t"); } else { response.Write("\t"); } } response.Write("\n"); } response.Flush(); response.Close(); } catch (Exception ex) { throw ex; } }
public void ExportGridViewToExcel(GridView grid, string fileName, HttpResponse Hresponse) { Hresponse.Clear(); Hresponse.Buffer = true; Hresponse.AddHeader("content-disposition", "attachment;fileName=" + fileName + ".xls"); Hresponse.Charset = ""; Hresponse.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); grid.RenderControl(hw); Hresponse.Output.Write(sw.ToString()); Hresponse.Flush(); Hresponse.Close(); //Hresponse.End(); Hresponse.OutputStream.Close(); }
private void dtManageThemes_ItemCommand(object sender, System.Web.UI.WebControls.DataListCommandEventArgs e) { if (e.Item.ItemType == System.Web.UI.WebControls.ListItemType.Item || e.Item.ItemType == System.Web.UI.WebControls.ListItemType.AlternatingItem) { string text = this.dtManageThemes.DataKeys[e.Item.ItemIndex].ToString(); string directoryName = this.Page.Request.MapPath(Globals.ApplicationPath + "/Templates/master/") + text; string text2 = this.Page.Request.MapPath(Globals.ApplicationPath + "/Templates/master/") + text; if (e.CommandName == "btnUse") { this.UserThems(text); this.ShowMsg("成功修改了商城模板", true); } if (e.CommandName == "download") { try { new System.IO.DirectoryInfo(text2); System.Text.Encoding uTF = System.Text.Encoding.UTF8; using (ZipFile zipFile = new ZipFile()) { zipFile.CompressionLevel = CompressionLevel.Default; if (System.IO.Directory.Exists(text2)) { zipFile.AddDirectory(text2); } else { zipFile.AddDirectory(directoryName); } System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ContentType = "application/zip"; response.ContentEncoding = uTF; response.AddHeader("Content-Disposition", "attachment;filename=" + text + ".zip"); response.Clear(); zipFile.Save(response.OutputStream); response.Flush(); response.Close(); } } catch (System.Exception ex) { throw ex; } } } }
public void publishReportForWeb(Siberix.Report.Report Report) { try { System.Web.HttpContext context = System.Web.HttpContext.Current; System.Web.HttpResponse response = context.Response; response.Clear(); //PDF response.ContentType = "application/pdf"; response.AddHeader("content-disposition", "attachment; filename=report-" + string.Format("{0}.pdf", DateTime.Now.ToString("MMddyy"))); Report.Publish(response.OutputStream, Siberix.Report.FileFormat.PDF); HttpContext.Current.ApplicationInstance.CompleteRequest(); response.Close(); } catch (Exception ex) { } }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.Close(); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); return(false); } }
public override void Close() { _httpResponse.Close(); }
public override void Close() { w.Close(); }
public void Methods_Deny_Unrestricted () { HttpResponse response = new HttpResponse (writer); response.AddCacheItemDependencies (new ArrayList ()); response.AddCacheItemDependency (String.Empty); response.AddFileDependencies (new ArrayList ()); response.AddFileDependency (fname); response.AddCacheDependency (new CacheDependency[0]); response.AddCacheItemDependencies (new string [0]); response.AddFileDependencies (new string [0]); try { response.AppendCookie (new HttpCookie ("mono")); } catch (NullReferenceException) { // ms } try { Assert.IsNull (response.ApplyAppPathModifier (null), "ApplyAppPathModifier"); } catch (NullReferenceException) { // ms } try { response.Clear (); } catch (NullReferenceException) { // ms } try { response.ClearContent (); } catch (NullReferenceException) { // ms } try { response.ClearHeaders (); } catch (NullReferenceException) { // ms } try { response.Redirect ("http://www.mono-project.com"); } catch (NullReferenceException) { // ms } try { response.Redirect ("http://www.mono-project.com", false); } catch (NullReferenceException) { // ms } try { response.SetCookie (new HttpCookie ("mono")); } catch (NullReferenceException) { // ms } response.Write (String.Empty); response.Write (Char.MinValue); response.Write (new char[0], 0, 0); response.Write (this); response.WriteSubstitution (new HttpResponseSubstitutionCallback (Callback)); response.Flush (); response.Close (); try { response.End (); } catch (NullReferenceException) { // ms } }
/// <summary> /// 将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。 /// </summary> /// <param name="filePath"></param> /// <param name="response"></param> public virtual bool TransmitFile(string fileName, string filePath, HttpResponse Response) { #region var flag = false; using (ImpersonateUser iu = new ImpersonateUser()) { ImpersonateUser.ValidUser(iu, _FileServer.Indentity); //if (File.Exists(filePath)) //{ // response.TransmitFile(filePath); // flag = true; //} System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 byte[] buffer = new byte[ChunkSize]; Response.Clear(); System.IO.FileStream fileStream = System.IO.File.OpenRead(filePath); long dataTotalLength = fileStream.Length; int readDataLength = 0; while (dataTotalLength > 0 && Response.IsClientConnected) { readDataLength = fileStream.Read(buffer, 0, Convert.ToInt32(ChunkSize)); Response.OutputStream.Write(buffer, 0, readDataLength); Response.Flush(); dataTotalLength = dataTotalLength - readDataLength; } Response.Close(); flag = true; } } return flag; #endregion }
public void ProcessRequest(HttpContext context) { string picPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "App_Data", "RSVGConverter", "chartExport"); string fileName = Path.ChangeExtension(picPath, "svg"); string downloadFileName = context.Request.Params["type"].ToString() + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + context.Request.Params["output_format"].ToString(); string svg = (context.Request.Params["data"].ToString()); try { string newSvg = Uri.UnescapeDataString(svg); Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.UseShellExecute = false; p.StartInfo = info; p.Start(); /*var stream = newSvg.ToString(); * * using (StreamWriter sw = new StreamWriter(fileName)) * { * sw.WriteLine(stream); * }*/ File.WriteAllText(fileName, newSvg); fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1); using (StreamWriter sw = p.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine(context.Request.PhysicalApplicationPath.Split(':')[0] + ":"); sw.WriteLine("cd " + Path.Combine(context.Request.PhysicalApplicationPath, "App_Data", "RSVGConverter")); if (context.Request.Params["output_format"].ToString() == "pdf") { sw.WriteLine("rsvg-convert -o " + downloadFileName + " -b white -f pdf chartExport.svg"); } else if (context.Request.Params["output_format"].ToString() == "jpg") { sw.WriteLine("rsvg-convert -o " + downloadFileName + " -b white -f jpg chartExport.svg"); } else { sw.WriteLine("rsvg-convert -o " + downloadFileName + " -b white -f png chartExport.svg"); } } sw.Close(); sw.Dispose(); } Thread.Sleep(900); System.Web.HttpResponse response = context.Response; response.ContentType = "application/octet-stream"; response.AddHeader("Content-Disposition", "attachment; filename=" + downloadFileName + ";"); response.WriteFile(Path.Combine(context.Request.PhysicalApplicationPath, "App_Data", "RSVGConverter", downloadFileName)); response.Flush(); response.Close(); } catch (Exception ex) { } finally { File.Delete(Path.Combine(context.Request.PhysicalApplicationPath, "App_Data", "RSVGConverter", downloadFileName)); } }
public static void HandleUpdate(HttpRequest Request, HttpResponse Response) { ClientControlsReader r = new ClientControlsReader(Request.InputStream); byte[] buffer; FileStream inFile = null; try { Response.ClearContent(); ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream); int updateManagerVersion = int.Parse(Request["updateManagerVersion"]); int controlReleaseVersion = int.Parse(Request["controlReleaseVersion"]); int processorArchitecture = int.Parse(Request["processorArchitecture"]); bool win95 = Request["platform"] == "95"; int winMajor = int.Parse(Request["winmajor"]); int winMinor = int.Parse(Request["winminor"]); string winCsd = Request["winCsd"]; string gdiplusVerString = Request["gdiplusver"].Trim(); bool hasGdiplus = gdiplusVerString != "0.0"; bool adminInstall = bool.Parse(Request["admin"]); bool hasMfc71 = bool.Parse(Request["mfc71"]); string[] files; if(!hasGdiplus) files = new string[] { "gdiplus", "minakortcontrols" }; else files = new string[] { "minakortcontrols" }; //Write version w.Write(updateManagerVersion); //Write response code w.Write(1); //Write response message string message = ""; w.WriteString(message); //Write file count w.Write(files.Length); //Write total file size int totalSize=0; foreach(string file in files) { string filePath = HttpContext.Current.Server.MapPath(Configuration.RootPath+ "public/" + file + ".dll"); totalSize += (int)new FileInfo(filePath).Length; } w.Write(totalSize); //Write files foreach(string file in files) { string clientFileName; if(file == "minakortcontrols") { w.Write((byte)(1)); clientFileName = "minakortcontrols.2.dll"; } else { w.Write((byte)(0)); clientFileName = "gdiplus.dll"; } //Write client file name w.WriteString(clientFileName); string filePath = HttpContext.Current.Server.MapPath(Configuration.RootPath+ "public/" + file + ".dll"); inFile = new FileStream(filePath, FileMode.Open, FileAccess.Read); w.Write((int)inFile.Length); buffer = new byte[inFile.Length]; inFile.Read(buffer,0,buffer.Length); w.Write(buffer); inFile.Close(); inFile = null; } } finally { if(inFile != null) inFile.Close(); Response.Flush(); Response.Close(); Response.End(); } }
static void FinalErrorWrite (HttpResponse response, string error) { try { response.Write (error); response.Flush (true); } catch { response.Close (); } }
public override void Put(HttpResponse response, string relativePath, byte[] data) { if (data.Length < 1) { response.StatusCode = 500; response.Close(); return; } var filename = "UploadedFile.bin".GenerateTemporaryFilename(); File.WriteAllBytes(filename, data); HandleFile(filename).ContinueWith(antecedent => { if (antecedent.IsFaulted) { var e = antecedent.Exception.InnerException; HandleException(e); response.StatusCode = 500; response.Close(); } else { response.StatusCode = antecedent.Result; response.Close(); } }).Wait(); filename.TryHardToDelete(); }
public override void Get(HttpResponse response, string relativePath, UrlEncodedMessage message) { if (string.IsNullOrEmpty(message["action"])) { response.StatusCode = 200; response.Write("No Action Specified."); } switch (message["action"]) { case "add": if (!string.IsNullOrEmpty(message["location"])) { try { var uri = new Uri(message["location"]); if (Peek(uri)) { var filename = "UploadedFile.bin".GenerateTemporaryFilename(); var rf = new RemoteFile(uri, filename); rf.Get(); if (File.Exists(filename)) { HandleFile(filename).ContinueWith(antecedent => { if (antecedent.IsFaulted) { var e = antecedent.Exception.InnerException; HandleException(e); response.StatusCode = 500; response.Close(); } else { response.StatusCode = antecedent.Result; response.Close(); } }).Wait(); return; } } } catch { } } break; case "validate": Validate().ContinueWith(antecedent => { if (antecedent.IsFaulted) { var e = antecedent.Exception.InnerException; HandleException(e); response.StatusCode = 500; response.Close(); } else { response.StatusCode = antecedent.Result; response.Close(); } }).Wait(); return; break; case "makewebpi": var txt = RegenerateWebPI(); response.ContentType = "application/xml"; response.StatusCode = 200; response.Write(txt); // response.Close(); return; case "test": var txt2 = "Hello World"; // response.ContentType = "application/text"; response.StatusCode = 200; response.Write(txt2); // response.Close(); return; } response.StatusCode = 500; response.Close(); }
private void downloadFile(string newFile, bool delete) { try { if (newFile != "") { FileInfo fle = new FileInfo(newFile); if (fle.Extension == "") { string tempath = System.IO.Path.GetTempPath(); if (!File.Exists(tempath + fle.Name + ".xml")) { File.Copy(newFile, tempath + fle.Name + ".xml"); } newFile = tempath + fle.Name + ".xml"; } } if (!File.Exists(newFile)) { lblSearchError.Text = "No File Exists at specified location."; return; } if (newFile != null && newFile != string.Empty) { System.Web.HttpResponse fileResponse = System.Web.HttpContext.Current.Response; fileResponse.Clear(); fileResponse.ClearHeaders(); System.IO.FileInfo fileToDownload = new System.IO.FileInfo(newFile); if (fileToDownload.Extension.Contains(".pdf")) { fileResponse.ContentType = "application/pdf"; } else if (fileToDownload.Extension.Contains(".doc")) { fileResponse.ContentType = "application/msword"; } else { fileResponse.ContentType = "text/plain"; } fileResponse.AppendHeader("Content-Disposition", "Attachment; Filename=\"" + fileToDownload.Name + "\""); fileResponse.Flush(); if (File.Exists(fileToDownload.FullName)) { fileResponse.WriteFile(fileToDownload.FullName); //fileResponse.End(); fileResponse.Flush(); fileResponse.Close(); if (delete) { File.Delete(fileToDownload.FullName); } } else { lblSearchError.Text = "No File Exists at specified location."; } } } catch (Exception ex) { lblSearchError.Text = ex.Message; } }
public override void Post(HttpResponse response, string relativePath, UrlEncodedMessage message) { var payload = message["payload"]; if( payload == null ) { response.StatusCode = 500; response.Close(); return; } Logger.Message("payload = {0}",payload); try { dynamic json = JObject.Parse(payload); Logger.Message("MSG Process begin {0}", json.commits.Count); var count = json.commits.Count; var doSiteRebuild = false; for (int i = 0; i < count; i++) { string username = json.commits[i].author.email.Value; var atSym = username.IndexOf('@'); if( atSym > -1 ) { username = username.Substring(0, atSym); } var commitMessage = json.commits[i].message.Value; var repository = json.repository.name.Value; var url = (string)json.commits[i].url.Value; if (repository == "coapp.org") { doSiteRebuild = true; } Bitly.Shorten(url).ContinueWith( (bitlyAntecedent) => { var commitUrl = bitlyAntecedent.Result; var handle = _aliases.ContainsKey(username) ? _aliases[username] : username; var sz = repository.Length + handle.Length + commitUrl.Length + commitMessage.Length + 10; var n = 140 - sz; if (n < 0) { commitMessage = commitMessage.Substring(0, (commitMessage.Length + n) - 1) + "\u2026"; } _tweeter.Tweet("{0} => {1} via {2} {3}", repository, commitMessage, handle, commitUrl); Logger.Message("{0} => {1} via {2} {3}", repository, commitMessage, handle, commitUrl); }); } // just rebuild the site once for a given batch of rebuild commit messages. if( doSiteRebuild) { Task.Factory.StartNew(() => { try { Logger.Message("Rebuilding website."); Bus.SendRegenerateSiteMessage(); } catch( Exception e ) { HandleException(e); } }); } } catch(Exception e) { Logger.Error("Error handling uploaded package: {0} -- {1}\r\n{2}", e.GetType(), e.Message, e.StackTrace); HandleException(e); response.StatusCode = 500; response.Close(); } }
public static void HandleUserLookup(HttpRequest Request, HttpResponse Response, Guid userId) { try { ClientControlsReader r = new ClientControlsReader(Request.InputStream); Response.ClearContent(); ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream); w.Write(1); string query = Request["userquery"]; //Write result code if(query == null || query.Length == 0) { w.Write(-1); return; } else w.Write(0); query = "%"+query+"%"; ArrayList data = new ArrayList(); using(Db db = new Db()) { db.CommandText = @" SELECT id, fullNameClean as fullName, username, email FROM tMember WHERE fullName LIKE @q OR email LIKE @q OR username LIKE @q ORDER BY fullNameClean ASC "; db.AddParameter("@q", query); while(db.Read()) { UserInfo user = new UserInfo(); user.username = (string)db["username"]; user.id = (Guid)db["id"]; user.email = db["email"] as string; user.name = (string)db["fullName"]; data.Add(user); } } w.Write((int)data.Count); foreach(object o in data) { if(o is UserInfo) { w.Write((byte)0); UserInfo user = (UserInfo)o; w.Write(user.id.ToByteArray()); w.WriteString(user.username); w.WriteString(user.email); w.WriteString(user.name); } } int a = 3; } finally { Response.Flush(); Response.Close(); Response.End(); } }
private void MakePdfReportButton_OnClick(object sender, EventArgs e) { var db = new SagittaDBEntities(); var dbProductEntities = db.Products; //SqlCommand allProducts = new SqlCommand("SELECT * FROM Products", db); DataRow dr = GetData("SELECT * FROM Products where VendorId = 10").Rows[0]; Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f); Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL); using (MemoryStream memoryStream = new MemoryStream()) { var writer = PdfWriter.GetInstance(document, memoryStream); // System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; //var phrase; //var cell; //var table; //Color color = null; document.Open(); document.NewPage(); //Header table var table = new PdfPTable(2); table.TotalWidth = 50f; table.LockedWidth = true; table.SetWidths(new float[] { 0.3f, 0.7f }); //Separater Line DrawLine(writer, 25f, document.Top - 79f, document.PageSize.Width - 25f, document.Top - 79f); DrawLine(writer, 25f, document.Top - 80f, document.PageSize.Width - 25f, document.Top - 80f); document.Add(table); table = new PdfPTable(2); table.HorizontalAlignment = Element.ALIGN_LEFT; table.SetWidths(new float[] { 0.3f, 1f }); table.SpacingBefore = 20f; //Vendor Details var cell = PhraseCell(new Phrase("Vendor Record", FontFactory.GetFont("Arial", 12, Font.UNDERLINE)), PdfPCell.ALIGN_CENTER); cell.Colspan = 2; table.AddCell(cell); cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER); cell.Colspan = 2; cell.PaddingBottom = 30f; table.AddCell(cell); //Name var phrase = new Phrase(); phrase.Add(new Chunk(dr["VendorName"] + "\n", FontFactory.GetFont("Arial", 10, Font.BOLD))); phrase.Add(new Chunk("(" + dr["Title"].ToString() + ")", FontFactory.GetFont("Arial", 8, Font.BOLD))); cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT); cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE; table.AddCell(cell); document.Add(table); DrawLine(writer, 160f, 80f, 160f, 690f); DrawLine(writer, 115f, document.Top - 200f, document.PageSize.Width - 100f, document.Top - 200f); table = new PdfPTable(2); table.SetWidths(new float[] { 0.5f, 2f }); table.TotalWidth = 340f; table.LockedWidth = true; table.SpacingBefore = 20f; table.HorizontalAlignment = Element.ALIGN_RIGHT; document.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.ClearContent(); Response.Clear(); Response.ContentType = "application/pdf"; Response.AddHeader("Pdf Report", "attachment; filename=Report.pdf"); Response.ContentType = "application/pdf"; Response.Buffer = true; Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.BinaryWrite(bytes); Response.End(); Response.Close(); } //using (TeamWorkEntities cn = new TeamWorkEntities()) //{ // FileStream fStream = File.OpenRead("E:\\MyFiles\\TempReport.pdf"); // byte[] contents = new byte[fStream.Length]; // fStream.Read(contents, 0, (int)fStream.Length); // fStream.Close(); // using (SqlCommand cmd = new SqlCommand("insert into SavePDFTable " + "(PDFFile)values(@data)")) // { // cmd.Parameters.Add("@data", contents); // cmd.ExecuteNonQuery(); // Console.Write("Pdf File Save in Dab"); // } //} }
/// <summary> /// 将DataTable导出到Excel /// </summary> /// <param name="dt">DataTable</param> /// <param name="fileName">仅文件名(非路径)</param> /// <returns>返回Excel文件绝对路径</returns> public void ExportDataSetToExcel(DataTable dt, string fileName, System.Web.HttpResponse Response) { #region 表头 HSSFWorkbook hssfworkbook = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet hssfSheet = hssfworkbook.CreateSheet(fileName); hssfSheet.DefaultColumnWidth = 10; hssfSheet.SetColumnWidth(0, 10 * 256); hssfSheet.SetColumnWidth(3, 10 * 256); // 表头 NPOI.SS.UserModel.IRow tagRow0 = hssfSheet.CreateRow(0); tagRow0.Height = 40 * 40; ICell cell0 = tagRow0.CreateCell(0); //设置单元格内容 cell0.SetCellValue("力诺瑞特制造工厂"); hssfSheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 13)); NPOI.SS.UserModel.IRow tagRow1 = hssfSheet.CreateRow(1); tagRow1.Height = 30 * 20; ICell cell1 = tagRow1.CreateCell(0); //设置单元格内容 cell1.SetCellValue("反冲材料补料单"); hssfSheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, 13)); NPOI.SS.UserModel.ICellStyle tagStyle = hssfworkbook.CreateCellStyle(); tagStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; tagStyle.VerticalAlignment = VerticalAlignment.Center; //tagStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN; //tagStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN; IFont font = hssfworkbook.CreateFont(); font.FontHeightInPoints = 16; font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold; font.FontName = "宋体"; tagStyle.SetFont(font);//HEAD 样式 cell0.CellStyle = tagStyle; NPOI.SS.UserModel.ICellStyle tagStyle1 = hssfworkbook.CreateCellStyle(); tagStyle1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; tagStyle1.VerticalAlignment = VerticalAlignment.Center; cell1.CellStyle = tagStyle1; // 标题样式 NPOI.SS.UserModel.ICellStyle cellStyle1 = hssfworkbook.CreateCellStyle(); cellStyle1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; cellStyle1.VerticalAlignment = VerticalAlignment.Center; cellStyle1.BorderBottom = NPOI.SS.UserModel.BorderStyle.None; cellStyle1.BorderLeft = NPOI.SS.UserModel.BorderStyle.None; cellStyle1.BorderRight = NPOI.SS.UserModel.BorderStyle.None; cellStyle1.BorderTop = NPOI.SS.UserModel.BorderStyle.None; #endregion //数据样式 NPOI.SS.UserModel.ICellStyle cellStyle = hssfworkbook.CreateCellStyle(); cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Black.Index; cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.Black.Index; cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.RightBorderColor = NPOI.HSSF.Util.HSSFColor.Black.Index; cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.TopBorderColor = NPOI.HSSF.Util.HSSFColor.Black.Index; #region 表数据 // 表数据 for (int k = 0; k < 2; k++) { DataRow dr = dt.Rows[k]; NPOI.SS.UserModel.IRow row = hssfSheet.CreateRow(k + 2); row.Height = 30 * 20; for (int i = 0; i < 2; i += 2) { row.CreateCell(i).SetCellValue(dr[0].ToString()); row.GetCell(i).CellStyle = cellStyle1; } for (int i = 2; i < 5; i += 3) { row.CreateCell(i).SetCellValue(dr[1].ToString()); row.GetCell(i).CellStyle = cellStyle1; } for (int i = 5; i < 7; i += 2) { row.CreateCell(i).SetCellValue(dr[2].ToString()); row.GetCell(i).CellStyle = cellStyle1; } for (int i = 7; i < 9; i += 2) { row.CreateCell(i).SetCellValue(dr[3].ToString()); row.GetCell(i).CellStyle = cellStyle1; } for (int i = 9; i < 11; i += 2) { row.CreateCell(i).SetCellValue(dr[4].ToString()); row.GetCell(i).CellStyle = cellStyle1; } for (int i = 11; i < 14; i += 3) { row.CreateCell(i).SetCellValue(dr[5].ToString()); row.GetCell(i).CellStyle = cellStyle1; } row.CreateCell(1).SetCellValue(""); row.GetCell(1).CellStyle = cellStyle1; row.CreateCell(3).SetCellValue(""); row.GetCell(3).CellStyle = cellStyle1; row.CreateCell(4).SetCellValue(""); row.GetCell(4).CellStyle = cellStyle1; row.CreateCell(6).SetCellValue(""); row.GetCell(6).CellStyle = cellStyle1; row.CreateCell(8).SetCellValue(""); row.GetCell(8).CellStyle = cellStyle1; row.CreateCell(10).SetCellValue(""); row.GetCell(10).CellStyle = cellStyle1; row.CreateCell(12).SetCellValue(""); row.GetCell(12).CellStyle = cellStyle1; row.CreateCell(13).SetCellValue(""); row.GetCell(13).CellStyle = cellStyle1; hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 0, 1)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 2, 4)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 5, 6)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 7, 8)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 9, 10)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 11, 13)); } // 表数据 for (int k = 2; k < dt.Rows.Count; k++) { if (k == dt.Rows.Count - 1) { DataRow drlast = dt.Rows[k]; NPOI.SS.UserModel.IRow rowlast = hssfSheet.CreateRow(k + 2); rowlast.Height = 30 * 20; for (int i = 0; i < 2; i++) { rowlast.CreateCell(i).SetCellValue(drlast[0].ToString()); rowlast.GetCell(i).CellStyle = cellStyle1; } for (int i = 2; i < 4; i++) { rowlast.CreateCell(i).SetCellValue(""); rowlast.GetCell(i).CellStyle = cellStyle1; } for (int i = 4; i < 6; i++) { rowlast.CreateCell(i).SetCellValue(drlast[2].ToString()); rowlast.GetCell(i).CellStyle = cellStyle1; } for (int i = 6; i < 8; i++) { rowlast.CreateCell(i).SetCellValue(""); rowlast.GetCell(i).CellStyle = cellStyle1; } for (int i = 8; i < 10; i++) { rowlast.CreateCell(i).SetCellValue(drlast[4].ToString()); rowlast.GetCell(i).CellStyle = cellStyle1; } for (int i = 10; i < 14; i++) { rowlast.CreateCell(i).SetCellValue(""); rowlast.GetCell(i).CellStyle = cellStyle1; } //hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 1, 7)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 0, 1)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 2, 3)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 4, 5)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 6, 7)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 8, 9)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 10, 13)); } else { DataRow dr = dt.Rows[k]; NPOI.SS.UserModel.IRow row = hssfSheet.CreateRow(k + 2); row.Height = 30 * 20; for (int i = 0; i < 1; i++) { row.CreateCell(i).SetCellValue(dr[i].ToString()); row.GetCell(i).CellStyle = cellStyle; } for (int i = 1; i < 3; i++) { row.CreateCell(i).SetCellValue(dr[1].ToString()); row.GetCell(i).CellStyle = cellStyle; } for (int i = 3; i < 6; i++) { row.CreateCell(i).SetCellValue(dr[2].ToString()); row.GetCell(i).CellStyle = cellStyle; } for (int i = 6; i < 8; i++) { row.CreateCell(i).SetCellValue(dr[3].ToString()); row.GetCell(i).CellStyle = cellStyle; } for (int i = 8; i < 10; i++) { row.CreateCell(i).SetCellValue(dr[4].ToString()); row.GetCell(i).CellStyle = cellStyle; } for (int i = 10; i < 12; i++) { row.CreateCell(i).SetCellValue(dr[5].ToString()); row.GetCell(i).CellStyle = cellStyle; } for (int i = 12; i < 14; i++) { row.CreateCell(i).SetCellValue(dr[6].ToString()); row.GetCell(i).CellStyle = cellStyle; } row.CreateCell(2).SetCellValue(""); row.GetCell(2).CellStyle = cellStyle; row.CreateCell(4).SetCellValue(""); row.GetCell(4).CellStyle = cellStyle; row.CreateCell(5).SetCellValue(""); row.GetCell(5).CellStyle = cellStyle; row.CreateCell(7).SetCellValue(""); row.GetCell(7).CellStyle = cellStyle; row.CreateCell(9).SetCellValue(""); row.GetCell(9).CellStyle = cellStyle; row.CreateCell(11).SetCellValue(""); row.GetCell(11).CellStyle = cellStyle; row.CreateCell(13).SetCellValue(""); row.GetCell(13).CellStyle = cellStyle; #region 合并单元格 hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 1, 2)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 3, 5)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 6, 7)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 8, 9)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 10, 11)); hssfSheet.AddMergedRegion(new CellRangeAddress(k + 2, k + 2, 12, 13)); #endregion } } #endregion hssfSheet.PrintSetup.NoColor = true; hssfSheet.PrintSetup.Landscape = true; hssfSheet.PrintSetup.PaperSize = (short)PaperSize.A4; //是否自适应界面 hssfSheet.FitToPage = true; string uploadPath = HttpContext.Current.Request.PhysicalApplicationPath + "Mfg/Temp/"; if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } try { FileStream file = new FileStream(uploadPath + fileName + ".xls", FileMode.Create); hssfworkbook.Write(file); file.Close(); var basePath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath); //return (basePath + "Temp/" + fileName + ".xls"); string fileURL = HttpContext.Current.Server.MapPath((basePath + "Mfg/Temp/" + fileName + ".xls"));//文件路径,可用相对路径 FileInfo fileInfo = new FileInfo(fileURL); Response.Clear(); using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ELCO_ConnectionString"].ToString())) { SqlCommand cmd = new SqlCommand(); SqlTransaction transaction = null; try { conn.Open(); transaction = conn.BeginTransaction(); cmd.Transaction = transaction; cmd.Connection = conn; cmd.CommandType = CommandType.Text; string str1 = string.Empty; for (int i = 0; i < materialid.Length; i++) { str1 = "update MFG_WIP_BKF_MTL_Record set Status='3',ConfirmTime=GETDATE(),ConfirmUser='******',PrintTime=GETDATE() where ID=" + materialid[i]; cmd.CommandText = str1; cmd.ExecuteNonQuery(); } Response.AddHeader("content-disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(fileInfo.Name.ToString())); //文件名 Response.AppendHeader("content-type", "application/x-msexcel"); Response.AddHeader("content-length", fileInfo.Length.ToString()); //文件大小 Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.Default; Response.WriteFile(fileURL); Response.Flush(); Response.Close(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); Response.Write(ex.Message); } } } catch (Exception ex) { Response.Write(ex.Message); } }
/// <summary> /// Ends the request if the maximum request length is exceeded. /// </summary> /// <param name="response">The HTTP response.</param> void EndRequestOnRequestLengthExceeded(HttpResponse response) { response.StatusCode = 400; // Generic 400 error just like ASP.Net response.StatusDescription = "Maximum request size exceeded"; response.Flush(); response.Close(); }
public static void HandleUploadControl(HttpRequest Request, HttpResponse Response) { Guid userId = Guid.Empty; try { HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName); if(cookie != null && cookie.Value != null && cookie.Value.Length > 0) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); if(ticket != null && ticket.Name != null && ticket.Name.Length > 0) userId = new Guid(ticket.Name); } if(userId == Guid.Empty) userId = Principal.MemberIdOrZero; } catch(Exception exc) { Log.LogDebug(exc); } string v = Request["v"]; int version = v!=null&&v.Length>0?int.Parse(v):0; string action = Request["action"]; try { Response.ClearContent(); if(action == "upload") HandleUploadControlUpload(Request, Response, userId); else if(action == "login") HandleUploadControlLogin(Request, Response); else if(action == "updatedetails") HandleDetailsUpdate(Request, Response, userId); else if(action == "userlookup") HandleUserLookup(Request, Response, userId); else if(action == "categorylookup") HandleCategoryLookup(Request, Response, userId); else if(action == "createcategory") HandleCreateCategory(Request, Response, userId); else { BinaryWriter w = new BinaryWriter(Response.OutputStream); w.Write(new byte[8]); } } finally { Response.Flush(); Response.Close(); Response.End(); } }
/// <summary> /// Http context handler. /// </summary> /// <param name="context">The http context.</param> public override void HttpContext(HttpContext context) { System.Web.HttpRequest request = null; System.Web.HttpResponse response = null; bool isServerError = false; bool keepAlive = true; bool isError = true; try { request = context.Request; response = context.Response; // If headers exist. if (request.Headers != null) { // Get the execution member. if (!String.IsNullOrEmpty(request.Headers["Member"])) { // Get the execution member. // Set the calling member. string executionMember = request.Headers["Member"].Trim(); response.AddHeader("Member", executionMember); response.AddHeader("ActionName", request.Headers["ActionName"]); // Create the chat state. Chat.ChatHttptState chatState = new Chat.ChatHttptState() { HttpContext = context, Member = new Net.Http.HttpContextMember(context), ExecutionMember = executionMember, ErrorCode = new Exceptions.ErrorCodeException("OK", 200) }; try { // Validate the current user token. bool isTokenValid = ValidateToken(chatState); } catch (Exceptions.ErrorCodeException exc) { // Get the error code. chatState.ErrorCode = exc; } catch (Exception ex) { // Internal error. chatState.ErrorCode = new Exceptions.ErrorCodeException(ex.Message, 500); } // Send a message back to the client indicating that // the message was recivied and was sent. CreateResponse(response, true, chatState.ErrorCode.ErrorCode, statusDescription: chatState.ErrorCode.Message); isError = false; } } else { // No headers have been found. keepAlive = false; throw new Exception("No headers have been found."); } // If error has occured. if (isError) { // Send an error response. response.StatusCode = 400; response.StatusDescription = "Bad Request"; response.AddHeader("Content-Length", (0).ToString()); response.Flush(); } } catch (Exception) { isServerError = true; } // If a server error has occured. if (isServerError) { // Make sure the response exists. if (response != null) { try { // Send an error response. response.StatusCode = 500; response.StatusDescription = "Internal server error"; response.AddHeader("Content-Length", (0).ToString()); response.Flush(); } catch { keepAlive = false; } } } // If do not keep alive. if (!keepAlive) { // Close the connection. if (response != null) { try { // Close the connection. response.Close(); } catch { } } } }
static void HandleCategoryLookup(HttpRequest Request, HttpResponse Response, Guid userId) { try { Response.ClearContent(); ClientControlsWriter w = new ClientControlsWriter(Response.OutputStream); //Version w.Write((int)1); //ResultCode if(userId == Guid.Empty) { w.Write((int)-1); return; } string categoryName = Request["categoryName"]; if(categoryName == null) categoryName = string.Empty; categoryName = categoryName.Trim(); if(!Validation.ValidateCategoryName(categoryName)) { w.Write((int)-2); return; } w.Write((int)0); // } result code. Database.MemberDetails details = Database.GetMemberDetails(null, userId); Guid existingId = Database.GetSubCategory(userId, details.HomeCategoryId, categoryName); Database.Category cat = null; if(existingId != Guid.Empty) cat = Database.GetCategoryInfo(userId, existingId); w.Write(existingId != Guid.Empty); w.Write(existingId.ToByteArray()); //canAddPermission w.Write(cat != null && cat.CurrentPermission >= Permission.Add); //securityPermission w.Write(cat != null && cat.CurrentPermission >= Permission.Owner); //TODO: shold be securitypermission. w.WriteString(cat != null?cat.Name:categoryName); //can't send email w.Write((byte)0x00); //can't share to friends w.Write((byte)0x00); //Write the permission entries on the category. if(existingId == Guid.Empty) w.Write(0); else { Guid groupId = Database.GetMemberGroup(userId, "$"+existingId); Database.GroupMember[] members = Database.EnumGroupMembers(userId, groupId); w.Write((uint)(members.Length-1)); //minus self foreach(Database.GroupMember member in members) { if(member.MemberId == userId) continue; Database.MemberDetails md = Database.GetMemberDetails(null, member.MemberId); w.Write((byte)0); w.Write(md.Id.ToByteArray()); w.WriteString(md.admin_username); w.WriteString(md.admin_email); w.WriteString(md.Name); w.Write((uint)0); w.Write((uint)0); w.Write((uint)0); w.Write((uint)0); } } } finally { Response.Flush(); Response.Close(); Response.End(); } }