private void ExportHeader() { string result = string.Empty; if (_structure != null) { result = _structure.ToString(); } if (_writer != null) { _writer.Write(result); _writer.Flush(); } }
public byte[] Generate(Models.WordList wordList) { MemoryStream mem = new MemoryStream(); Encoding encoding = new UTF8Encoding(false); using (StreamWriter streamWriter = new StreamWriter(mem, encoding)) { using (HtmlTextWriter writer = new HtmlTextWriter(streamWriter)) { writer.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); writer.WriteLine("<!DOCTYPE html>"); writer.WriteLine("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); writer.WriteLine("<head>"); WriteStyleSection(writer); writer.WriteLine("</head>"); writer.WriteLine("<body>"); foreach (WordForm wordForm in wordList.GetAllForms().OrderBy(wf => wf.Title)) { WriteWordForm(writer, wordForm); } writer.WriteLine("</body>"); writer.WriteLine("</html>"); writer.Flush(); } } return mem.ToArray(); }
public static string Render(RenderFunc func) { string content = string.Empty; using (MemoryStream ms = new MemoryStream()) { using (HtmlTextWriter htmlWriter = new HtmlTextWriter(new StreamWriter(ms))) { func(htmlWriter); htmlWriter.Flush(); } using (StreamReader rdr = new StreamReader(ms)) { rdr.BaseStream.Position = 0; content = rdr.ReadToEnd(); } } ITemplateEngine te = ServiceLocator.Instance.Resolve<ITemplateEngine>(); using (StringWriter sw = new StringWriter()) { te.Process(JContext.Current.ViewData, string.Empty, sw, content); return sw.GetStringBuilder().ToString(); } }
/// <summary> /// 获得设计时的HTML /// </summary> /// <returns>字符串</returns> public override string GetDesignTimeHtml() { try { string output = ""; Control oControl = ((Control)Component); StringBuilder strB = new StringBuilder(1024); using (StringWriter sw = new StringWriter(strB)) { HtmlTextWriter oWriter = new HtmlTextWriter(sw); oControl.RenderControl(oWriter); oWriter.Flush(); sw.Flush(); output = strB.ToString(); if (output == null ||output==String.Empty) { return GetEmptyDesignTimeHtml(); } return output ; } } catch (Exception ex) { return CreatePlaceHolderDesignTimeHtml(Resources.DeluxeWebResource.DesignerTimeErrorMessage + ex.ToString()); } }
public static void ToExcelF(System.Web.UI.HtmlControls.HtmlTable Table1, string FileName, string Title, string Head, string foot) { HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls"); //filename=Report.xls HttpContext.Current.Response.Charset = "UTF-8"; //UTF-8 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; //msword;image/JPEG;text/HTML;image/GIF;vnd.ms-excel //HttpContext.Current.Application.Page.EnableViewState = false; //Turn off the view state. System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); hw.WriteLine(@"<HTML>"); hw.WriteLine(@"<BODY>"); hw.WriteLine("<b>" + Title + "</b>"); //string Head = @"<table border=1><tr><td>1</td><td>2</td></tr><tr><td>3</td><td>4</td></tr></table>"; if (Head != "") { hw.WriteLine(Head); } Table1.RenderControl(hw); if (foot != "") { hw.WriteLine(foot); } hw.WriteLine(@"</BODY>"); hw.WriteLine(@"</HTML>"); hw.Flush(); hw.Close(); HttpContext.Current.Response.Write(tw.ToString()); //Write the HTML back to the browser. HttpContext.Current.Response.End(); }
/// <summary> /// 获取设计时HTML /// </summary> /// <returns></returns> public override string GetDesignTimeHtml() { try { TabControl oTabStrip = ((TabControl)Component); if (oTabStrip.Items == null || oTabStrip.Items.Count == 0) { return GetEmptyDesignTimeHtml(); } System.Text.StringBuilder oSB = new System.Text.StringBuilder(); StringWriter oStringWriter = new StringWriter(oSB); HtmlTextWriter oWriter = new HtmlTextWriter(oStringWriter); oTabStrip.RenderDownLevelContent(oWriter); oWriter.Flush(); oStringWriter.Flush(); return oSB.ToString(); } catch (Exception ex) { return CreatePlaceHolderDesignTimeHtml("生成设计时代码错误:\n\n" + ex.ToString()); } }
public new void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName) { EndpointHost.Config.AssertFeatures(Feature.Metadata); var operations = EndpointHost.ServiceOperations; if (httpReq.QueryString["xsd"] != null) { var xsdNo = Convert.ToInt32(httpReq.QueryString["xsd"]); var schemaSet = XsdUtils.GetXmlSchemaSet(operations.AllOperations.Types); var schemas = schemaSet.Schemas(); var i = 0; if (xsdNo >= schemas.Count) { throw new ArgumentOutOfRangeException("xsd"); } httpRes.ContentType = "text/xml"; foreach (XmlSchema schema in schemaSet.Schemas()) { if (xsdNo != i++) continue; schema.Write(httpRes.Output); break; } return; } var writer = new HtmlTextWriter(httpRes.Output); httpRes.ContentType = "text/html"; ProcessOperations(writer, httpReq); writer.Flush(); }
public static string GetHtml(HtmlGenericControl control) { StringBuilder s = new StringBuilder(); HtmlTextWriter tw = new HtmlTextWriter(new StringWriter(s)); control.RenderControl(tw); tw.Flush(); return s.ToString(); }
private static void EndForm(System.Web.UI.HtmlTextWriter writer) { writer.EndRender(); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); writer.Flush(); }
protected void ExportInventoryEquip_Click(object sender, EventArgs e) { try { string type = HttpContext.Current.Request.QueryString["type"]; DataTable dt = JsonToDataTable(hidExcelCenter.Value); string fileName = HttpUtility.UrlDecode("盘点单", System.Text.Encoding.UTF8) + DateTime.Now.ToShortDateString() + ".xls"; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); Response.Clear(); Response.Charset = "gb2312"; Response.ContentType = "application/vnd.ms-excel"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName)); Response.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>"); Response.Write(@"<table style='BORDER-COLLAPSE: collapse;' borderColor=#e5e5e5 height=40 cellPadding=1 width=250 align=center border=1> <thead> <tr> <td style='BACKGROUND:#e5e5e5;'>资产号</td> <td style='BACKGROUND:#e5e5e5;'>资产名称</td>" + (type == "2" ? "<td style='BACKGROUND:#e5e5e5;'>负责人</td>" : "") + (type == "0" ? "<td style='BACKGROUND:#e5e5e5;'>状态</td>" : "") + @"<td style='BACKGROUND:#e5e5e5;'>计量单位</td> <td style='BACKGROUND:#e5e5e5;'>存放地点</td> <td style='BACKGROUND:#e5e5e5;'>设备来源</td> <td style='BACKGROUND:#e5e5e5;'>是否拟盘亏</td> </tr> </thead><tbody>"); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { DataRow row = dt.Rows[i]; Response.Write(@"<tr><td >" + row["AssetNumber"].ToString() + @"</td> <td>" + row["AssetName"].ToString() + "</td>" + (type == "2" ? "<td>" + row["CreateName"].ToString() + "</td>" : "") + (type == "0" ? "<td>" + GetEquipStatusName(row["Status"].ToString()) + "</td>" : "") + "<td>" + row["Unit"].ToString() + @"</td> <td>" + row["Storage"].ToString() + @"</td> <td>" + GetEquipSource(row["EquipSource"].ToString()) + @"</td> <td>" + GetIsloss(row["loss"].ToString()) + "</td></tr>"); } } Response.Write(@"</tbody></table>"); Response.Write(tw.ToString()); Response.Write("</body></html>"); Response.End(); hw.Close(); hw.Flush(); tw.Close(); tw.Flush(); } catch (Exception ex) { } }
protected override void Render(HtmlTextWriter writer) { StringBuilder sb = new StringBuilder(); HtmlTextWriter tempWriter = new HtmlTextWriter(new StringWriter(sb)); base.Render(tempWriter); tempWriter.Flush(); tempWriter.Close(); writer.Write(MyCompany.Data.Localizer.Replace("Pages", Path.GetFileName(Request.PhysicalPath), sb.ToString())); }
protected override void Render(HtmlTextWriter writer) { if (this.CanCache) { // 将底层构建的内容都拦截到自定义的流中 var stringWriter = new StringWriter(); var htmlTextWriter = new HtmlTextWriter(stringWriter); // 这句话很重要,页面所有的元素要呈现为HTML内容都要经过它本身的Render()函数 // 而这个 htmlTextWriter 就贯穿于流程始末,拦截到所有元素呈现的内容 // 否则页面呈现的内容一个字符都获取不到 base.Render(htmlTextWriter); htmlTextWriter.Flush(); htmlTextWriter.Close(); // 这句话比上面那句 base.Render( htmlTextWriter ); 更重要。 // 原因就是,如果你想让页面呈现内容一字不差的发送到客户端就是这句话在起作用 // 这句话以及上面那句虽然很简单,但是如果你忽略了它们中的任意一句,它们会让你知道什么叫噩梦~! writer.Write(stringWriter); // 以下代码将由底层构建的用于呈现到客户端的内容保存到物理文件中,很简单 var htmlText = stringWriter.ToString(); stringWriter.Close(); stringWriter.Dispose(); // 保存页面最终呈现的内容到文件,并附加缓存有效期 // 好吧,这里使用文件的共享方式来控制对文件的并发写入控制 // 所以这里必须处理好异常,虽然不能写入但是至少我能做到让上面的代码呈现的页面内容顺利的响应到客户端 // 葛小亮 2015-12-22 try { if (!Directory.Exists(this.CachedPageFileFolderPath)) { Directory.CreateDirectory(this.CachedPageFileFolderPath); } using (var fs = File.Open(this.CachedPageFileFullName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) { fs.SetLength(0); // 清空原有文件的内容 var streamWriter = new StreamWriter(fs, Encoding.UTF8); streamWriter.WriteLine("<!-- expiry[{0}] -->", DateTime.Now.AddMinutes(this.CachedExpiryMinutes) .ToString("yyyy-MM-dd HH:mm:ss")); streamWriter.Write(htmlText); streamWriter.Flush(); streamWriter.Close(); } } catch (IOException) { // 隐藏掉由于IO操作导致的异常,例如:并发写文件因为不共享写入导致的错误。 } } else { base.Render(writer); } }
protected internal override void RenderChildren(HtmlTextWriter writer) { RenderChildrenWriter = null; if (IsInPartialRendering) { ScriptManager.AlternativeHtmlTextWriter altWriter = writer as ScriptManager.AlternativeHtmlTextWriter; if (altWriter == null) { altWriter = writer.InnerWriter as ScriptManager.AlternativeHtmlTextWriter; } if (altWriter == null) { UpdatePanel parentPanel = ParentPanel; if (parentPanel != null) { altWriter = parentPanel.RenderChildrenWriter; } } if (altWriter == null) { throw new InvalidOperationException("Internal error. Invalid writer object."); } // Used by nested panels (see bug #542441) RenderChildrenWriter = altWriter; try { HtmlTextWriter responseOutput = altWriter.ResponseOutput; StringBuilder sb = new StringBuilder(); HtmlTextWriter w = new HtmlTextWriter(new StringWriter(sb)); base.RenderChildren(w); w.Flush(); if (sb.Length > 0) { UpdatePanel parent = ParentPanel; if (parent != null && parent.ChildrenAsTriggers) { writer.Write(sb.ToString()); } else { ScriptManager.WriteCallbackPanel(responseOutput, this, sb); } } } finally { RenderChildrenWriter = null; } } else { base.RenderChildren(writer); } }
protected override void Render(HtmlTextWriter writer) { string layout = string.Empty; // remove contents before render it foreach (Control ctrl in ctrls) { Controls.Remove(ctrl); } using (MemoryStream ms = new MemoryStream()) { using (HtmlTextWriter htmlWriter = new HtmlTextWriter(new StreamWriter(ms))) { base.Render(htmlWriter); htmlWriter.Flush(); } using (StreamReader rdr = new StreamReader(ms)) { rdr.BaseStream.Position = 0; layout = rdr.ReadToEnd(); } } foreach (Control ctrl in ctrls) { string tag = "{" + ctrl.ID + "}"; if (layout.IndexOf(tag) == -1) throw new ArgumentException(string.Format("{0} not found!", tag)); string content = string.Empty; using (MemoryStream ms = new MemoryStream()) { using (HtmlTextWriter htmlwriter = new HtmlTextWriter(new StreamWriter(ms))) { ctrl.RenderControl(htmlwriter); htmlwriter.Flush(); } using (StreamReader rdr = new StreamReader(ms)) { rdr.BaseStream.Position = 0; content = rdr.ReadToEnd(); } } layout = layout.Replace(tag, content); } writer.Write(layout); }
public static string RenderControl(Control control) { using (var writer = new StringWriter()) using (var htmlWriter = new HtmlTextWriter(writer)) { control.RenderControl(htmlWriter); htmlWriter.Flush(); return writer.ToString(); } }
public string Render(string newLine) { StringWriter sw = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(sw, ""); writer.NewLine = newLine; base.Render(writer); writer.Flush(); writer.Close(); string result = sw.GetStringBuilder().ToString(); return result; }
public void Compression(System.Web.UI.HtmlTextWriter writer) { StringWriter sr = new StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(sr); base.Render(tw); tw.Flush(); tw.Dispose(); StringBuilder sb = new StringBuilder(sr.ToString()); string outhtml = Regex.Replace(sb.ToString(), "\\r+\\n+\\s+", string.Empty); writer.Write(outhtml); sr.Dispose(); }
public override void encodeChildren(FacesContext context) { System.Diagnostics.Trace.WriteLine("encodeChildren"); // reset _facesContext if changed between action and render phases (such portal). _facesContext = null; IHttpHandler jsfHandler = EnterThread(); bool wasException = false; try { if (!context.getResponseComplete()) { if (IsCallback) { string result = ProcessGetCallbackResult(_callbackTarget, _callbackEventError); HtmlTextWriter callbackOutput = new HtmlTextWriter(Response.Output); callbackOutput.Write(result); callbackOutput.Flush(); return; } // ensure lifecycle complete. if (!IsLoaded) { ProcessLoad(); RestoreValidatorsState(_validatorsState); } if (!IsPrerendered) { ProcessLoadComplete(); } RenderPage(); } } catch (Exception ex) { wasException = true; HandleException(ex); } finally { try { if (!wasException) { ProcessUnload(); } } finally { ExitThread(jsfHandler); } } }
public string GetHtml() { // populate the control this.PopulateControl(); StringWriter buffer = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(buffer); this.RenderControl(writer); writer.Flush(); return buffer.ToString().Trim(); }
protected void Page_Load(object sender, EventArgs e) { StringBuilder renderedOutput = null; StringWriter strWriter = null; HtmlTextWriter tWriter = null; try { renderedOutput = new StringBuilder(); strWriter = new StringWriter( renderedOutput ); tWriter = new HtmlTextWriter( strWriter ); view.RenderControl( tWriter ); tWriter.Flush(); strWriter.Flush(); Response.Write( renderedOutput.ToString() ); Response.Flush(); } catch( Exception ex ) { SendJson( new Framework.API.ReturnObject { Error = true, Message = "There was an error loading the requested page.", Result = new { Message = ex.Message, Type = ex.GetType().FullName, StackTrace = ex.StackTrace } } ); } finally { if( tWriter != null ) { tWriter.Close(); tWriter.Dispose(); tWriter = null; } if( strWriter != null ) { strWriter.Close(); strWriter.Dispose(); strWriter = null; } } Response.End(); }
public static string CaptureViewOutput(Controller controller, ViewResult view) { var builder = new StringBuilder(); using (var stringWriter = new StringWriter(builder)) { using (var htmlTextWriter = new HtmlTextWriter(stringWriter)) { var currentContext = controller.ControllerContext.HttpContext; try { // get the Request and User objects from the current, unchanged context var currentRequest = HttpContext.Current.ApplicationInstance.Context.Request; var currentUser = HttpContext.Current.ApplicationInstance.Context.User; // create our new HttpResponse object containing our HtmlTextWriter var newResponse = new HttpResponse(htmlTextWriter); // create a new HttpContext object using our new Response object and the existing Request and User objects var newContext = new HttpContextWrapper( new HttpContext(currentRequest, newResponse) { User = currentUser }); // swap in our new HttpContext object - output from this controller is now going to our HtmlTextWriter object controller.ControllerContext.HttpContext = newContext; // Run the ViewResult view.ExecuteResult(controller.ControllerContext); // flush the output newResponse.Flush(); htmlTextWriter.Flush(); stringWriter.Flush(); } finally { // and no matter what happens, set the context back! controller.ControllerContext.HttpContext = currentContext; } } } // our StringBuilder object now contains the output of the ViewResult object return builder.ToString(); }
protected override void Render(System.Web.UI.HtmlTextWriter writer) { System.IO.StringWriter stringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter); base.Render(htmlTextWriter); htmlTextWriter.Flush(); htmlTextWriter.Close(); string text = stringWriter.ToString(); text = text.Trim(); string webUrlStart = Globals.GetWebUrlStart(); text = text.Replace("<img src=\"" + webUrlStart + "/Storage/master/product/", "<img class='imgLazyLoading' src=\"/Utility/pics/lazy-ico.gif\" data-original=\"" + webUrlStart + "/Storage/master/product/"); text = text.Replace("<img src=\"/Storage/master/product/", "<img class='imgLazyLoading' src=\"/Utility/pics/lazy-ico.gif\" data-original=\"/Storage/master/product/"); writer.Write(text); }
public static void ToExcelE(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName) { HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls"); //filename=Report.xls HttpContext.Current.Response.Charset = "GB2312"; //UTF-8 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); DataGrid2Excel.RenderControl(hw); //Get the HTML for the control. hw.Flush(); hw.Close(); HttpContext.Current.Response.Write(tw.ToString()); //Write the HTML back to the browser. HttpContext.Current.Response.End(); }
protected override void Render( HtmlTextWriter writer ) { using ( var memoryStream = new MemoryStream( ) ) { using ( var streamWriter = new StreamWriter( memoryStream ) ) { using ( var htmlTextWriter = new HtmlTextWriter( streamWriter ) ) { base.Render( htmlTextWriter ); htmlTextWriter.Flush( ); memoryStream.Position = 0; TextReader textReader = new StreamReader( memoryStream ); String output = textReader.ReadToEnd( ); String newOutput = RewriteOutput( output ); writer.Write( newOutput ); } } } }
static void Main(string[] args) { MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); HtmlTextWriter htw = new HtmlTextWriter(sw); htw.RenderBeginTag(HtmlTextWriterTag.H1); htw.RenderEndTag(); htw.Flush(); long ms_len = ms.Length; Console.WriteLine("ms.Length(" + ms_len + ")"); byte[] buff = ms.GetBuffer(); for (long i = 0; i < ms_len; i++) { Console.Write((char)(buff[i])); } }
public void WriteImg_Performance() { for (int i = 0; i < PERFORMANCE_TEST_RUNS; i++) { string imageRelativeUrl = "images/logo.jpg"; string altText = "Company logo"; StringBuilder htmlBuilder = new StringBuilder(); HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(htmlBuilder)); writer.AddAttribute(HtmlTextWriterAttribute.Src, imageRelativeUrl); writer.AddAttribute(HtmlTextWriterAttribute.Alt, altText); writer.RenderBeginTag(HtmlTextWriterTag.Img); writer.RenderEndTag(); writer.Flush(); string html = htmlBuilder.ToString(); } }
public static string RenderMenuItems(List <MenuItem> datasource) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.IO.StringWriter stWriter = new System.IO.StringWriter(sb); System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter); foreach (var item in datasource) { _RenderMenu(item, htmlWriter); if (item.ChildItems != null && item.ChildItems.Count > 0) { htmlWriter.Write("</ul>\r"); htmlWriter.Write("</li>\r"); } } htmlWriter.Flush(); htmlWriter.Close(); //System.Diagnostics.Debug.WriteLine(sb.ToString()); return(sb.ToString()); }
public string GetCallbackResult() { string[] str = new string[] { "11", "22", "33", "44" }; ListItem item = null; this.drpList1.Items.Clear(); foreach (string tmp in str) { item = new ListItem(tmp, tmp); this.drpList1.Items.Add(item); } StringWriter writer1 = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); HtmlTextWriter writer2 = new HtmlTextWriter(writer1); this.drpList1.RenderControl(writer2); writer2.Flush(); writer2.Close(); return writer1.ToString(); }
protected void btnImport_Click(object sender, EventArgs e) { System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); Response.Clear(); Response.Charset = "gb2312"; Response.ContentType = "application/vnd.ms-excel"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("其他出库单") + ".xls"); Response.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>"); Response.Write(hiddExcel.Value); Response.Write(tw.ToString()); Response.Write("</body></html>"); Response.End(); hw.Close(); hw.Flush(); tw.Close(); tw.Flush(); }
public override void RenderControl(HtmlTextWriter writer) { base.RenderControl(writer); //writer.WriteBeginTag("object"); if (Url.ToLower().EndsWith(".flv") || Url.ToLower().EndsWith(".swf")) RenderFlashControl(writer); else if (Url.ToLower().EndsWith(".mov") || Url.ToLower().EndsWith(".mp4")) RenderApple(writer); else if(Url.ToLower().EndsWith(".wmv")) { RenderWmv(writer); } else { writer.WriteLine("<h2>Bad Video File</h2>"); } writer.Flush(); //RenderMp4(writer); //writer.WriteLine("<object></object>"); //writer.WriteEndTag("object"); }
/// <summary> /// 导出EXCEL方法 /// </summary> /// <param name="page"></param> /// <param name="fileName"></param> /// <param name="html"></param> protected void ExportDsToXls(Page page, string fileName, string html) { System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); Response.Clear(); Response.Charset = "gb2312"; Response.ContentType = "application/vnd.ms-excel"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName) + ".xls"); Response.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>"); Response.Write(html); Response.Write(tw.ToString()); Response.Write("</body></html>"); Response.End(); hw.Close(); hw.Flush(); tw.Close(); tw.Flush(); }
public string RenderControlToHtml(System.Web.UI.Control controlToRender) { string retValue = null; controlToRender.Visible = true; System.Text.StringBuilder sb = new System.Text.StringBuilder(); using (System.IO.StringWriter stWriter = new System.IO.StringWriter(sb, System.Globalization.CultureInfo.InvariantCulture)) { using (System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter)) { controlToRender.DataBind(); controlToRender.RenderControl(htmlWriter); htmlWriter.Flush(); stWriter.Flush(); retValue = sb.ToString(); } // End Using htmlWriter } // End Using stWriter return(retValue); } // End Function RenderControlToHtml
protected override void Render(HtmlTextWriter writer) { var stringWriter = new System.IO.StringWriter(); var htmlWriter = new System.Web.UI.HtmlTextWriter(stringWriter); base.Render(htmlWriter); htmlWriter.Flush(); htmlWriter.Close(); string html = stringWriter.ToString().Replace("\t", " "); html = Regex.Replace(html, "(\r\n){2,}", "\r\n"); html = Regex.Replace(html, "(\r\n\\s+)+(?<Follow>\r\n\\s+</)", "${Follow}"); html = Regex.Replace(html, "\r\n(?<Indent>\\s+)(\r\n\\s+)+", "\r\n${Indent}"); var match = Regex.Match(html, "\r\n(?<Indent>\\s+)<span>Page Events:"); if (match.Success) { string indent = match.Groups["Indent"].Value; html = Regex.Replace(html, "<br />(?<counter><span>[0-9]{12})", "<br />\r\n" + indent + "${counter}"); } Response.Write(html); }
public override string ToString() { StringBuilder buffer = new StringBuilder(); HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(buffer)); writer.RenderBeginTag(HtmlTextWriterTag.Table); foreach (var row in rows) { writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "200px"); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(row.Key); writer.RenderEndTag(); // td writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(row.Value); writer.RenderEndTag(); // td writer.RenderEndTag(); // tr } writer.RenderEndTag(); // table writer.Flush(); return buffer.ToString(); }
protected void HandleGET( IHttpRequest httpReq, IHttpResponse httpResp, bool autoDocVersion) { using (MemoryStream stm = new MemoryStream()) { using (HtmlTextWriter wrtr = new HtmlTextWriter(new StreamWriter(stm))) { XmlRpcDocWriter.WriteDoc(wrtr, this.GetType(), autoDocVersion); wrtr.Flush(); httpResp.ContentType = "text/html"; httpResp.StatusCode = 200; if (!httpResp.SendChunked) { httpResp.ContentLength = stm.Length; } stm.Position = 0; Stream respStm = httpResp.OutputStream; Util.CopyStream(stm, respStm); respStm.Flush(); } } }
protected void btnImport_Click(object sender, EventArgs e) { System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); Response.Clear(); Response.Charset = "gb2312"; Response.ContentType = "application/vnd.ms-excel"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("委托代销结算单") + ".xls"); Response.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>"); Response.Write(hiddExcel.Value); Response.Write(tw.ToString()); Response.Write("</body></html>"); Response.End(); hw.Close(); hw.Flush(); tw.Close(); tw.Flush(); }
bool ProcessLoadComplete () { Trace.Write ("aspx.page", "Begin LoadComplete"); OnLoadComplete (EventArgs.Empty); Trace.Write ("aspx.page", "End LoadComplete"); if (IsCrossPagePostBack) return true; if (IsCallback) { string result = ProcessCallbackData (); HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output); callbackOutput.Write (result); callbackOutput.Flush (); return true; } Trace.Write ("aspx.page", "Begin PreRender"); PreRenderRecursiveInternal (); Trace.Write ("aspx.page", "End PreRender"); ExecuteRegisteredAsyncTasks (); Trace.Write ("aspx.page", "Begin PreRenderComplete"); OnPreRenderComplete (EventArgs.Empty); Trace.Write ("aspx.page", "End PreRenderComplete"); Trace.Write ("aspx.page", "Begin SaveViewState"); SavePageViewState (); Trace.Write ("aspx.page", "End SaveViewState"); Trace.Write ("aspx.page", "Begin SaveStateComplete"); OnSaveStateComplete (EventArgs.Empty); Trace.Write ("aspx.page", "End SaveStateComplete"); return false; }
bool ProcessLoadComplete () { Trace.Write ("aspx.page", "Begin LoadComplete"); OnLoadComplete (EventArgs.Empty); Trace.Write ("aspx.page", "End LoadComplete"); if (IsCrossPagePostBack) return true; if (IsCallback) { #if TARGET_J2EE if (getFacesContext () != null) { _callbackTarget = GetCallbackTarget (); ProcessRaiseCallbackEvent (_callbackTarget, ref _callbackEventError); return true; } #endif string result = ProcessCallbackData (); HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output); callbackOutput.Write (result); callbackOutput.Flush (); return true; } Trace.Write ("aspx.page", "Begin PreRender"); PreRenderRecursiveInternal (); Trace.Write ("aspx.page", "End PreRender"); ExecuteRegisteredAsyncTasks (); Trace.Write ("aspx.page", "Begin PreRenderComplete"); OnPreRenderComplete (EventArgs.Empty); Trace.Write ("aspx.page", "End PreRenderComplete"); Trace.Write ("aspx.page", "Begin SaveViewState"); SavePageViewState (); Trace.Write ("aspx.page", "End SaveViewState"); Trace.Write ("aspx.page", "Begin SaveStateComplete"); OnSaveStateComplete (EventArgs.Empty); Trace.Write ("aspx.page", "End SaveStateComplete"); return false; }
static string GetHtmlFromControl(Control ctrl) { StringWriter sr = new StringWriter (); HtmlTextWriter tr = new HtmlTextWriter (sr); ctrl.RenderControl (tr); tr.Flush (); return sr.GetStringBuilder ().ToString (); }
private void RenderError(HtmlTextWriter writer) { Debug.Assert(writer != null); Error error = _errorEntry.Error; // // Write out the page title containing error type and message. // writer.AddAttribute(HtmlTextWriterAttribute.Id, "PageTitle"); writer.RenderBeginTag(HtmlTextWriterTag.H1); HtmlEncode(error.Message, writer); writer.RenderEndTag(); // </h1> writer.WriteLine(); SpeedBar.Render(writer, SpeedBar.Home.Format(BasePageName), SpeedBar.Help, SpeedBar.About.Format(BasePageName)); writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTitle"); writer.RenderBeginTag(HtmlTextWriterTag.P); writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorType"); writer.RenderBeginTag(HtmlTextWriterTag.Span); HtmlEncode(error.Type, writer); writer.RenderEndTag(); // </span> writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorTypeMessageSeparator"); writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(": "); writer.RenderEndTag(); // </span> writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorMessage"); writer.RenderBeginTag(HtmlTextWriterTag.Span); HtmlEncode(error.Message, writer); writer.RenderEndTag(); // </span> writer.RenderEndTag(); // </p> writer.WriteLine(); // // Do we have details, like the stack trace? If so, then write // them out in a pre-formatted (pre) element. // NOTE: There is an assumption here that detail will always // contain a stack trace. If it doesn't then pre-formatting // might not be the right thing to do here. // if (error.Detail.Length != 0) { writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorDetail"); writer.RenderBeginTag(HtmlTextWriterTag.Pre); writer.Flush(); MarkupStackTrace(error.Detail, writer.InnerWriter); writer.RenderEndTag(); // </pre> writer.WriteLine(); } // // Write out the error log time. This will be in the local // time zone of the server. Would be a good idea to indicate // it here for the user. // writer.AddAttribute(HtmlTextWriterAttribute.Id, "ErrorLogTime"); writer.RenderBeginTag(HtmlTextWriterTag.P); HtmlEncode(string.Format("Logged on {0} at {1}", error.Time.ToLongDateString(), error.Time.ToLongTimeString()), writer); writer.RenderEndTag(); // </p> writer.WriteLine(); // // Render alternate links. // writer.RenderBeginTag(HtmlTextWriterTag.P); writer.Write("See also:"); writer.RenderEndTag(); // </p> writer.WriteLine(); writer.RenderBeginTag(HtmlTextWriterTag.Ul); // // Do we have an HTML formatted message from ASP.NET? If yes // then write out a link to it instead of embedding it // with the rest of the content since it is an entire HTML // document in itself. // if (error.WebHostHtmlMessage.Length != 0) { writer.RenderBeginTag(HtmlTextWriterTag.Li); string htmlUrl = this.BasePageName + "/html?id=" + HttpUtility.UrlEncode(_errorEntry.Id); writer.AddAttribute(HtmlTextWriterAttribute.Href, htmlUrl); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("Original ASP.NET error page"); writer.RenderEndTag(); // </a> writer.RenderEndTag(); // </li> } // // Add a link to the source XML and JSON data. // writer.RenderBeginTag(HtmlTextWriterTag.Li); writer.Write("Raw/Source data in "); writer.AddAttribute(HtmlTextWriterAttribute.Href, "xml" + Request.Url.Query); writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate); writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/xml"); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("XML"); writer.RenderEndTag(); // </a> writer.Write(" or in "); writer.AddAttribute(HtmlTextWriterAttribute.Href, "json" + Request.Url.Query); writer.AddAttribute(HtmlTextWriterAttribute.Rel, HtmlLinkType.Alternate); writer.AddAttribute(HtmlTextWriterAttribute.Type, "application/json"); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("JSON"); writer.RenderEndTag(); // </a> writer.RenderEndTag(); // </li> // // End of alternate links. // writer.RenderEndTag(); // </ul> // // If this error has context, then write it out. // ServerVariables are good enough for most purposes, so // we only write those out at this time. // RenderCollection(writer, error.ServerVariables, "ServerVariables", "Server Variables"); base.RenderContents(writer); }
/// <summary> /// The design time generated HTML for the control. /// </summary> /// <returns>A string containing the HTML rendering.</returns> public override string GetDesignTimeHtml() { // Extremely simple design time rendering! // will work on something better sooner or later. // This acts as a placeholder. Web.PlotSurface2D plot = (Web.PlotSurface2D)Component; int xs = Convert.ToInt32(plot.Width.Value); if ( xs < 1 ) return ""; int ys = Convert.ToInt32(plot.Height.Value); if ( ys < 1 ) return ""; StringWriter sw = new StringWriter(); HtmlTextWriter output= new HtmlTextWriter(sw); output.AddAttribute("border",plot.BorderWidth.ToString()); output.AddAttribute("borderColor",plot.BorderColor.ToKnownColor().ToString()); output.AddAttribute("cellSpacing","0"); output.AddAttribute("cellPadding","0"); output.AddAttribute("width",xs.ToString()); output.RenderBeginTag("table "); output.RenderBeginTag("tr"); output.AddAttribute("vAlign","center"); output.AddAttribute("align","middle"); output.AddAttribute("height",ys.ToString()); output.RenderBeginTag("td"); output.RenderBeginTag("P"); output.Write("PlotSurface2D:" + plot.Title); output.RenderEndTag(); output.RenderEndTag(); output.RenderEndTag(); output.RenderEndTag(); output.Flush(); return sw.ToString(); }
/// <summary> /// Exports the datagrid to an Excel file with the name of the datasheet provided by the passed in parameter /// </summary> public virtual void Export(string reportName, Page currentPage, Control gridView) { System.Web.UI.HtmlControls.HtmlForm htmlForm = new System.Web.UI.HtmlControls.HtmlForm(); currentPage.Controls.Add(htmlForm); htmlForm.Controls.Add(gridView); ClearChildControls((GridView)gridView); currentPage.Response.Clear(); currentPage.Response.Buffer = true; currentPage.Response.AddHeader("Content-Disposition", "attachment; filename=" + reportName); currentPage.Response.ContentType = "application/vnd.ms-excel"; currentPage.Response.ContentEncoding = System.Text.Encoding.UTF8; currentPage.Response.Charset = ""; currentPage.EnableViewState = false; using (StringWriter stringWriter = new StringWriter()) { HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); htmlForm.RenderControl(htmlWriter); htmlWriter.Flush(); currentPage.Response.Write(stringWriter.ToString()); currentPage.Response.End(); } }
private static void PersistObject(HtmlTextWriter writer, object control, IDesignerHost host, bool runAtServer) { //look up tag prefix from host IWebFormReferenceManager refMan = host.GetService (typeof (IWebFormReferenceManager)) as IWebFormReferenceManager; if (refMan == null) throw new Exception("Could not obtain IWebFormReferenceManager service"); string prefix = refMan.GetTagPrefix (control.GetType ()); //write tag to HtmlTextWriter writer.WriteBeginTag (prefix + ":" + control.GetType().Name); //go through all the properties and add attributes if necessary PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (control); foreach (PropertyDescriptor prop in properties) ProcessAttribute (prop, control, writer, string.Empty); if (runAtServer) writer.WriteAttribute ("runat", "server"); //do the same for events IComponent comp = control as IComponent; if (comp != null && comp.Site != null) { IEventBindingService evtBind = (IEventBindingService) comp.Site.GetService (typeof (IEventBindingService)); if (evtBind != null) foreach (EventDescriptor e in TypeDescriptor.GetEvents (comp)) ProcessEvent (e, comp, writer, evtBind); } //ControlDesigner designer = (ControlDesigner) host.GetDesigner(control); //TODO: we don't yet support designer.GetPersistInnerHtml() 'cause we don't have the designers... if (HasInnerProperties(control)) { writer.Write (HtmlTextWriter.TagRightChar); writer.Indent++; PersistInnerProperties (writer, control, host); writer.Indent--; writer.WriteEndTag (prefix + ":" + control.GetType ().Name); } else writer.Write (HtmlTextWriter.SelfClosingTagEnd); writer.WriteLine (); writer.Flush (); }
protected void GenerateProductTypePropertyFields() { ProductTypePropertiesLiteral.Text = ""; if (lstProductType.SelectedValue.Trim() != string.Empty) { string productTypeBvin = lstProductType.SelectedValue; List<ProductProperty> props = MTApp.CatalogServices.ProductPropertiesFindForType(productTypeBvin); StringBuilder sb = new StringBuilder(); int count = 0; foreach (ProductProperty item in props) { count += 1; StringWriter sw = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(sw); sb.Append("<tr><td class=\"formlabel\">"); sb.Append(item.DisplayName); sb.Append("</td><td class=\"formfield\">"); if (item.TypeCode == ProductPropertyType.CurrencyField) { HtmlInputText input = new HtmlInputText(); input.ID = "ProductTypeProperty" + count.ToString(); if (ProductTypeProperties.Count > (count - 1)) { if (ProductTypeProperties[count - 1] != null) { input.Value = ProductTypeProperties[count - 1]; } else { input.Value = item.DefaultValue; } } else { input.Value = item.DefaultValue; } input.RenderControl(writer); writer.Flush(); sb.Append(sw.ToString()); } else if (item.TypeCode == ProductPropertyType.DateField) { HtmlInputText input = new HtmlInputText(); input.ID = "ProductTypeProperty" + count.ToString(); if (ProductTypeProperties.Count > (count - 1)) { if (ProductTypeProperties[count - 1] != null) { input.Value = ProductTypeProperties[count - 1]; } else { input.Value = item.DefaultValue; } } else { input.Value = item.DefaultValue; } input.RenderControl(writer); writer.Flush(); sb.Append(sw.ToString()); } else if (item.TypeCode == ProductPropertyType.HyperLink) { HtmlInputText input = new HtmlInputText(); input.ID = "ProductTypeProperty" + count.ToString(); if (ProductTypeProperties.Count > (count - 1)) { if (ProductTypeProperties[count - 1] != null) { input.Value = ProductTypeProperties[count - 1]; } else { input.Value = item.DefaultValue; } } else { input.Value = item.DefaultValue; } input.RenderControl(writer); writer.Flush(); sb.Append(sw.ToString()); } else if (item.TypeCode == ProductPropertyType.MultipleChoiceField) { HtmlSelect input = new HtmlSelect(); input.ID = "ProductTypeProperty" + count.ToString(); bool setWidth = false; foreach (ProductPropertyChoice choice in item.Choices) { if (choice.ChoiceName.Length > 25) { setWidth = true; } System.Web.UI.WebControls.ListItem li = new System.Web.UI.WebControls.ListItem(choice.ChoiceName, choice.Id.ToString()); input.Items.Add(li); } if (setWidth) { input.Style.Add("width", "305px"); } if (ProductTypeProperties.Count > (count - 1)) { if (ProductTypeProperties[count - 1] != null) { input.Value = ProductTypeProperties[count - 1]; } else { input.Value = item.DefaultValue; } } else { input.Value = item.DefaultValue; } input.RenderControl(writer); writer.Flush(); sb.Append(sw.ToString()); } else if (item.TypeCode == ProductPropertyType.TextField) { HtmlTextArea input = new HtmlTextArea(); input.ID = "ProductTypeProperty" + count.ToString(); if (ProductTypeProperties.Count > (count - 1)) { if (ProductTypeProperties[count - 1] != null) { input.Value = ProductTypeProperties[count - 1]; } else { input.Value = item.DefaultValue; } } else { input.Value = item.DefaultValue; } input.Rows = 5; input.Cols = 40; input.RenderControl(writer); writer.Flush(); sb.Append(sw.ToString()); } sb.Append("</td></tr>"); ProductTypePropertiesLiteral.Text = sb.ToString(); } } }