Search Results

Search found 113 results on 5 pages for 'htmltextwriter'.

Page 2/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • MVC Automatic Menu

    - by Nuri Halperin
    An ex-colleague of mine used to call his SQL script generator "Super-Scriptmatic 2000". It impressed our then boss little, but was fun to say and use. We called every batch job and script "something 2000" from that day on. I'm tempted to call this one Menu-Matic 2000, except it's waaaay past 2000. Oh well. The problem: I'm developing a bunch of stuff in MVC. There's no PM to generate mounds of requirements and there's no Ux Architect to create wireframe. During development, things change. Specifically, actions get renamed, moved from controller x to y etc. Well, as the site grows, it becomes a major pain to keep a static menu up to date, because the links change. The HtmlHelper doesn't live up to it's name and provides little help. How do I keep this growing list of pesky little forgotten actions reigned in? The general plan is: Decorate every action you want as a menu item with a custom attribute Reflect out all menu items into a structure at load time Render the menu using as CSS  friendly <ul><li> HTML. The MvcMenuItemAttribute decorates an action, designating it to be included as a menu item: [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class MvcMenuItemAttribute : Attribute {   public string MenuText { get; set; }   public int Order { get; set; }   public string ParentLink { get; set; }   internal string Controller { get; set; }   internal string Action { get; set; }     #region ctor   public MvcMenuItemAttribute(string menuText) : this(menuText, 0) { } public MvcMenuItemAttribute(string menuText, int order) { MenuText = menuText; Order = order; }       internal string Link { get { return string.Format("/{0}/{1}", Controller, this.Action); } }   internal MvcMenuItemAttribute ParentItem { get; set; } #endregion } The MenuText allows overriding the text displayed on the menu. The Order allows the items to be ordered. The ParentLink allows you to make this item a child of another menu item. An example action could then be decorated thusly: [MvcMenuItem("Tracks", Order = 20, ParentLink = "/Session/Index")] . All pretty straightforward methinks. The challenge with menu hierarchy becomes fairly apparent when you try to render a menu and highlight the "current" item or render a breadcrumb control. Both encounter an  ambiguity if you allow a data source to have more than one menu item with the same URL link. The issue is that there is no great way to tell which link a person click. Using referring URL will fail if a user bookmarked the page. Using some extra query string to disambiguate duplicate URLs essentially changes the links, and also ads a chance of collision with other query parameters. Besides, that smells. The stock ASP.Net sitemap provider simply disallows duplicate URLS. I decided not to, and simply pick the first one encountered as the "current". Although it doesn't solve the issue completely – one might say they wanted the second of the 2 links to be "current"- it allows one to include a link twice (home->deals and products->deals etc), and the logic of deciding "current" is easy enough to explain to the customer. Now that we got that out of the way, let's build the menu data structure: public static List<MvcMenuItemAttribute> ListMenuItems(Assembly assembly) { var result = new List<MvcMenuItemAttribute>(); foreach (var type in assembly.GetTypes()) { if (!type.IsSubclassOf(typeof(Controller))) { continue; } foreach (var method in type.GetMethods()) { var items = method.GetCustomAttributes(typeof(MvcMenuItemAttribute), false) as MvcMenuItemAttribute[]; if (items == null) { continue; } foreach (var item in items) { if (String.IsNullOrEmpty(item.Controller)) { item.Controller = type.Name.Substring(0, type.Name.Length - "Controller".Length); } if (String.IsNullOrEmpty(item.Action)) { item.Action = method.Name; } result.Add(item); } } } return result.OrderBy(i => i.Order).ToList(); } Using reflection, the ListMenuItems method takes an assembly (you will hand it your MVC web assembly) and generates a list of menu items. It digs up all the types, and for each one that is an MVC Controller, digs up the methods. Methods decorated with the MvcMenuItemAttribute get plucked and added to the output list. Again, pretty simple. To make the structure hierarchical, a LINQ expression matches up all the items to their parent: public static void RegisterMenuItems(List<MvcMenuItemAttribute> items) { _MenuItems = items; _MenuItems.ForEach(i => i.ParentItem = items.FirstOrDefault(p => String.Equals(p.Link, i.ParentLink, StringComparison.InvariantCultureIgnoreCase))); } The _MenuItems is simply an internal list to keep things around for later rendering. Finally, to package the menu building for easy consumption: public static void RegisterMenuItems(Type mvcApplicationType) { RegisterMenuItems(ListMenuItems(Assembly.GetAssembly(mvcApplicationType))); } To bring this puppy home, a call in Global.asax.cs Application_Start() registers the menu. Notice the ugliness of reflection is tucked away from the innocent developer. All they have to do is call the RegisterMenuItems() and pass in the type of the application. When you use the new project template, global.asax declares a class public class MvcApplication : HttpApplication and that is why the Register call passes in that type. protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes);   MvcMenu.RegisterMenuItems(typeof(MvcApplication)); }   What else is left to do? Oh, right, render! public static void ShowMenu(this TextWriter output) { var writer = new HtmlTextWriter(output);   renderHierarchy(writer, _MenuItems, null); }   public static void ShowBreadCrumb(this TextWriter output, Uri currentUri) { var writer = new HtmlTextWriter(output); string currentLink = "/" + currentUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);   var menuItem = _MenuItems.FirstOrDefault(m => m.Link.Equals(currentLink, StringComparison.CurrentCultureIgnoreCase)); if (menuItem != null) { renderBreadCrumb(writer, _MenuItems, menuItem); } }   private static void renderBreadCrumb(HtmlTextWriter writer, List<MvcMenuItemAttribute> menuItems, MvcMenuItemAttribute current) { if (current == null) { return; } var parent = current.ParentItem; renderBreadCrumb(writer, menuItems, parent); writer.Write(current.MenuText); writer.Write(" / ");   }     static void renderHierarchy(HtmlTextWriter writer, List<MvcMenuItemAttribute> hierarchy, MvcMenuItemAttribute root) { if (!hierarchy.Any(i => i.ParentItem == root)) return;   writer.RenderBeginTag(HtmlTextWriterTag.Ul); foreach (var current in hierarchy.Where(element => element.ParentItem == root).OrderBy(i => i.Order)) { if (ItemFilter == null || ItemFilter(current)) {   writer.RenderBeginTag(HtmlTextWriterTag.Li); writer.AddAttribute(HtmlTextWriterAttribute.Href, current.Link); writer.AddAttribute(HtmlTextWriterAttribute.Alt, current.MenuText); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.WriteEncodedText(current.MenuText); writer.RenderEndTag(); // link renderHierarchy(writer, hierarchy, current); writer.RenderEndTag(); // li } } writer.RenderEndTag(); // ul } The ShowMenu method renders the menu out to the provided TextWriter. In previous posts I've discussed my partiality to using well debugged, time test HtmlTextWriter to render HTML rather than writing out angled brackets by hand. In addition, writing out using the actual writer on the actual stream rather than generating string and byte intermediaries (yes, StringBuilder being no exception) disturbs me. To carry out the rendering of an hierarchical menu, the recursive renderHierarchy() is used. You may notice that an ItemFilter is called before rendering each item. I figured that at some point one might want to exclude certain items from the menu based on security role or context or something. That delegate is the hook for such future feature. To carry out rendering of a breadcrumb recursion is used again, this time simply to unwind the parent hierarchy from the leaf node, then rendering on the return from the recursion rather than as we go along deeper. I guess I was stuck in LISP that day.. recursion is fun though.   Now all that is left is some usage! Open your Site.Master or wherever you'd like to place a menu or breadcrumb, and plant one of these calls: <% MvcMenu.ShowBreadCrumb(this.Writer, Request.Url); %> to show a breadcrumb trail (notice lack of "=" after <% and the semicolon). <% MvcMenu.ShowMenu(Writer); %> to show the menu.   As mentioned before, the HTML output is nested <UL> <LI> tags, which should make it easy to style using abundant CSS to produce anything from static horizontal or vertical to dynamic drop-downs.   This has been quite a fun little implementation and I was pleased that the code size remained low. The main crux was figuring out how to pass parent information from the attribute to the hierarchy builder because attributes have restricted parameter types. Once I settled on that implementation, the rest falls into place quite easily.

    Read the article

  • Server Controls in ASP.NET MVC without ViewState

    - by imran_ku07
      Introduction :           ASP.NET Web Forms provides a development environment just like GUI or windows application and try to hide statelessness nature of HTTP protocol. For accomplishing this target, Web Forms uses ViewState (a hidden field) to remove the gap between HTTP statelessness and GUI applications. But the problem with this technique is that ViewState size which grows quickly and also go back and forth with every request, as a result it will degrade application performance. In this article i will try to use existing ASP.NET server controls without ViewState.   Description :           When you add a server control which needs viewstate, in the presentation view in ASP.NET MVC application without a form tag, for example,            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>            It will shows the following exception,            Control 'TextBox1' of type 'TextBox' must be placed inside a form tag with runat=server             When you place this textbox inside a form tag with runat=server, this will add the following ViewState even when you disable ViewState by using EnableViewState="false"            <input type="hidden" value="/wEPDwUJMjgzMDgzOTgzZGQ6u9CwikhHEW39ObrHyLTPFSboPA==" id="__VIEWSTATE" name="__VIEWSTATE"/>             The solution to this problem is to use the RenderControl method of server control which is simply renders HTML without any ViewState hidden field.         <% TextBox txt = new TextBox();          txt.Text = "abc";          StringBuilder sb = new StringBuilder();          System.IO.StringWriter textwriter = new System.IO.StringWriter(sb);          HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);          txt.RenderControl(htmlwriter);  %>        <%= sb.ToString() %>             This will render <input type="text" > without any View State. This technique become very useful when you are using rich server controls like GridView. For example, let's say you have List of Recalls in Model.Recalls, then you will show your tabular data as,     <%  GridView gv = new GridView();          gv.AutoGenerateColumns = true;          gv.DataSource = Model.Recalls;          gv.DataBind();         StringBuilder sb = new StringBuilder();         System.IO.StringWriter textwriter = new System.IO.StringWriter(sb);         HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);         gv.RenderControl(htmlwriter);%>            <%= sb.ToString() %>             This code might looks odd in your presentation view. A more better approach is to create a HTML Helper method which contains the above code. Summary :        In some cases you might needs to use existing ASP.NET Web Forms server controls but also dislikes ViewState. In this article i try to solve this gap by using the RenderControl method of Control class. Hopefully you enjoyed and become ready to create HTML helpers for many of the existing server controls.

    Read the article

  • Output asp.net masterpage webform to html email

    - by Steve McCall
    Hi I'm having a bit of a nightmare here! I'mv trying output a webform to html using page.rendercontrol and htmltextwriter but it is resulting in a blank email. Code: StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); HtmlTextWriter htmlTW = new HtmlTextWriter(sw); page.RenderControl(htmlTW); String content = sb.ToString(); MailMessage mail = new MailMessage(); mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]"); mail.IsBodyHtml = true; mail.Subject = "Test"; mail.Body = content; SmtpClient smtp = new SmtpClient("1111"); smtp.Send(mail); Response.Write("Message Sent"); I also tried it by rendering a single textbox and got and error saying It needed to be within form tags (which are on the masterpage). I tried this fix: http://forums.asp.net/p/1016960/1368933.aspx#1368933 and added: public override void VerifyRenderingInServerForm(Control control) { return; } But now the errror I get is: VerifyRenderingInServerForm(Control)': no suitable method found to override Does anyone have a fix for this? I'm tearing my hair out!! Thanks, Steve

    Read the article

  • Invoking code both before and after WebControl.Render method

    - by Dirk
    I have a set of custom ASP.NET server controls, most of which derive from CompositeControl. I want to implement a uniform look for "required" fields across all control types by wrapping each control in a specific piece of HTML/CSS markup. For example: <div class="requiredInputContainer"> ...custom control markup... </div> I'd love to abstract this behavior in such a way as to avoid having to do something ugly like this in every custom control, present and future: public class MyServerControl : TextBox, IRequirableField { public IRequirableField.IsRequired {get;set;} protected override void Render(HtmlTextWriter writer){ RequiredFieldHelper.RenderBeginTag(this, writer) //render custom control markup RequiredFieldHelper.RenderEndTag(this, writer) } } public static class RequiredFieldHelper{ public static void RenderBeginTag(IRequirableField field, HtmlTextWriter writer){ //check field.IsRequired, render based on its values } public static void RenderEndTag(IRequirableField field, HtmlTextWriter writer){ //check field.IsRequired , render based on its values } } If I was deriving all of my custom controls from the same base class, I could conceivably use Template Method to enforce the before/after behavior;but I have several base classes and I'd rather not end up with really a convoluted class hierarchy anyway. It feels like I should be able to design something more elegant (i.e. adheres to DRY and OCP) by leveraging the functional aspects of C#, but I'm drawing a blank.

    Read the article

  • How I can export a datatable to MS word 2007, excel 2007,csv from asp.net?

    - by bala3569
    Hi, I am using the below code to Export DataTable to MS Word,Excel,CSV format & it's working fine. But problem is that this code export to MS Word 2003,Excel 2003 version. I need to Export my DataTable to Word 2007,Excel 2007,CSV because I am supposed to handle more than 100,000 records at a time and as we know Excel 2003 supports for only 65,000 records. Please help me out if you know that how to export DataTable or DataSet to MS Word 2007,Excel 2007. public static void Convertword(DataTable dt, HttpResponse Response,string filename) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".doc"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.word"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView(); dg.DataSource = dt; dg.DataBind(); dg.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); //HttpContext.Current.ApplicationInstance.CompleteRequest(); } public static void Convertexcel(DataTable dt, HttpResponse Response, string filename) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite); System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid(); dg.DataSource = dt; dg.DataBind(); dg.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); //HttpContext.Current.ApplicationInstance.CompleteRequest(); } public static void ConvertCSV(DataTable dataTable, HttpResponse Response, string filename) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".csv"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "Application/x-msexcel"; StringBuilder sb = new StringBuilder(); if (dataTable.Columns.Count != 0) { foreach (DataColumn column in dataTable.Columns) { sb.Append(column.ColumnName + ','); } sb.Append("\r\n"); foreach (DataRow row in dataTable.Rows) { foreach (DataColumn column in dataTable.Columns) { if(row[column].ToString().Contains(',')==true) { row[column] = row[column].ToString().Replace(",", ""); } sb.Append(row[column].ToString() + ','); } sb.Append("\r\n"); } } Response.Write(sb.ToString()); Response.End(); //HttpContext.Current.ApplicationInstance.CompleteRequest(); }

    Read the article

  • Problem showing modelstate errors while using RenderPartialToString

    - by Martin
    Im using the following code: public string RenderPartialToString(ControllerContext context, string partialViewName, ViewDataDictionary viewData, TempDataDictionary tempData) { ViewEngineResult result = ViewEngines.Engines.FindPartialView(context, partialViewName); if (result.View != null) { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (HtmlTextWriter output = new HtmlTextWriter(sw)) { ViewContext viewContext = new ViewContext(context, result.View, viewData, tempData, output); result.View.Render(viewContext, output); } } return sb.ToString(); } return String.Empty; } To return a partial view and a form through JSON. It works as it should, but as soon as I get modelstate errors my ValidationSummary does not show. The JSON only return the default form but it does not highlight the validation errors or show the validation summary. Am I missing something? This is how I call the RenderPartialToString: string partialView = RenderPartialToString(this.ControllerContext, "~/Areas/User/Views/Account/ChangeAccountDetails.ascx", new ViewDataDictionary(avd), new TempDataDictionary());

    Read the article

  • Is there a better approach to minify html generated from aspx page

    - by Hoque
    I am using the following code to minify html generated from aspx page duuring runtime. protected override void Render(HtmlTextWriter writer) { TextWriter output = new StringWriter(); base.Render(new HtmlTextWriter(output)); String html = output.ToString(); html = Regex.Replace(html, @"\n|\t", " "); html = Regex.Replace(html, @">\s+<", "><").Trim(); html = Regex.Replace(html, @"\s{2,}", " "); writer.Write(html); } Is there more better approach to do the same. Thank you so much.

    Read the article

  • What are the alternative ways to export excel file

    - by fealin
    i m trying to generate an excel file from my web page but i have some issues with Turkish chars such as "I" "g" when i open the file some chars are incorrect (I seems Ä°) here is my code gvExpRequests.DataSource = dsExpRequests; gvExpRequests.DataBind(); gvExpRequests.GridLines = GridLines.Both; Page.EnableViewState = false; Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=export.xls"); Response.ContentType = "application/ms-excel"; Response.ContentEncoding = Encoding.UTF8; Response.BinaryWrite(Encoding.UTF8.GetPreamble()); StringWriter yaz = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(yaz); gvExpRequests.RenderControl(htw); i don't know what's wrong with here i tried a lot of encoding but i got same results every time i want to try something different to do this are there any another way to export a excel file from a gridview

    Read the article

  • Grid View To Excel

    - by rahulchandran
    Hi I am trying to convert the contents of a grid View to an excel file and I am doing it using this code string attachment = "attachment; filename= " + FileName; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gv.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); The problem is I am getting some sort of html in an excel style format , theres java script in the page links etc what I want is to turn the results of my query into a comma seperated file Is that do-able for free or do I have to run the query myself get the data and write out a csv stream Thanks

    Read the article

  • Exporting data from a gridview to different excel worksheets

    - by Alex
    I am binding data from a dataset to a grid and exporting data from the grid to an excel.if the the number of items in the grid is greater than 50000,an error message is displayed. So i want to split the data and display it in different worksheets in excel.(Am working in a web application) using this code for exporting to excel gvExcel.DataSource = DTS; gvExcel.DataBind(); Response.AddHeader("content-disposition", "attachment; filename= filename.xls"); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gvExcel.RenderControl(htw); // Style is added dynamically Response.Write(style); Response.Write(sw.ToString()); Response.End(); Can anyone help me on this??

    Read the article

  • Reading an embedded file from an ASP.NET Custom Server Control an rendering it

    - by Andreas Grech
    I currently have a file "abc.htm" in my Custom Server Control Project and it's Build Action is set to Embedded Resource. Now in the RenderContents(HtmlTextWriter output) method, I need to read that file and render it on the website. I am trying the following but it's to no avail: protected override void RenderContents(HtmlTextWriter output) { var providersURL = Page.ClientScript.GetWebResourceUrl(typeof (OpenIDSel), "OpenIDSelector.Providers.htm"); var fi = new FileInfo(providersURL); // <- exception here //the remaining code is to possibly render the file } This is an example of how the providersURL is: /WebResource.axd?d=kyU2OiYu6lwshLH4pRUCUmG-pzI4xDC1ii9u032IPWwUzMsFzFHzL3veInwslz8Y0&t=634056587753507131 FileInfo is throwing System.ArgumentException: Illegal characters in path.

    Read the article

  • C#: Changing the order of columns when binding DataTable to a GridView

    - by Nir
    How is it possible to change the displayed order of columns from a DataTable? For example, dataTable "dt" contains two columns "a" and "b". I bind it to a GridView like this: gridView.DataSource = dt; gridView.DataBind(); But I'd like the GridView to display "b" first (leftmost). Important point: I'm using this to export to Excel and there's no actual output to screen, using: HtmlTextWriter htw = new HtmlTextWriter(sw); gridView.RenderControl(htw); Thanks!

    Read the article

  • Excel 2008 Cant Parse HTML

    - by VictorV
    I need to export a gridview to excel, I put the return html code from the gridview to a HtmlTextWriter and put this into the response. The result file work fine in excel, excel can parse the html and the result is readable, work perfect on excel 2003 and 2007, but in some machines with Excel 2008 (MACOS) excel shows only the raw html code and can't process this html code. Any idea to configure excel? This is the code to convert: public static void ToExcel(GridView gridView, string fileName) { HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Buffer = true; fileName = fileName.Replace(".xls", string.Empty) + ".xls"; response.AddHeader("content-disposition", "attachment;filename=" + fileName); response.Charset = ""; response.ContentEncoding = Encoding.Unicode; response.BinaryWrite(Encoding.Unicode.GetPreamble()); response.ContentType = MimeTypes.GetContentType(fileName); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); gridView.AllowPaging = false; //gridView.DataBind(); //Change the Header Row back to white color gridView.HeaderRow.Style.Add("background-color", "#FFFFFF"); //Apply style to Individual Cells for (int i = 0; i < gridView.HeaderRow.Cells.Count; i++) { gridView.HeaderRow.Cells[i].Style.Add("background-color", "yellow"); } for (int i = 0; i < gridView.Rows.Count; i++) { GridViewRow row = gridView.Rows[i]; //Change Color back to white row.BackColor = System.Drawing.Color.White; //Apply text style to each Row row.Attributes.Add("class", "textmode"); //Apply style to Individual Cells of Alternating Row if (i % 2 != 0) { for (int j = 0; j < row.Cells.Count; j++) { row.Cells[j].Style.Add("background-color", "#C2D69B"); } } } gridView.RenderControl(hw); //style to format numbers to string string style = @"<style> .textmode { mso-number-format:\@; } </style>"; response.Write(style); response.Output.Write(sw.ToString()); response.Flush(); response.End(); }

    Read the article

  • export data from WCF Service to excel

    - by Dave
    I need to provide an export to excel feature for a large amount of data returned from a WCF web service. The code to load the datalist is as below: List<resultSet> r = myObject.ReturnResultSet(myWebRequestUrl); //call to WCF service myDataList.DataSource = r; myDataList.DataBind(); I am using the Reponse object to do the job: Response.Clear(); Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment; filename=MyExcel.xls"); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); HtmlTextWriter tw = new HtmlTextWriter(sw); myDataList.RenderControl(tw); Response.Write(sb.ToString()); Response.End(); The problem is that WCF Service times out for large amount of data (about 5000 rows) and the result set is null. When I debug the service, I can see the window for saving/opening the excel sheet appear before the service returns the result and hence the excel sheet is always empty. Please help me figure this out.

    Read the article

  • Microsoft ReportViewer Web Control Requiring a ScriptManager

    - by Maya
    I'm trying to render the report viewer programmatically within a custom Page placed in an IHttpHandler context ReportViewer rv = new ReportViewer(); ReportDataSource rds = new ReportDataSource(); rds.Name = "Report"; rv.LocalReport.ReportPath = "Report.rdlc"; rds.Value = SomeReportObject; rv.LocalReport.DataSources.Add(rds); rv.LocalReport.Refresh(); ScriptManager scriptHandler = new ScriptManager(); MyPage p = new MyPage(); p.Controls.Add(scriptHandler); p.Controls.Add(rv); using (TextWriter myTextWriter = new StringWriter()) { using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter)) { p.RenderControl(myWriter); } } Although I have the ScriptManager added to the page but the runtime complains that the ReportViewer needs one, it throws the following exception at p.RenderControl(myWriter) line The Report Viewer Web Control requires a System.Web.UI.ScriptManager on the web form. And this is the MyPage Class public class MyPage : Page { public override void VerifyRenderingInServerForm(Control control) { //Empty Method } public override bool EnableEventValidation { get { return false; } set { /* Do nothing */} } } Any help would be very appreciated. This is done on .NET 4 and I'm using ReportViewer 2010. Many thanks, Maya.

    Read the article

  • iTextSharp error - cannot convert type 'Collections.Generic.List' to 'iTextSharp.text.Element'

    - by mike
    I am trying to export pdf file using aspx and c#. I got the following error. Cannot implicitly convert type 'System.Collections.Generic.List'' to 'iTextSharp.text.Element' I have the following code using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.text.html.simpleparser; StringBuilder strB = new StringBuilder(); document.Open(); if (text.Length.Equals(0))//export the text { GridView1.DataBind(); using (StringWriter sWriter = new StringWriter(strB)) { using (HtmlTextWriter htWriter = new HtmlTextWriter(sWriter)) { GridView1.RenderControl(htWriter); } } } else //export the grid { strB.Append(text); } using (TextReader sReader = new StringReader(strB.ToString())) { StyleSheet styles = new StyleSheet(); List<Element> list = new List<Element>(); list = HTMLWorker.ParseToList(sReader, styles); foreach (IElement elm in list) { document.Add(elm); } } I got the error in this line: list = HTMLWorker.ParseToList(sReader, styles); It's the first time that I am trying to export pdf files. I tried to cast the list element , however this did not solve my error. Any advice would be helpful!!!

    Read the article

  • c# asp.net How to return a usercontrol from a handeler ashx?

    - by Justin808
    I want to return the HTML output of the control from a handler. My code looks like this: <%@ WebHandler Language="C#" Class="PopupCalendar" % using System; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public class PopupCalendar : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; System.Web.UI.Page page = new System.Web.UI.Page(); UserControl ctrl = (UserControl)page.LoadControl("~/Controls/CalendarMonthView.ascx"); page.Form.Controls.Add(ctrl); StringWriter stringWriter = new StringWriter(); HtmlTextWriter tw = new HtmlTextWriter(stringWriter); ctrl.RenderControl(tw); context.Response.Write(stringWriter.ToString()); } public bool IsReusable { get { return false; } } } I'm getting the error: Server Error in '/CMS' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 14: System.Web.UI.Page page = new System.Web.UI.Page(); Line 15: UserControl ctrl = (UserControl)page.LoadControl("~/Controls/CalendarMonthView.ascx"); Line 16: page.Form.Controls.Add(ctrl); Line 17: Line 18: StringWriter stringWriter = new StringWriter(); How can I return the output of a Usercontrol via a handler?

    Read the article

  • Export the datagrid data to text in asp.net

    - by SRIRAM
    Problem:It will asks there is no assembly reference/namespace for Database Database db = DatabaseFactory.CreateDatabase(); DBCommandWrapper selectCommandWrapper = db.GetStoredProcCommandWrapper("sp_GetLatestArticles"); DataSet ds = db.ExecuteDataSet(selectCommandWrapper); StringBuilder str = new StringBuilder(); for(int i=0;i<=ds.Tables[0].Rows.Count - 1; i++) { for(int j=0;j<=ds.Tables[0].Columns.Count - 1; j++) { str.Append(ds.Tables[0].Rows[i][j].ToString()); } str.Append("<BR>"); } Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=FileName.txt"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.text"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); Response.Write(str.ToString()); Response.End();

    Read the article

  • Rendering a control generates security exception in .Net 4

    - by Jason Short
    I am having a problem with code that worked fine in .Net 2 giving this error under .Net 4. Build (web): Inheritance security rules violated while overriding member: 'Controls.RelatedPosts.RenderControl(System.Web.UI.HtmlTextWriter)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden. This is in DotNetBlogEngine. There were several other security demands in the code that .Net 4 didn't seem to like. I followed some of the advice I found on blogs (and here) and got rid of all the other errors. But this one still eludes me. The Main blogengine core dll is not set for security demands anylonger and is compiled for .Net 4 as well. This error is in the website side attempting to use the dll. There are controls that call a RenderControl method taking an HtmlTextWriter. Apparently the text writer now has some soft of security attributes set on it. Each of the controls implements a custom interface ( public interface ICustomFilter ), there are no security permissions present or demands. The site is running full trust on my local dev machine.

    Read the article

  • Render User Controls and call their Page_Load

    - by David Murdoch
    The following code will not work because the controls (page1, page2, page3) require that their "Page_Load" event gets called. using System; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using iTextSharp.text; using iTextSharp.text.html.simpleparser; using iTextSharp.text.pdf; public partial class utilities_getPDF : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // add user controls to the page AddContentControl("controls/page1"); AddContentControl("controls/page2"); AddContentControl("controls/page3"); // set up the response to download the rendered PDF... Response.ContentType = "application/pdf"; Response.ContentEncoding = System.Text.Encoding.UTF8; Response.AddHeader("Content-Disposition", "attachment;filename=FileName.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); // get the rendered HTML of the page System.IO.StringWriter stringWrite = new StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); this.Render(htmlWrite); StringReader reader = new StringReader(stringWrite.ToString()); // write the PDF to the OutputStream... Document doc = new Document(PageSize.A4); HTMLWorker parser = new HTMLWorker(doc); PdfWriter.GetInstance(doc, Response.OutputStream); doc.Open(); parser.Parse(reader); doc.Close(); } // the parts are probably irrelevant to the question... private const string contentPage = "~/includes/{0}.ascx"; private void AddContentControl(string page) { content.Controls.Add(myLoadControl(page)); } private Control myLoadControl(string page) { return TemplateControl.LoadControl(string.Format(contentPage, page)); } } So my question is: How can I get the controls HTML?

    Read the article

  • How can I embed images in an ASP.NET Generated Word File

    - by Nikos Steiakakis
    Hi everyone! I have a quite common problem, as I saw in the various user groups but could not find a suitable answer. What I want to do is generate an ASP.NET page in my website which will have the option of being exported into Microsoft Word .doc format. The method I have used is this: Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=Test.doc"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/msword"; StringWriter sw = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(sw); Page.RenderControl(htmlWrite); Response.Write(sw.ToString()); Response.End(); However this eventhough it generates a word doc, the images are note embedded in the document, rather they are placed as links. I have looked for a way to do this, but have not found something that actually worked. I would appreciate any help I can get, since this as "last minute" requirement (talk about typical) Thanks

    Read the article

  • Find Control inside Grid Row

    - by arpan911
    i m using parent child grid and on child grid i m doing Show / hide threw java script. and child grid i bind run time with Templatecolumns like GridView NewDg = new GridView(); NewDg.ID = "dgdStoreWiseMenuStock"; TemplateField TOTAL = new TemplateField(); TOTAL.HeaderTemplate = new BusinessLogic.GridViewTemplateTextBox(ListItemType.Header, "TOTAL",e.Row.RowIndex ); TOTAL.HeaderStyle.Width = Unit.Percentage(5.00); TOTAL.ItemTemplate = new BusinessLogic.GridViewTemplateTextBox(ListItemType.Item, "TOTAL", e.Row.RowIndex); NewDg.Columns.Add(TOTAL); NewDg.DataSource = ds; NewDg.DataBind(); NewDg.Columns[1].Visible = false; NewDg.Columns[2].Visible = false; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); NewDg.RenderControl(htw); Now I have one TextBox inside Grid named "TOTAL" I want to Find This TextBox and wanna get its value. How can Get it ?

    Read the article

  • How do I change the base class at runtime in C#?

    - by MatthewMartin
    I may be working on mission impossible here, but I seem to be getting close. I want to extend a ASP.NET control, and I want my code to be unit testable. Also, I'd like to be able to fake behaviors of a real Label (namely things like ID generation, etc), which a real Label can't do in an nUnit host. Here a working example that makes assertions on something that depends on a real base class and something that doesn't-- in a more realistic unit test, the test would depend on both --i.e. an ID existing and some custom behavior. Anyhow the code says it better than I can: public class LabelWrapper : Label //Runtime //public class LabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } //Ugh, now I have to test FakeLabelWrapper public class FakeLabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } [TestFixture] public class UnitTest { [Test] public void Test() { //Wish this was LabelWrapper label = new LabelWrapper(new FakeBase()) LabelWrapper label = new LabelWrapper(); //FakeLabelWrapper label = new FakeLabelWrapper(); label.Text = "ToUpper"; Assert.AreEqual("TOUPPER",label.Text); StringWriter stringWriter = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(stringWriter); label.RenderControl(writer); Assert.AreEqual(1,label.ID); Assert.AreEqual("<span>TOUPPER</span>", stringWriter.ToString()); } } public class FakeLabel { virtual public string Text { get; set; } public void RenderControl(TextWriter writer) { writer.Write("<span>" + Text + "</span>"); } } //System Under Test internal class LabelLogic { internal string ProcessGetText(string value) { return value.ToUpper(); } internal string ProcessSetText(string value) { return value.ToUpper(); } }

    Read the article

  • Will this class cause memory leaks, and does it need a dispose method? (asp.net vb)

    - by Phil
    Here is the class to export a gridview to an excel sheet: Imports System Imports System.Data Imports System.Configuration Imports System.IO Imports System.Web Imports System.Web.Security Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.WebControls.WebParts Imports System.Web.UI.HtmlControls Namespace ExcelExport Public NotInheritable Class GVExportUtil Private Sub New() End Sub Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView) HttpContext.Current.Response.Clear() HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName)) HttpContext.Current.Response.ContentType = "application/ms-excel" Dim sw As StringWriter = New StringWriter Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) Dim table As Table = New Table table.GridLines = GridLines.Vertical If (Not (gv.HeaderRow) Is Nothing) Then GVExportUtil.PrepareControlForExport(gv.HeaderRow) table.Rows.Add(gv.HeaderRow) End If For Each row As GridViewRow In gv.Rows GVExportUtil.PrepareControlForExport(row) table.Rows.Add(row) Next If (Not (gv.FooterRow) Is Nothing) Then GVExportUtil.PrepareControlForExport(gv.FooterRow) table.Rows.Add(gv.FooterRow) End If table.RenderControl(htw) HttpContext.Current.Response.Write(sw.ToString) HttpContext.Current.Response.End() End Sub Private Shared Sub PrepareControlForExport(ByVal control As Control) Dim i As Integer = 0 Do While (i < control.Controls.Count) Dim current As Control = control.Controls(i) If (TypeOf current Is LinkButton) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text)) ElseIf (TypeOf current Is ImageButton) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText)) ElseIf (TypeOf current Is HyperLink) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text)) ElseIf (TypeOf current Is DropDownList) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text)) ElseIf (TypeOf current Is CheckBox) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked)) End If If current.HasControls Then GVExportUtil.PrepareControlForExport(current) End If i = (i + 1) Loop End Sub End Class End Namespace Will this class cause memory leaks? And does anything here need to be disposed of? The code is working but I am getting frequent crashes of the app pool when it is in use. Thanks.

    Read the article

  • Will this class cause memory leaks, and does anything need disposing of? (asp.net vb)

    - by Phil
    Here is the class to export a gridview to an excel sheet: Imports System Imports System.Data Imports System.Configuration Imports System.IO Imports System.Web Imports System.Web.Security Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.WebControls.WebParts Imports System.Web.UI.HtmlControls Namespace ExcelExport Public NotInheritable Class GVExportUtil Private Sub New() End Sub Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView) HttpContext.Current.Response.Clear() HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName)) HttpContext.Current.Response.ContentType = "application/ms-excel" Dim sw As StringWriter = New StringWriter Dim htw As HtmlTextWriter = New HtmlTextWriter(sw) Dim table As Table = New Table table.GridLines = GridLines.Vertical If (Not (gv.HeaderRow) Is Nothing) Then GVExportUtil.PrepareControlForExport(gv.HeaderRow) table.Rows.Add(gv.HeaderRow) End If For Each row As GridViewRow In gv.Rows GVExportUtil.PrepareControlForExport(row) table.Rows.Add(row) Next If (Not (gv.FooterRow) Is Nothing) Then GVExportUtil.PrepareControlForExport(gv.FooterRow) table.Rows.Add(gv.FooterRow) End If table.RenderControl(htw) HttpContext.Current.Response.Write(sw.ToString) HttpContext.Current.Response.End() End Sub Private Shared Sub PrepareControlForExport(ByVal control As Control) Dim i As Integer = 0 Do While (i < control.Controls.Count) Dim current As Control = control.Controls(i) If (TypeOf current Is LinkButton) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text)) ElseIf (TypeOf current Is ImageButton) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText)) ElseIf (TypeOf current Is HyperLink) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text)) ElseIf (TypeOf current Is DropDownList) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text)) ElseIf (TypeOf current Is CheckBox) Then control.Controls.Remove(current) control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked)) End If If current.HasControls Then GVExportUtil.PrepareControlForExport(current) End If i = (i + 1) Loop End Sub End Class End Namespace Will this class cause memory leaks? And does anything here need to be disposed of? The code is working but I am getting the app pool falling over frequently when it is in use. Thanks.

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >