HttpWebRequest reades only homepage - c#

Hi I tried to read a page using HttpWebRequest like this
string lcUrl = "http://www.greatandhra.com";
HttpWebRequest loHttp = (HttpWebRequest)WebRequest.Create(lcUrl);
loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Code Sample Web Client";
HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();
Encoding enc = Encoding.GetEncoding(1252); // Windows default Code Page
StreamReader loResponseStream =
new StreamReader(loWebResponse.GetResponseStream(), enc);
string lcHtml = loResponseStream.ReadToEnd();
mydiv.InnerHtml = lcHtml;
// Response.Write(lcHtml);
loWebResponse.Close();
loResponseStream.Close();
i can able to read that page and bind it to mydiv. But when i click on any one of links in that div it is not displaying any result. Because my application doesnt contain entire site. So what we will do now.
Can somebody copy my code and test it plz
Nagu

I'm fairly sure you can't insert a full page in a DIV without breaking something. In fact the whole head tag may be getting skipped altogether (and any javascript code there may not be run). Considering what you seem to want to do, I suggest you use an IFRAME with a dynamic src, which will also hopefully lift some pressure off your server (which wouldn't be in charge of fetching the html to be mirrored anymore).

If you really want a whole page of HTML embedded in another, then the IFRAME tag is probably the one to use, rather than the DIV.
Rather than having to create a web request and have all that code to retrieve the remote page, you can just set the src attribute of the IFRAME to point ot the page you want it to display.
For example, something like this in markup:
<iframe src="<%=LcUrl %>" frameborder="0"></iframe>
where LcUrl is a property on your code-behind page, that exposes your string lcUrl from your sample.
Alternatively, you could make the IFRAME runat="server" and set its src property programatically (or even inject the innerHTML in a way sismilar to your code sample if you really wanted to).

The code you are putting inside .InnerHtml of the div contains the entire page (including < html >, < body >, < /html > and < /body> ) which can cause a miriad of problems with any number of browsers.
I would either move to an iframe, or consider some sort of parsing the HTML for the remote site and displaying a transformed version (ie. strip the HTML ,BODY, META tags, replace some link URLs, etc).

But when i click on any one of links in that div it is not displaying any result
Probably because the links in the download page are relative... If you just copy the HTML into a DIV in your page, the browser considers the links relative to the current URL : it doesn't know about the origin of this content. I think the solution is to parse the downloaded HTML, and convert relative URLs in href attributes to absolute URLs

If you want to embed it, you need to strip everything but the body part. That means that you have to parse your string lcHTML for <body....> and remove everything before and includeing the body tag. You must also strip away everything from </body>. Then you need to parse the string for all occurences of <a href="....."> that do not start with http:// and include h t t p://www.greatandhra.com or set <base target="h t t p://www.greatandhra.com"> in your head section.
If you don't want to embed, simply clear the response buffer and stream the lcHTML string back to the browser.
PS: I had to write all h t t p with spaces to be able to post this.

Sounds like what you are trying to do is display a different site embedded in your site. For this to work by dropping it into a div you would have to extract the code between the body tags as it wouldn't be valid with html and head in the middle of another page.
The links won't work because you've now taken that page out of context in your site so you'd also have to rewrite any links on the page that are relative (i.e. don't start with http) to point to a page on your site which will then fetch the other sites page and display them back in your site, or you could add the url of the site you're grabbing to the beginning of all the relative links so they link back to that site.

Related

Displaying images from database using c# .net

recently, I've been developing a website with .NET c# and I've been trying to display images via the imagepath in the db. It is currently working by this line of code.
return File(byte array, "image/jpeg");
The problem is that by this line of code the layout page is completely ignored as only the image with white background is shown. I need to display the image along with the return view (the image inside the layout of the website). thx
The reason you're not seeing anything is because you can only have one type of response per request; Either a response containing HTML or a response containing the image.
What you need to do in order to serve images via your application is set up a route that you can put in your <img> tags as the src attribute.
<img src="/static/images/123">
Your route would listen for requests on the /static/images/ path and then try to parse the ID number at the end. It could then take that ID number (123) and look up the relevant image in your database.
So, to be clear, you'd have at least two requests that occur; First, you serve the request for the page, then you serve subsequent requests for the image(s). These two request handlers do not share the same code.
Finally, if you really wanted to "inline" an image as part of the page response, The only way you can "inline" an image into a page is to base64 encode it and set that as as the src of an <img> tag. This process is slow and bloats your HTML, making it take longer to load.

Set base URL of Windows Phone 8.1 WebView and use NavigateToString()

In my app I want to load an html that contains an iframe with a remote url. This html is always the same, except for the iframe's src. What I do is hold the html in a string, and fill in the iframe url, than call NavigateToString(html). I get the iframe url from a REST API. I also get a baseUrl. If I merge those two urls into an absoulute url and set that as the iframe's src, the page won't load due to security reasons (it's a payment page). But if I set it without baseUrl, of course, the webview has no idea what's the baseUrl is, and the page also won't load.
In Android one could simply call webView.loadDataWithBaseURL. Is there something like this in Windows Phone 8.1? Any workaround?
(The problem is further complicated by that I also have to set Cookies to the webview.)
I came up with a solution, which works, and actually it's less hacky than it seemed to me at first.
I skipped NavigateToString. By using NavigateWithHttpRequestMessage, I can send a request to an URL, for example http://mybackend.com. I can set cookies as well (more information on this: https://social.msdn.microsoft.com/Forums/windowsapps/en-US/a451d411-9312-4d40-80ee-112e166144ab/how-to-send-auth-cookie-in-webview-request?forum=winappswithcsharp). So far I have:
base URL set
cookies set.
Though, I haven't set my local html string yet. For this, in the WebView's NavigationCompleted event, I run a JS script like this:
await wvSecurePay.InvokeScriptAsync("eval", new string[] { "document.getElementsByTagName('html')[0].innerHTML = '" + htmlToLoad + "';"})
This will replace the current html content with the one I want to load. So I have my html containing the iframe with the relative url on a page which has the domain I need.

How to assign HTML content to iframe control from asp.net codebehind?

I want to assign the html content to iframe control from asp.net code behind page;
this is working fine
myIframe.Attributes.Add("src", "pathtofilewith.html");
but, i don't want to give the path of html file to display i just want to assign some html content which comes from database to iframe control.
i want some thing like this(Ashok) to be displayed in iframe control
i tried the bellow ways but nothing is succesful
myIframe.Attributes["innerHTML"] = "<h1>Thank You..</h1>";
myIframe.Attributes.Add("innerHTML", "<h1>Ashok</h1>");
A way to communicate between two different pages where one is in an IFrame on the other, is to post data using JQuery. An example is given in this StackOverflow question
It is also discussed in this other StackOverflow question
On this page, you will also find a short and simple example of how you can put content in an IFrame without using a separate web-page for it (note the lacking src attribute!).
Hope some of this helps!
You can't. That's not how an IFRAME works - it is for use with the src attribute as you've already discovered.
Perhaps you want to create a DIV instead
There is no way to insert HTML content into iframe tag directly, but you can create a page which gets the content form the database and then you can view it using iframe,
or
You can create a page for example called getContent.aspx which request value from the URL e.g. getContent.aspx?content=<h1>Thank You..</h1> and display it wherever you like, and then call it from iframe.

C# extracting html only

Basically i have a webpage with embedded css and JavaScript, so what i want to do is extract only the HTML itself, from texts to tables , images and what not.
So far i have the whole web page stored into a string called "html" the contents of this page is just the facebook hompepage for example,but as you will see there's all scripts and other embedded stuff which i don't want to have.
HTMLEdit = //webpage I chose to store in here//
string html = HTMLEdit.DocumentText;
String result = "this i want to only contain the <head>,<body>,<foot>."
I am only interested in displaying the result witch only contains html, i don't want the JavaScript or css or any other stuff
I have looked at the agility pack but there's no documentation on there website to do this and this is my first ever c# project i have decided to make, so excuse my ignorance if i don't make sense.
See this question
HTML Agility Pack strip tags NOT IN whitelist
Maybe adapt that answer, and drop link and script tags.

How to programmatically load a HTML document in order to add to the document's <head>?

We are supplied with HTML 'wrapper' files from the client, which we need to insert out content into, and then render the HTML.
Before we render the HTML with our content inserted, I need to add a few tags to the <head> section of the client's wrapper, such as references to our script files, css and some meta tags.
So what I'm doing is
string html = File.ReadAllText(wrapperLocation, Encoding.GetEncoding("iso-8859-1"));
and now I have the complete HTML. I then search for a pre-defined content well in that string and insert our content into that, and render it.
How can I create an instance of a HTML document and modify the <head> section as required?
edit: I don't want to reference System.Windows.Forms so WebBrowser is not an option.
I haven't tried this library myself, but this would probably fit the bill: http://htmlagilitypack.codeplex.com/
You can use https://github.com/jamietre/CsQuery to edit an html dom.
var dom = CQ.Create(html);
var dom = CQ.CreateFromUrl("http://www.jquery.com");
dom.Select("div > span")
.Eq(1)
.Text("Change the text content of the 2nd span child of each div");
Just select the head and add to it.
I use the WebBrowser control as host, and navigate/alter the document through its Document property.
Nice documentation and samples at the link above.
Are you using MasterPages?
This seems like the most obvious use of them.
The MasterPage has <asp:ContentPlaceHolder>'s for all the points where you want the content to go.
In our app we have a base controller that overrides all the View() overloads so that it reads in the name of the MasterPage from the web.config. That way customising the app is as simple as a new MasterPage and from a Controllers point of view there is no code change since our base class handles the MasterPage/web.config stuff.
I couldn't get an automated solution to this, so it came down to a hack:
public virtual void PopulateCssTag(string tags)
{
// tags is a pre-compsed string containing all the tags I need.
this.Wrapper = this.Wrapper.Replace("</head>", tags + "</head>");
}

Categories

Resources