How to render XML file using CodeBehind C# - c#

I wanted to know how can I get request to XML file (.xml) but to render the response using codebehind... (like doing <% ... %> )
Thanks

Not sure I understand the question, but you seem to ask about something like
<%
Response.Clear();
Response.ContentType="text/xml";
Response.Write("<?xml version=""1.0"" encoding=""UTF-8"">");
Response.Write("<MyFancyRecord>");
Response.Write("<Title>" + someRec.Title + "</Title>");
Response.Write("<Price>" + (someRec.Price * 1.20) + "</Price>");
// etc.
Response.Write("</MyFancyRecord>");
Response.End();
%>
As hinted in other response, while this approach is a direct answer to the OP's question, it is typically better to map non-html requests to handlers.

Requests to ASP.NET applications that return XML or other non-HTML responses are best implemented as handlers (*.ASHX). You can find an example of how to do this here:
http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx

Related

How to load local html page in web form

I wish to load a local html page in my web form.
The code I'm using looks like
Response.Redirect("C:\Player\Results\xyz.html", false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
I know there are similar questions asked but none helped me.
It would be very much helpful if someone can let me know where I'm going wrong
Thank you
#m_beta you are using the physical path for redirection. This will necessiate you to change the code whenever you move your code location. Use relative path instead.
It would be something like below. You need to correct the path according to your location.
Response.Redirect("~/admin/paths.aspx", false);
Redirecting to a http / https url that will respond with the static content is one thing, but no browser is going to load a local file. If browsers did that it would introduce a massive security risk.
You can add redirection like this also
If localhost, check your localhost value add like below
Response.Redirect("http://localhost:51043/xyz.html");
Live site
Response.Redirect("http://xyzdotcom/xyz.html");
A simple way might be :
var htmlContent = System.IO.File.ReadAllText(#"C:\Player\Results\xyz.html");
Response.Write(htmlContent);
Use IFrame and use it;s SRC property to call your html page
There are many ways to do it but I would like to mention the 2 which worked for me
In this approach the response will be redirected to the page you are passing.
Response.Redirect("~/Results/xyz.html", false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
In this below mentioned approach the content of the html page which you wish to render will be read and then passed on using OutputStream.
var encoding = new System.Text.UTF8Encoding();
var htm = System.IO.File.ReadAllText(Server.MapPath("/Results/Html/") + "xyz.html", encoding);
byte[] data = encoding.GetBytes(htm);
Response.OutputStream.Write(data, 0, data.Length);
Response.OutputStream.Flush();
Thanks to everyone who has contributed here!

C# - create and write HTML file with variables

Basiclly I'm trying to create an HTML, I already have it written but I want the user to be able to put some text on the textboxes and saving it into strings and use later when creating the HTML file.
I tried playing abit with StreamWriter but I don't think that will be the best idea.
Also I want it to open on the default web browser , or just on IE if it's easier after the file is created.
I really need help as I'm struggling especially with the creating part.
Thanks for reading!
You can also do this without external libraries.
Set up your HTML file as follows:
<!DOCTYPE html>
<html>
<header>
<title>{MY_TITLE}</title>
</header>
<body></body>
</html>
Then edit and save the HTML from C#:
const string fileName = "Foobar.html";
//Read HTML from file
var content = File.ReadAllText(fileName);
//Replace all values in the HTML
content = content.Replace("{MY_TITLE}", titleTextBox.Text);
//Write new HTML string to file
File.WriteAllText(fileName, content);
//Show it in the default application for handling .html files
Process.Start(fileName);
If you already have the HTML you want to export (just not customized), you could manually add format strings to it (like {0}, {1}, {2}) where you want to substitute text from your app, then embed it as a resource, load it in at runtime, substitute the TextBox text using string.Format, and finally write it out again. This is admittedly a really fragile way to do it, as you need to make sure the number of parameters agrees between the resource file and your call to string.Format. In fact, this is a horrible way to do it. Actually, you should do it the way #EmilePels suggests, which is basically a less fragile version of this answer.

Why url parameter doesn't have correct format in javascript?

I have to create a javascript which contains an url in code behind page using C#. But the url parameter inside javascript doesn't have correct format after generated by C#.
Example:
Url parameter: http://google.com
Javascript: javascript:dnnModal.show('http://google.com',false,365,206,false)
C# code:
string link = "http://google.com?popUp=true";
string googleIcon = "<a href='javascript:dnnModal.show('" + link +',false,365,206,false)'><img border='0' src='~/Icons/gIcon.png'></a>";
After generated from code behind the page view the url incorrect format. There is the code of googleIcon after I am using "View Select Source" to view the code of aspx page:
<img src="~/Icons/gIcon.png" border="0">
The hyperlink on icon just show this when I move the mouse over it:
javascript:dnnModal.show(
The url is lost and the remind string is lost too.
I need some help on my issue to show the way how to pass an url parameter into javascript using C#.
Should be like this,
string googleIcon = "<img border='0' src='~/Icons/gIcon.png'>";
You are not escaping the strings properly
string googleIcon = "<a href='javascript:dnnModal.show(\"" + link +"\",false,365,206,false)'><img border='0' src='~/Icons/gIcon.png'></a>";
I agree with two other answers, but you should try to encapsulate these kind of tasks in a user control maybe. but if that's not possible I suggest to use System.Web.UI.HtmlControls instead, since it will give you more flexibility.
Something like this:
HtmlLink myHtmlLink = new HtmlLink();
myHtmlLink.Href = #"javascript:dnnModal.show(\"" + link +"\",false,365,206,false)";
HtmlImage myImage = new HtmlImage();
myImage.Src = "~/Icons/gIcon.png";
myImage.Border = 0;
myHtmlLink.Controls.Add(myImage);
I like this approach more because Asp.net is responsible for creating DOM, which means that you will be safe and you're guaranteed to get a valid XHTML result.

Trouble Scraping .HTM File

I have just begun scraping basic text off web pages, and am currently using the HTMLAgilityPack C# library. I had some success with boxscores off rivals.yahoo.com (sports is my thing so why not scrape something interesting?) but I am stuck on NHL's game summary pages. I think this is kind of an interesting problem so I would post it here.
The page I am testing is:
http://www.nhl.com/scores/htmlreports/20102011/GS020079.HTM
Upon first glance, it seems like basic text with no ajax or stuff to mess up a basic scraper. Then I realize I can't right click due to some javascript, so I work around that. I right click in firefox and get the xpath of the home team using XPather and I get:
/html/body/table[#id='MainTable']/tbody/tr[1]/td/table[#id='StdHeader']/tbody/tr/td/table/tbody/tr/td[3]/table[#id='Home']/tbody/tr[3]/td
When I try to grab that node / inner text, htmlagilitypack won't find it. Does anyone see anything strange in the page's source code that might be stopping me?
I am new to this and still learning how people might stop me from scraping, any tips or tricks are gladly appreciated!
p.s. I observe all site rules regarding bots, etc, but I noticed this strange behavior and saw it as a challenge.
Ok so it appears that my xpaths have tbody's in them. When I remove these tbodys manually from the xpath, HTMLAgilityPack can handle it fine.
I'd still like to know why I am getting invalid xpaths, but for now I have answered my question.
I think unless my xpath knowledge is heaps flawed(probably) the problem is with the /tbody node in your xpath expression.
When I do
string test = string.Empty;
StreamReader sr = new StreamReader(#"C:\gs.htm");
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(sr);
sr.Close();
sr = null;
string xpath = #"//table[#id='Home']/tr[3]/td";
test = doc.DocumentNode.SelectSingleNode(xpath).InnerText;
That works fine.. returns a
"COLUMBUS BLUE JACKETSGame 5 Home Game 3"
which I hope is the string you wanted.
Examining the html I couldn't find a /tbody.

Creating XML in C# for jQuery

I'm trying to generate some XML for a jQuery.get (AJAX) call, and I'm getting the following error from my C# page: "Using themed css files requires a header control on the page. (e.g. <head runat="server" />)."
The file generating the XML is a simple .aspx file, consisting entirely of:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ChangePeopleService.aspx.cs" Inherits="ChangeRegister.Person.ChangePeopleService" EnableTheming="false" %>
with codebehind using Linq-to-XML, which is working ok:
XElement xml = new XElement("People",
from p in People
select new XElement("Person", new XAttribute("Id", p.Id),
new XElement("FirstName", p.FirstName)));
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.Write(xml.ToString());
I know that the error relates to the Web.Config's <pages styleSheetTheme="default" theme="default"> tag, because when I remove the 'styleSheetTheme' and 'theme' attributes, the XML gets generated ok. The problem then obviously is that every other page loses its styling. All this leads me to think that I'm approaching this wrong.
My question is: what's an accepted way to generate XML in C#, for consumption by a jQuery AJAX call, say?
If I am returning simple data (not a page), I probably wouldn't use aspx; that is really web-forms, but what you are returning isn't a web-form. Two options leap to mind:
use ASP.NET MVC; sounds corny, but it really is geared up to return different types of response much more elegantly
use a handler (ashx) - which omits all the web-form noise, just leaving you with a HttpContext with which to construct your response
You could also try (within aspx) clearing the response (Clear()?) and calling Close() afterwards. But IMO a lot more roundabout than just using a handler.
You need to use theme=""
example:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ChangePeopleService.aspx.cs" Inherits="ChangeRegister.Person.ChangePeopleService" Theme="" %>
Try writing to the Response.OutputStream instead:
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
using (TextWriter textWriter
= new StreamWriter(HttpContext.Current.Response.OutputStream, Encoding.UTF8))
{
XmlTextWriter writer = new XmlTextWriter(textWriter);
writer.WriteString(xml.ToString());
}

Categories

Resources