asp.net JSON escaping output -- disable? - asp.net

Sub Application_Start()
' ... do stuff
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear()
End Sub
Then inside my controller I have:
Dim serializer As New JavaScriptSerializer()
Dim json As String = serializer.Serialize(Quotes.ToArray).Replace("\""", "")
Return json
When I set a break point on final statement I can clearly see the results are just as I expected but by the time I see it in Chrome JSON viewer it has been escaped with double quotes.
When I comment the configuration line provided above SO XML is the return type but still use JSON converter on the array the data packaged in the XML tags are as I would expect.
This is what I need, not the escaped gibberish provided.

Related

Convert JSon to dynamic object in VB.Net

I am using VB.Net and calling salesforce API. It returns very ugly JSON which I am not able to deserialize. I have a following code using JSON.Net
Dim objDescription As Object = JsonConvert.DeserializeObject(Of Object)(result)
objDescription contains many properties, one on=f them in fields. But when I write something like objDescription.fields it gives me error.
objDescription.fields Public member 'fields' on type 'JObject' not found. Object
I am not very sure but I think it C# allow to convert any JSON to dynamic object. How can I use it in VB.Net?
You can turn Option Strict Off and use ExpandoObject which is recognized by JSON.NET. In order to leverage the dynamic features you can use a variable of type object.
Option Strict Off
Sub Main
Dim jsonData As Object = JsonConvert.DeserializeObject(Of System.Dynamic.ExpandoObject)("{""Id"":25}")
Dim test As Integer = jsonData.Id
Console.WriteLine(test)
End Sub
If you would like to use JObject because you need some of its features, you can index the JObject instead.
Sub Main
Dim jsonData As Object = JsonConvert.DeserializeObject(Of Object)("{""Id"":25}")
Dim test = jsonData("Id")
Console.WriteLine(test)
End Sub

vb.net Document Generation, Handling Greater Than & Less Than Symbols in Word

We are using TinyMCE editor to store Rich Text in a MS SQL database.
When using "<" & ">" symbols, TinyMCE converts these into the HTML escaped characters &lt ; and &gt ; For Example: <p><This is some test information then sometime I use this></p>
We are trying to export these symbols in a Microsoft Word document using document automation however the symbols do not appear in the document.
Function PreFormatHTML(ByVal html As String) As String
If String.IsNullOrEmpty(html) Then Return html
html = WebUtility.HtmlDecode(html)
Return html
End Function
Dim SumRng As Word.Range = objWordDoc.Bookmarks.Item("bSummary").Range
SumRng.Text = PreFormatHTML(GeneralComponent.CheckReadNull(SqlReader.Item("Summary")))
This also doesn't work. I'm using Word 2013 and TinyMCE text editor.
Any suggestions?
Without seeing the full html I can only make an assumption however what I would suggest is use WebUtility.HtmlDecode:
Converts a string that has been HTML-encoded for HTTP transmission into a decoded string.
This is how you would use it:
html = WebUtility.HtmlDecode(html)
With Word this is how I have tested:
Dim s As String = "<this is some text and I'm wondering what to do>"
Dim wrd As New Word.Application
Dim doc As Word.Document = wrd.Documents.Add()
Dim para As Word.Paragraph = doc.Content.Paragraphs.Add()
para.Range.Text = WebUtility.HtmlDecode(s)
This is what the text looks like in my Document:
Edited as per OP's comment:
Dim s As String = "<p><This is some test information then sometime I use this></p>"
Dim wrd As New Word.Application
Dim doc As Word.Document = wrd.Documents.Add()
Dim para As Word.Paragraph = doc.Content.Paragraphs.Add()
para.Range.Text = WebUtility.HtmlDecode(s)
This code produces the following output in my Document:
Edited as per OP's update to question:
I have created a document called test.docx and added a bookmark called bSummary. I have done this in an attempt to replicate the OP's code.
Dim s As String = "<p><This is some test information then sometime I use this></p>"
Dim wrd As New Word.Application
Dim doc As Word.Document = wrd.Documents.Open("C:\test.docx")
Dim SumRng As Word.Range = doc.Bookmarks.Item("bSummary").Range
SumRng.Text = PreFormatHTML(s)
The output is the same as above. This leads me to think that whatever is passed into PreFormatHTML is not what you think it is. Is GeneralComponent.CheckReadNull(SqlReader.Item("Summary"))) passing into PreFormatHTML the following string; <p><This is some test information then sometime I use this></p>?
OP has confirmed the HTML is returned from PrrFormatHTML as expected. The issues seems to be linked to the Document. It may be to do with the with version of Word Interop that the OP is using. I'm using Microsoft Word 16.0 Object Library whilst the OP is using Microsoft Word 15.0 Object Library.

simply dump write xml to screen

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()

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.

NullReference on a value that is not null

I have a function that gets a string passed to it. When testing the function, I'm getting a null reference exception on the string parameter that gets passed to it, even though the string is not null, I don't understand why I'm getting this error. I have a screen shot below
I used a dummy value to verify both the string parameter in the SelectSingleNode function and the newValue string parameter being passed to my function and they both contain values, so I don't understand why it's throwing a null reference exception. Just for clarity, the purpose of the function is to write values back to the nodes of an XML file.
UPDATE
Sorry for not posting code
Private Sub setValue(ByVal nodeToMod As String, ByVal newValue As String)
''Test writing to xml config file
Dim dummy As String = "Config/" & nodeToMod
Dim xmlDoc As New XmlDocument
Using fs As FileStream = New FileStream(HttpContext.Current.Server.MapPath("~/XML_Config/Config.xml"), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
xmlDoc.Load(fs)
Dim foo As XmlNode = xmlDoc.SelectSingleNode(dummy)
Console.WriteLine(foo.InnerXml)
fs.Seek(0, SeekOrigin.Begin)
fs.SetLength(0)
xmlDoc.Save(fs)
End Using
End Sub
And here is the XML file I'm working with
<?xml version="1.0" encoding="utf-8"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Username>john.doe#email.com</Username>
<Password>Password1</Password>
<ProductType>MyProduct</ProductType>
<DirectoryEntryPath>LDAP://myDomain</DirectoryEntryPath>
<SMTPDefaultOnly>True</SMTPDefaultOnly>
<Logo>myLogo.gif</Logo>
</Config>
Yes, the SlectSingleNode function is not returning a value. I just started working with XPath, this seemed to have worked when I was using last week. I'm not sure why it has stopped working now.
UPDATE2:
Got it, stupid mistake. I had nodeToMod being passed as "UserName" instead of "Username" in the Set method
Set(ByVal value As String)
setValue("UserName", value.ToString)
_userName = value
End Set
The null reference that is being complained about is the result of the call to SelectSingleNode. That is, when the xpath formed by concatenating /Config/ and the contents of nodeToMod is evaluated against the document, no node matches. So you get null, and attempting to set the InnerText of null gives the exception.
We would really need to see nodeToMod and the xml file itself to help further. Also, please post code rather than screenshots!
Ensure that the FileStream object you're creating doesn't come out null. Maybe it can't find the config.xml file?
It's likely that the result of SelectSingleNode is null.
Change that line to two lines, and it will be easier to see the problem in the debugger:
Dim node = xmlDoc.SelectSingleNode(dummy)
node.InnerText = newValue

Resources