Prompt user to download .html page generated from .aspx - html

I have a default page with a button that prompts user to download a "signature"
Which is basically an .html file with specific format (based on user info)
So currently I have an .aspx page but I'm not sure how to make the user download the "rendered HTML page from that aspx"
On the default page i have the following
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.ContentType = "text/html"
Response.AppendHeader("Content-Disposition", "attachment; filename=My_Signature.html")
Response.TransmitFile(Server.MapPath("~/Signature.aspx"))
Response.End()
End Sub
Is it possible to render the aspx page in the background then somehow prompt the user to download it ( the resulted html) ?

You're making it more difficult than it is. Simply download the file content as you would from any other website, store it in a string, write it to the response.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Response.ContentType = "text/html"
Response.AppendHeader("Content-Disposition", "attachment; filename=My_Signature.html")
Dim contents As String = New System.Net.WebClient().DownloadString(Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/Signature.aspx"))
Response.Write(contents)
Response.End()
End Sub
Of course, a better solution would be to put your code for generating the signature in a Class Library (.dll) and then call that as needed.

You could override the Render() method of the aspx file so it writes an html file:
Protected Overrides Sub Render(writer As HtmlTextWriter)
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
Dim hwriter As New HtmlTextWriter(sw)
MyBase.Render(hwriter)
Using outfile As New StreamWriter(Server.MapPath(".") + "\signature.html")
outfile.Write(sb.ToString())
End Using
Response.ContentType = "text/html"
Response.AppendHeader("Content-Disposition", "attachment; filename=signature.html")
Response.TransmitFile(Server.MapPath("~/signature.html"))
Response.End()
End Sub
All this would be in the aspx file to be converted to html (signature.aspx). I would say have your button click do a redirect to a new window that calls the aspx, and thus this method.

Related

Get website's inner text without webbrowser

I want to get website's inner text through code.
I can already get it's inner html with code below, but i can't find any code that's getting URL's inner text without webbrowser.
This code is getting text from website in webbrowser, but i need same thing, just without webbrowser.
Dim sourceString As String = WebBrowser1.Document.Body.InnerText
With HtmlAgilityPack...
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
Dim doc As HtmlAgilityPack.HtmlDocument = New HtmlAgilityPack.HtmlDocument
With New Net.WebClient
doc.LoadHtml(.DownloadString("https://example.com"))
.Dispose()
End With
Debug.Print(doc.DocumentNode.Name)
PrintChildNodes(doc.DocumentNode)
Debug.Print(doc.DocumentNode.Element("html").Element("body").InnerText)
End Sub
Sub PrintChildNodes(Node As HtmlAgilityPack.HtmlNode, Optional Indent As Integer = 1)
For Each Child As HtmlAgilityPack.HtmlNode In Node.ChildNodes
Debug.Print("{0}{1}", String.Empty.PadLeft(Indent, vbTab), Child.Name)
PrintChildNodes(Child, Indent + 1)
Next
End Sub
**Taken from **
Wolfwyrd
In this question HTTP GET in VB.NET
Try
Dim fr As System.Net.HttpWebRequest
Dim targetURI As New Uri("http://whatever.you.want.to.get/file.html")
fr = DirectCast(HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)
If (fr.GetResponse().ContentLength > 0) Then
Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
Response.Write(str.ReadToEnd())
str.Close();
End If
Catch ex As System.Net.WebException
'Error in accessing the resource, handle it
End Try
You will get Html as well as http headers. Don't think this will work by itself with https.

get HTMLDocument from HttpWebRequest without HtmlAgilityPack

I'm trying to write a function that returns an "htmlDocument" using "HttpWebRequest" instead of a browser but I'm stuck with transferring of innerhtml.
I don't understand how to set value of "mWebPage" because VB doesn't accept "New" for HTMLDocument
I know that I can use "HtmlAgilityPack" but I would like to test my current code, changing only web request and not to change all parsing code.(To do this I need an HtmlDocument)
After this test, I'll try to change also the parsing code.
Function mWebRe(ByVal mUrl As String) As HTMLDocument
Dim request As HttpWebRequest = CType(WebRequest.Create(mUrl), HttpWebRequest)
' Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4
request.MaximumResponseHeadersLength = 4
' Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials
'Here I've tryed many types
Dim mWebPage As HTMLDocument
Try
Dim request2 As HttpWebRequest = WebRequest.Create(mUrl)
Dim response2 As HttpWebResponse = request2.GetResponse()
Dim reader2 As StreamReader = New StreamReader(response2.GetResponseStream())
Dim WebContent As String = reader2.ReadToEnd()
'This is my last attempt
'This gives Null Reference Exception
mWebPage.Body.InnerHtml = WebContent
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return mWebPage
End Function
I've tryed many ways (also import HTML Object Library) but nothing worked :(
Okay this is becoming more of a hack by the minute, but this should work.
First, you'll need to instantiate your WebBrowser control at the class level:
Private m_objWebBrowser As WebBrowser
Next add an Event Handler for the DocumentCompleted Event that contains all your HTML parsing data. You get an instance of the HtmlDocument using the OpenNew method of the WebBrowser control.
Private Sub HandleParsing(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
'Use your code for generating WebContent.
Dim WebContent As String = "<html></html>"
Dim mWebPage As HtmlDocument = DirectCast(sender, WebBrowser).Document.OpenNew(True)
mWebPage.Write(WebContent)
End Sub
Finally, you can trigger all of this by wiring up the Event Handler and navigating to some page or Html file on disk (DocumentCompleted fires asynchronously):
AddHandler m_objWebBrowser.DocumentCompleted, AddressOf HandleParsing
m_objWebBrowser.Navigate("www.google.com")
I found a solution on the web and modified my code as below:
To make it work you must activate reference to "Microsoft HTML object library" (in .Com references)
It is obsolete but it seems to be the only way to make an html document without using webbrowser.
I Hope it helps someone else.
Function mWebRe(ByVal mUrl As String) As MSHTML.HTMLDocument
Dim request As HttpWebRequest = WebRequest.Create(mUrl)
Dim doc As MSHTML.IHTMLDocument2 = New MSHTML.HTMLDocument
' Set some reasonable limits on resources used by this request
request.MaximumAutomaticRedirections = 4
request.MaximumResponseHeadersLength = 4
' Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials
Try
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
Dim WebContent As String = reader.ReadToEnd()
doc.clear()
doc.write(WebContent)
doc.close()
'To make sure that the data is fully load.
While (doc.readyState <> "complete")
'This for more waiting (if needed)
'System.Threading.Thread.Sleep(1000)
Application.DoEvents()
End While
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return doc
End Function

Can I automatically convert .ppt to .html?

I have been trying to work out the best way for a power point to be shown on a Intranet. The users in the company will not be very technical and might not follow the processes I will describe.
I found this page
Which shows how to convert a power point in to a html page which can be viewed. I was wanting to know if there is some way to automate this process. Such as a file watcher watching the location it will saved and then as soon as it is seen automatically changes this to a html using the code provided on the page I gave. Preferred language to use would be VB.NET.
I am happy for any suggestions that people can give.
Thanks in advance
You can try with this code - based on Microsoft.Office.Interop.PowerPoint.Application
You have sample of code in order to try functionality
View Aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="AspNetPowerPointConvertToHTML.aspx.vb" Inherits="AspNetPowerPointConvertToHTML" %>
<html>
<head>
<title>ShotDev.Com Tutorial</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label id="lblText" runat="server"></asp:Label>
</form>
</body>
</html>
Code behind
Imports Microsoft.Office.Interop.PowerPoint
Public Class AspNetPowerPointConvertToHTML
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim ppApp As New Microsoft.Office.Interop.PowerPoint.Application
Dim ppName As String = "MySlides.ppt"
Dim FileName As String = "MyPP/MyPPt"
ppApp.Visible = True
ppApp.Presentations.Open(Server.MapPath(ppName))
ppApp.ActivePresentation.SaveAs(Server.MapPath(FileName), 13)
ppApp.Quit()
ppApp = Nothing
Me.lblText.Text = "PowerPoint Created to Folder <strong> " & FileName & "</strong>"
End Sub
End Class
I've used the:
Imports PowerPoint = Microsoft.Office.Interop.PowerPoint
to be able to automatically change a power point in to a HTML. I've used a file watcher to watch a directory on my computer to look out for power point presentations at the moment it is only set to .pptx however I'll change this to add other formats soon. This fileWater is sat on a service that starts up when the computer does. It then looks to see if a powerpoint has been created or modified and runs this code:
Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
'set varaibles so that html can save in correct place
Dim destinationDirectory As String = e.FullPath.Replace(e.Name.ToString(), "")
Dim sourceLocation As String
Dim fileName As String
'couple of if statements to get rid of unwanted characters
If e.Name.Contains("~$") Then
fileName = e.Name.Replace("~$", "")
fileName = fileName.Replace(".pptx", ".html")
Else
fileName = e.Name
fileName = fileName.Replace(".pptx", ".html")
End If
If e.FullPath.Contains(("~$")) Then
sourceLocation = e.FullPath.Replace("~$", "")
Else
sourceLocation = e.FullPath
End If
Dim strSourceFile As String = sourceLocation 'set source location after removing unwanted characters
Dim strDestinationFile As String = destinationDirectory & fileName 'set the destination location with the directory and file name
'set ppAPP to a power point application
Dim ppApp As PowerPoint.Application = New PowerPoint.Application
Dim prsPres As PowerPoint.Presentation = ppApp.Presentations.Open(strSourceFile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse)
'Call the SaveAs method of Presentaion object and specify the format as HTML
prsPres.SaveAs(strDestinationFile, PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue)
'Close the Presentation object
prsPres.Close()
'Close the Application object
ppApp.Quit()
End Sub
This gets the file which has been modified and saves it as a html document. It will also get the files needed to run so if any animations have been saved it will also keep those.

how to parse html contents returned as a response from a webserver and show a specific tag value in a combobox in desktop application in vb.net

i am trying to fetch some data from Url using Httpwebrequest/response, i am getting response which i am showing in a msgbox. It show whole HTML contents.
Now my i want to fetch a specific tag(TD tag) value and show all its value in a combobox in vb.net desktop application.
my code to get response from webserver is :
enter code here
Imports System.IO
Imports System.Net
Imports System.Xml
Imports System.Text.Encoder
Public Class login
Private Sub login_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End
End Sub
Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint
End Sub
Private Sub Ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Ok.Click
Dim strId As String = txt_uid.Text
Dim strPwd As String = txt_pwd.Text
Dim oEncoder As New System.Text.ASCIIEncoding
Dim postData As String = "UM_username=" + strId
postData += ("&UM_password=" + strPwd)
Dim data As Byte() = oEncoder.GetBytes(postData)
MsgBox(postData)
Dim webStream As Stream
Dim webResponse As String = ""
Dim req As HttpWebRequest
Dim res As HttpWebResponse
Dim Output As String
'Dim Posit1 As Int32
'Dim Posit2 As Int32
req = WebRequest.Create("http://localhost/basic_framework/index.php?menu=login&UM_email=" & strId & "&UM_password=" & strPwd)
req.ContentType = "application/x-www-form-urlencoded"
req.KeepAlive = False
req.Method = "POST"
res = req.GetResponse()
webStream = res.GetResponseStream()
Dim webStreamReader As New StreamReader(webStream)
While webStreamReader.Peek >= 0
Output = webStreamReader.ReadToEnd()
RichTextBox1.Text = Output
Msgbox(Output)
End While
End Sub
End Class
this code get the response from url and show it in a richtextbox or msgbox
Now i want to get a specific tag value (say, td, option values) and show it in a combobox in my vb.net application form dynamically.It would be needed to parse html content then get that tag value . Please suggest me a way......
If parsing needed , how to parse html contents to get only specific tag value in a combobox in vb.net form
Well...if you can be sure that your request returns valid XHTML (which is XML indeed), you might be able to use an XPath expression.
For the most complicated cases (e.g., an AJAX web-site, etc.) you could use HTMLUnit library with iKVM.

vb.NET WebRequest to read aspx page to string, access denied?

I'm trying to make an executable in VS2008 that will read a webpage source code using a vb.NET function into a string variable. The problem is that the page is not *.html but rather *.aspx.
I need a way to execute the aspx and get the displayed html into a string.
The page I want to read is any page of this type: http://www.realtor.ca/PropertyDetails.aspx?PropertyID=9620716
I have tried the following code, which works properly for html pages, but generates the wrong source code with "access denied" for the page title when I pass in the above aspx page.
Dim myReq As WebRequest = WebRequest.Create(url)
Dim myWebResponse As WebResponse = myReq.GetResponse()
Dim dataStream As Stream = myWebResponse.GetResponseStream()
Dim reader As New StreamReader(dataStream, System.Text.Encoding.UTF8)
Dim responseFromServer As String = reader.ReadToEnd()
Any suggestions or ideas?
I get the same thing while running wget from the command line:
wget http://www.realtor.ca/PropertyDetails.aspx?PropertyID=9620716
I guess the server is relying on that something is set in the browser before the response is delivered, e.g. a cookie. You might want to try using a WebBrowser control (you don't have to have it visible) in the following way (this works):
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf DocumentCompletedHandler)
WebBrowser1.Navigate("http://www.realtor.ca/PropertyDetails.aspx?PropertyID=9620716")
End Sub
Private Sub DocumentCompletedHandler(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
Console.WriteLine(WebBrowser1.DocumentText)
End Sub
End Class