ASP.NET: dynamicly generating HTML, how to? - c#

I've been doing ASP.NET a little bit (on and off) over the last year, but I've never come upon this challenge: I'm building a website right now which is quite simple, mostly based in HTML and Javascript. However, on one page, I need to read an XML file off the server, parse it, create HTML from values contained in the XML file, and output it as the response. I am going to use ASP.NET with C# for this. I understand how to parse the XML and generate the HTML code in C#, but how do I write the HTML code into the response/into the page? The generated dynamic HTML is only in one big div in the page, and the rest of the page is static. What is the best way to do this? As I've never done anything like this before, I'm guessing that one way to do it would be to clear the whole HTML source of the page and use Response.Write() in the Page_Load event to write in the whole HTML of the page, with the XML values already inserted. Is this the correct method, and if so, could you give me a few lines of code as an example to make sure that I'm doing it right? Thanks!
Also, as I've never had the opportunity to do this before, what is the best way of reading a file in ASP.NET C# that is located on your server?
UPDATE: Thank you for all the answers! I have found the solution to my problem, and yet all three answers provided are good ways of approaching this challenge. As you can guess, it's a tough choice who to give the accepted answer to, but I'm going to give it to this answer, by awe, because he clearly put a lot of effort into it, it's a quite elegant solution, and he answered both my questions. Thank you all for the wonderful answers!

Create a div that is accessible in server code:
<div runat="server" id="xmlGeneratedContent"></div>
In Page_Load:
xmlGeneratedContent.InnerHtml = parcedHtmlFromXml;
EDIT:
As answer to the last question: how to read a file on the server...
If the file is located under the web site, you can use Server.MapPath to get the physical disk location from the relative url:
string filename = Server.MapPath("files/file.txt");
How to read it depends on what kind of file it is, and how you want to read it. If you want to read it as plain text, here are some methods:
Read all at once:
string content = System.IO.File.ReadAllText(filename);
Read all at once into string array containing the lines:
string[] content = System.IO.File.ReadAllLines(filename);
Read one line at a time:
System.IO.StreamReader sr = new System.IO.StreamReader(filename);
while (!sr.EndOfStream)
{
string line = sr.ReadLine(); // or other method reading a block
//Do something whith the line
}
sr.Close();
sr.Dispose();

In codebehind function:
public string getHML()
{
return "htmltext";
}
on Page:
<div><%=getHML()%></div>

Just to add to the diversity: My favorite solution is to use
<asp:Literal runat="server" ID="myLiteral" />
And then in code:
this.MyLiteral.Text = "Generated HTML goes here";
The advantage over a <div> is that this generates no extra HTML - so you can put it wherever you want and generate whatever you want.
Often I also set EnableViewState="false" on it, if I can easily regenerate the contents on every request. This cuts down on the ViewState size, because the myLiteral.Text is also saved in ViewState.

Well, your own suggestion would certainly work. Clear out all the html in the ASPX page, and in the Page_Load event you'll do this:
Response.Write(System.IO.File.ReadAllText(yourFilePath));
I don't think there's much more to it.

Related

How do I write a text file from within a C# ASP.NET page?

I'm coming to C# ASP.NET from Ruby and PHP, and I'm enjoying some elements of it but am finding certain things difficult to achieve. It's a bit different to get my head around, and I'd really appreciate it if someone could help me get this bit up and running.
I am trying to take some text sent in a POST request, HTML-escape it, and then write it to a text file.
So I look it up, read a little, and try:
<%
System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath(#"./messager.txt"));
file.WriteLine(Request.Form["message"]);
file.Close();
%>
Not doing the HTML-escaping yet, just trying to actually write to the text file.
This doesn't work, though; it throws no error that I can see, but just does nothing, the text file isn't written to at all. I've researched the methods and can't really figure out why. I would really love some help.
If it helps, here is working Ruby code for what I am trying to do:
File.open "messager.txt", "w" {|f| f.puts h params[:message]}
You have to provide a virtual path relative to the web app when using Server.MapPath using the special character ~ which is a shortcut to the web app root directory. Now, the simplest way to do it is a follows...
System.IO.File.WriteAllText(Server.MapPath("~\messager.txt"), Request.Form["message"]);
this is assuming that the request actually contains the "message" form variable. Note that this approach will create a new file if it doesn't exist or will override it if it does exist.
However, in ASP.NET Web Forms we usually use server controls such as a TextBox, if when posting the page the message is set to a text box, then a better way to retrieve this message in OOP-style would be...
TextBox_ID.Text;
where TextBox_ID is the id of the TextBox
Edit
if Request.Form["message"] is coming in empty. Make sure that:
there's a text input element named message
there's no other element with the same name attribute
the input element is inside the form tag with runat=server attribute
you are posting back the page instead of issuing a GET request

Edit single lines in textfile

Imagine, you are confronted with a big textfile, for example HTML, and only want to edit one line of code in this file.
The standard approach would be to first read everthing and then write everthing, including the changed text, back to a separate file, which would not be very efficient in this usecase.
I want to use a similar approach to open a file in the Editor, find the line you need and then edit this specific line.
Is there any FileIO that allows actual editing/replacing in stead of plain append or create?
EDIT:
What I have in my mind so far is exactly the example that Rahul Singh gave below.
But as mentioned, if I think about this approach it doesn't seem very efficient if you just want to edit one or even a few lines. In my actual problem where the question came from, the file is a HTML file in which want to insert a additional table row. But I think this use-case also is interesting to all files that contains plain text
You can use HTML Agility Pack.
This is an agile HTML parser that builds a read/write DOM and supports
plain XPATH or XSLT.It is a .NET code library that allows you to parse "out of the web"
HTML files.
For example this code fix all hrefs in HTML file:
HtmlDocument doc = new HtmlDocument();
doc.Load("file.htm");
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[#href"])
{
HtmlAttribute att = link["href"];
att.Value = FixLink(att); //FixLink() is your custom method
}
doc.Save("file.htm");
firstly please share what you have tried so far, as we dont have any idea upon data that your textFile contains,
First read through out the file in streamreader and store it into string then do string.replace and do the editing, you could also use the split options and by check it by contains function do the editing.
and you can always go by XSLT options but for that you need to use XPath to select

response.write writes after html closing tag, how to instead replace a string from the response inside html?

in the global.asax to measure the request execution time in the onbeginrequest (start the stopwatch) and onendrequest (calculate the difference).
then in the end request do response.write with the result.
however it writes the result AFTER the closing html tag. basically appends to the end.
current line of code is:
HttpContext.Current.Response.Write(elapsedTime);
is there an easy way for the response write to REPLACE the string ::actualResult:: within the actual html with the actual result string from the response write?
i've tried a lot of things including searching online but seems no one needs this or i suck at searching. i thought i could just get the entire response somehow and replace from there but unsure how to do that... something along ...Response.GetTheEnitreResponse??.Replace... of course that is just wishful thinking ;)
thnx
You didn't specify if you were using web forms, MVC, web pages, etc. but normally these frameworks have buffered a response that has been output by whatever page the user is hitting. Your code in onendrequest is coming to the party after all of the page contents (normally closed with an html closing tag) has been output to the buffer. So when you do a Response.Write you are appending to that html, thus it is outside the closing html tag.
If you want to have the timing be visual on the page you will have to parse into the response and inject your string. This looks hard to do outside of a Page class in ASP.NET.
Messy, and there are better alternatives. Tracing is usually the way these types of things are handled.
You may want to consider writing this information out to a Glimpse trace or somehow hooking into its display... I can't say enough about Glimpse.
Rather than writing the elapsed value to the response, you could store the result in HttpContext.Items and then access this on the view/page:
HttpContext.Current.Items.Add("elapsed", elapsed);
HttpContext.Items Property

Reading values from webpage programmatically

I don't know what it called, but i think this is possible
I am looking to write something(don't know the exact name) that will,
go to a webpage and select a value from drop-down box on that page and read values from that page after selection, I am not sure weather it called crawler or activity, i am new to this but i heard long time back from one of my friend this can be done,
can any one please give me a head start
Thanks
You need an HTTP client library (perhaps libcurl in C, or some C# wrapper for it, or some native C# HTTP client library like this).
You also need to parse the retrieved HTML content. So you probably need an HTML parsing library (maybe HTML agility pack).
If the targeted webpage is nearly fixed and has e.g. some comments to ease finding the relevant part, you might use simpler or ad-hoc parsing techniques.
Some sites might send a nearly empty static HTML client, with the actual page being dynamically constructed by Javascript scripts (Ajax). In that case, you are unlucky.
Maybe you want some web service ....
One simple way (but not the most efficient way) is to simply read the webpage as String using the WebClient, for example:
WebClient Web = new WebClient();
String Data = Web.DownloadString("Address");
Now since HTML is simply an XML document you can parse the string to a XDocument and look up the tag that represents the dropdown box. Parsing the string to XDocument is done this way:
XDocument xdoc = XDocument.Pase(Data);
Update:
If you want to read the result of the selected value, and that result is displayed within the page do this:
Get all the items as I explained.
If the page does not make use of models, then you can use your selected value as an argument for example :
www.somepage.com/Name=YourItem?
Read the page again and find the value

Sending information from one webform to another

i'm generating HyperLinks, all of them (depending on the circunstance, could be 1, 2 or 1000) send to the same webform:
from default.aspx
to envia.aspx
i can't use session, or anything i already know, because i can't create as many methods i want (that would not be good, due to possible large numbers)
example, there are three lines i print on demand:
house [link]
car [link]
flower[link]
i want the three links to load the same aspx webform sending as a parameter a string with these lines.
i don't care if the answer is in vb.net or in c#, anything you could help it's ok (i'm using vb.net though)
can you use Query String?
envia.aspx?param1=something&param2=somethingelse
in envia.aspx:
string param1 = Request["param1"];
string param2 = Request["param2"];
What about crosspage postbacks? Only used it once, but this sounds like a good candidate for it. See Cross-Page Posting in ASP.NET Web Pages, http://msdn.microsoft.com/en-us/library/ms178139.aspx

Categories