simply dump write xml to screen - asp.net

XML/ASP.net VB newbie here having fun can't find needle in haystack.
I just want to dump some XML to the screen! Loads of sites tell me how to iterate the nodes, xpath my way in directly. I just want the whole lot to screen.
Dim doc As New XmlDocument
doc.Load("remote.xml")
Dim writer as XmlTextWriter = new XmlTextWriter("debug.xml",nothing)
writer.Formatting = Formatting.Indented
doc.Save(writer)
Does a sterling job of getting it to a file, but I want it on the screen. doc.print(writer).....
Please help.

Try it with the innerXml of your doc. Make sure to HtmlEncode it for it to show up. Stick a literalcontrol on your aspx with id='ltXml' and then something like this:
Dim doc As New XmlDocument()
doc.Load(Server.MapPath("~/remote.xml"))
ltXml.Text = Server.HtmlEncode(doc.InnerXml)
Edited per comment by OP.
Have the function in your class return the Xml string.
Private Class [MyClass]
Public Shared Function getXml() As String
Dim doc As New XmlDocument()
doc.Load("somefile.xml")
Return HttpContext.Current.Server.HtmlEncode(doc.InnerXml)
End Function
End Class
Then in your aspx code behind of your webpage call the class function:
ltXml.Text = [MyClass].getXml()

I suggest using the modern XDocument class instead of the old, deprecated XmlDocument.
XDocument.ToString already returns a nicely formatted version of the XML, so all you need to do is:
Dim doc As XDocument = XDocument.Load("remote.xml")
Dim formatted As String = doc.ToString()

Related

How to get Description of Youtube embeded videos in my asp.net application?

I am using the below code to get the Title and description of the youtube video embeded in my asp.net application. I am able to see the Title, but not description.
I use Atomfeed to do this...
Problem is i get the Description as "Google.GData.Client.AtomTextConstruct" for all my videos.
Private Function GetTitle(ByVal myFeed As AtomFeed) As String
Dim strTitle As String = ""
For Each entry As AtomEntry In myFeed.Entries
strTitle = entry.Title.Text
Next
Return strTitle
End Function
Private Function GetDesc(ByVal myFeed As AtomFeed) As String
Dim strDesc As String = ""
For Each entry As AtomEntry In myFeed.Entries
strDesc = entry.Summary.ToString()
Next
Return strDesc
End Function
I believe that when the XML from the atom feed is parsed, that the description is not handled. Take a look at this: http://code.google.com/p/google-gdata/wiki/UnderstandingTheUnknown
But what happens with things that are not understood? They end up as
an element of the ExtensionElements collection, that is a member of
all classes inherited from AtomBase, like AtomFeed, AtomEntry,
EventEntry etc...
So, what we can do is pull out the description from the extensionelement like this:
Dim query As New FeedQuery()
Dim service As New Service()
query.Uri = New Uri("https://gdata.youtube.com/feeds/api/standardfeeds/top_rated")
Dim myFeed As AtomFeed = service.Query(query)
For Each entry In myFeed.Entries
For Each obj As Object In entry.ExtensionElements
If TypeOf obj Is XmlExtension Then
Dim xel As XElement = XElement.Parse(TryCast(obj, XmlExtension).Node.OuterXml)
If xel.Name = "{http://search.yahoo.com/mrss/}group" Then
Dim descNode = xel.Descendants("{http://search.yahoo.com/mrss/}description").FirstOrDefault()
If descNode IsNot Nothing Then
Console.WriteLine(descNode.Value)
End If
Exit For
End If
End If
Next
Next
Also, the reason why you are getting "Google.GData.Client.AtomTextConstruct" is because Summary is an object of type Google.GData.Client.AtomTextConstruct, so doing entry.Summary.ToString() is just giving you the default ToString() behavior. You would normally do Summary.Text, but this of course is blank because as I say above, it's not handled properly by the library.
For youtube, I fetch the information for each video using the Google.GData.YouTube.
Something like this returns a lot of information from the video.
Dim yv As Google.YouTube.Video
url = New Uri("http://gdata.youtube.com/feeds/api/videos/" & video.Custom)
r = New YouTubeRequest(New YouTubeRequestSettings("??", "??"))
yv = r.Retrieve(Of Video)(url)
Then it's possible to get the description with: yv.Description

Using ParseQueryString function to get values from QueryString

I needed to get values out of a string in a QueryString format, that is such as: data1=value1&data2=value2...
Someone suggested I used HttpUtility.ParseQueryString to get the value, I've searched and searched but I can't find any documentation or implementation of this and the Microsoft documentation for it doesn't explain how it works, can someone tell me hwat I'm doing wrong, my code is below;
Public Shared Sub ProcessString(ByVal Vstring As String)
Dim var As NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = var.QueryString("VNAME")
End Sub
MSDN has an example.
' Parse the query string variables into a NameValueCollection.
Dim qscoll As System.Collections.Specialized.NameValueCollection = HttpUtility.ParseQueryString(Vstring)
Dim vname As String = qscoll("VNAME")
A NameValueCollection represents a collection of associated String keys and String values that can be accessed either with the key or with the index.
I found the problem, I was referencing everything fine but I was doing it in a separate .VB dependency file, once I did it on the actual code behind of the aspx form that solved the problem and it all worked. So now I'm just passing the string from Codebehind as a specialised.NameValue collection in to the function.

Using PostedFile.InputStream twice

I'm trying to resize one image to 5 different sizes (and then upload them to amazonS3).
I'm using imageresizer.net
the problem seems to be that i cannot use the inputstream twice. it works the first time.
Dim SmallStream As Stream = New MemoryStream
Dim TinyStream As Stream = New MemoryStream
If FileUpload1.HasFile Then
**ImageResizer.ImageBuilder.Current.Build(FileUpload1.PostedFile.InputStream, SmallStream, New ResizeSettings("maxwidth=100&maxheight=100"))
ImageResizer.ImageBuilder.Current.Build(FileUpload1.PostedFile.InputStream, TinyStream, New ResizeSettings("maxwidth=100&maxheight=100"))**
AmazonUploadFile("SmallImages/" & FileUpload1.FileName, SmallStream)
AmazonUploadFile("TinyImages/" & FileUpload1.FileName, TinyStream)
End If
Public Shared Function GetS3Client() As AmazonS3
Dim appConfig As NameValueCollection = ConfigurationManager.AppSettings
Dim s3Client As AmazonS3 = AWSClientFactory.CreateAmazonS3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
Return s3Client
End Function
Public Sub AmazonUploadFile(S3Key As String, FileStream As Stream)
Dim request As New PutObjectRequest()
request.WithBucketName(BUCKET_NAME)
request.WithKey(S3Key).InputStream = FileStream
request.WithCannedACL(S3CannedACL.PublicRead)
GetS3Client.PutObject(request)
End Sub
The code breaks when i try to retrieve the FileUpload1.PostedFile.InputStream the second time.
I believe ImageResizer will accept Image objects to that method. So, you could read the InputStream into an Image object first (Image.FromStream()), then you can use that image object repeatedly.
[Disclaimer: I'm the author of http://imageresizing.net/]
Pass FileUpload1.PostedFile instead of FileUpload1.PostedFile.InputStream to the ImageResizer and it will automatically handle re-seeking the stream to the beginning after each read. (Make sure you're using 3.1.5 or later).
Alternatively, use the ImageJob class and set ResetSourceStream=true.

How to call a node from a xml file within asp.net web page

I am trying to use the value of <Directory> in my following piece of code:
Public Function GetFile() As String
Dim di As New DirectoryInfo(< Directory >)
Dim files As FileSystemInfo() = di.GetFileSystemInfos()
Dim newestFile = files.OrderByDescending(Function(f) f.CreationTime).First
Return newestFile.FullName
End Function
Is there any way i can call the value stored in the xml file in my code?
Andy's answer is good, but in VB it's even easier.
Dim xmlDoc As XDocument
Dim dir as String
xmlDoc = XDocument.Load("XMLFile1.xml")
dir = xmlDoc.<ServerList>.<Server>.<Directory>.First().Value;
Or even easier if the XML file will never have more than one <Directory> element that you care about:
dir = xmlDoc...<Directory>.First().Value;
To answer your comment on Andy's answer:
dir = (From server as XElement in xmlDoc...<Server>
Where server.<ServerName>.First().Value = requiredServer
Select server.<Directory>.First().Value)(0);
As you are clearly familiar with Linq, you can operate on the Xml using System.Xml.Linq.
Apologies, this is in c#.
var xDoc = XDocument.Load("XMLFile1.xml");
var dir = xDoc.Element("ServerList").Elements("Server").Elements("Directory").First().Value;
If you have the Xml stored in a string replace XDocument.Load with XDocument.Parse.
Obviously you'll have to defend against parse errors, file missing and schema inconsistencies in your production code.
You can use this http://support.microsoft.com/kb/301225

process webclients data with xquery

I retrieve the html from a cross domain web page using asp.net vb
Dim objWebClient As New WebClient()
objWebClient.UseDefaultCredentials = True
objWebClient.Headers.Add(HttpRequestHeader.UserAgent, "XPlorer")
'STEP 2: Call the DownloadedData method
Const strURL As String = "http://www.example.com"
Dim aRequestedHTML() As Byte
aRequestedHTML = objWebClient.DownloadData(strURL)
'STEP 3: Convert the Byte array into a String
Dim objUTF8 As New UTF8Encoding()
Dim strRequestedHTML As String
strRequestedHTML = objUTF8.GetString(aRequestedHTML)
Additionally I want show just a portion of it in a literal control. As an example I want to show just the table with the class "result".
How do I process this further in XML and XQuery in VB.NET? How do I declare strRequestedHTML as XML and how do I xquery in it?
thx in advance...
If your talking about a webpage (html) it would be better to parse it as HTML rather than XML.
Html Agility Pack is a good open source HTML parser for .NET
You could also use Html Agility Pack do download the web page aswell.
Something like:
Dim htmlWeb As HtmlAgilityPack.HtmlWeb = New HtmlWeb()
Dim htmlDocument As HtmlAgilityPack.HtmlDocument = htmlWeb.Load("http://www.google.com")
Dim htmlNode As HtmlAgilityPack.HtmlNode = htmlDocument.DocumentNode.SelectSingleNode("//table[#class='result']")
Response.Write(htmlNode)

Resources