I am trying to export data from MS SQL out in a json format in my asp.net web forms application. Problem is it exports with two double quotes around the values instead of just one double quote.
I want it to export like this:
{"bizunitid":"11111","prodlineid":"1","reasonforsurvey":"1"}
but it is coming out like this:
"{""bizunitid"":""11111"",""prodlineid"":""1"",""reasonforsurvey"":""2""}"
I have tried replacing the two double quotes but it always returns two double quotes.
Dim json As String = cmd.ExecuteScalar
streamWriter.Write(json.Replace("""""", Chr(34)))
Not sure if this is what you're looking for, but it's how I've done it when posting JSon to an API for a messaging app with VB.Net:
MessageTitle = MessageTitle.Replace("""", """""")
MessageBody = MessageBody.Replace("""", """""")
Dim strPostData As String = "{" &
"""notification"": {" &
"""sound"": ""default""," &
"""title"": """ & MessageTitle & """," &
"""body"": """ & MessageBody & """" &
"}, " &
"""data"": {" &
"""title"": """ & MessageTitle & """," &
"""body"": """ & MessageBody & """" &
"}," &
"""to"": """ & strRegIDs & """," &
"""priority"": 10 " &
"}"
hopefully that helps a bit
Related
I'm working on a rss feed reader and seems so work great.
The only thing that I seem not to get working is to read the image in the feed.
<itunes:image href="http://www.itunes.com/image.jpg"/>
Can anyone help?
This is a part of my code.
For Each objItem in objItems
On Error Resume Next
TheTitle = objItem.selectSingleNode("title").Text
TheLink = objItem.selectSingleNode("image").Text
Theimg = objItem.SelectSingleNode("itunes").Attributes(":image").InnerText
Response.Write "<div class='article'>" &_
"<a href=" & TheLink & ">" & _
"<span>" & Theimg & TheTitle & "</span>" & _
"</a>" & _
"</div>"
Next
Your image address needs to go inside an image tag
Response.Write "<div class=""article"">" &_
"<a href=""" & TheLink & """>" & _
"<img src=""" & Theimg & """ alt=""" & TheTitle & """ />" & _
"</a>" & _
"</div>"
If you're wondering why all the double quotes, see this question
Adding quotes to a string in VBScript
As an aside, if you understand XSL then I find that the best way to handle RSS feeds in Classic ASP is to do a server side XSLT transformation. The ASP looks like this
set xml = Server.CreateObject("Msxml2.DomDocument.6.0")
xml.setProperty "ServerHTTPRequest", true
xml.async = false
xml.validateOnParse = false
xml.load("http://your-rss-feed")
set xsl = Server.CreateObject("Msxml2.DomDocument.6.0")
xsl.load(Server.Mappath("yourxslfile.xsl"))
Response.Write(xml.transformNode(xsl))
set xsl = nothing
set xml = nothing
How do I get my Asp.net webapi to return the correct response for a pdf form submit?
To keep the response inside of the pdf application you must return an FDF formatted file.
The key to get this to work is that you cannot just return a string. You must first encode it to a memory stream and the header must be set to application/vnd.fdf.
Here is the example code:
Public Function PostValue(<FromBody()> ByVal value As MyPDFFieldsObject) As HttpResponseMessage
Dim fdfmessage As String = "%FDF-1.2" & vbCrLf & _
"1 0 obj <<" & vbCrLf & _
"/FDF <<" & vbCrLf & _
"/Status (Submitted Successfully!)" & vbCrLf & _
">>" & vbCrLf & _
">>" & vbCrLf & _
"endobj" & vbCrLf & _
"trailer" & vbCrLf & _
"<</Root 1 0 R>>" & vbCrLf & _
"%%EOF"
Dim result As HttpResponseMessage = New HttpResponseMessage(HttpStatusCode.OK)
Dim stream As New MemoryStream(Encoding.UTF8.GetBytes(fdfmessage))
stream.Position = 0
result.Content = New StreamContent(stream)
result.Content.Headers.ContentType = New MediaTypeHeaderValue("application/vnd.fdf")
Return result
End Function
I´m not familiar with JSON data parsing. So far, this is what I´ve come up to through web research:
data to parse:
https://api.twitch.tv/kraken/streams/
I´m trying to use the JSON.NET/VB.NET framework to do so:
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq
'(inside a function)
Dim json As JObject = JObject.Parse("https://api.twitch.tv/kraken/streams/")
strResult As String = json.SelectToken("streams").SelectToken("game")
It´s returning me an error message, and I´m sure I don´t have the structure right. How could I make this work? And afterwards, I´d like to loop through the results of the returning array.
Thanks,
This should get you going (just a conceptual example - console, not asp.net):
Dim json As JObject = _
JObject.Parse(New WebClient().DownloadString("https://api.twitch.tv/kraken/streams/"))
If json IsNot Nothing AndAlso json.HasValues Then
If json.SelectTokens("streams") IsNot Nothing _
AndAlso json.SelectTokens("streams").Children().Any() Then
Dim games() As JToken = json.SelectTokens("streams").Children().ToArray()
For Each child As JToken In games
Console.WriteLine("game title: {0} game id: {1} for mature audience? {2}", _
child.Item("game"), child.Item("_id"), child.Item("channel").Item("mature"))
Console.WriteLine()
Next
Console.ReadLine()
End If
End If
Hth....
This is the code simplified, with the help of EdSF, for the newbies in json (like myself):
Dim apiURL As String = "https://api.twitch.tv/kraken/streams?limit=10&offset=0"
Dim json As JObject = JObject.Parse(New WebClient().DownloadString(apiURL))
If json IsNot Nothing AndAlso json.HasValues Then
If json.SelectTokens("streams") IsNot Nothing AndAlso json.SelectTokens("streams").Children().Any() Then
Dim games() As JToken = json.SelectTokens("streams").Children().ToArray()
For Each child As JToken In games
'Console.WriteLine("game title: {0} game id: {1} for mature audience? {2}", child.Item("game"), child.Item("_id"), child.Item("channel").Item("mature"))
'Console.WriteLine()
lblMensagemSucesso.Text &= "_id=" & child.Item("_id").ToString() & "<br>"
lblMensagemSucesso.Text &= "game=" & child.Item("game").ToString() & "<br>"
lblMensagemSucesso.Text &= "viewers=" & child.Item("viewers").ToString() & "<br>"
lblMensagemSucesso.Text &= "preview=" & child.Item("preview").ToString() & "<br>"
lblMensagemSucesso.Text &= "preview.small=" & child.Item("preview").Item("small").ToString() & "<br>"
lblMensagemSucesso.Text &= "<img src='" & child.Item("preview").Item("small").ToString() & "'/><br>"
lblMensagemSucesso.Text &= "_links.self=" & child.Item("_links").Item("self").ToString() & "<br>"
lblMensagemSucesso.Text &= "channel.status=" & child.Item("channel").Item("status").ToString() & "<br>"
lblMensagemSucesso.Text &= "channel.logo=" & child.Item("channel").Item("logo").ToString() & "<br>"
lblMensagemSucesso.Text &= "<img src='" & child.Item("channel").Item("logo").ToString() & "'/><br>"
lblMensagemSucesso.Text &= "channel.video_banner=" & child.Item("channel").Item("video_banner").ToString() & "<br>"
lblMensagemSucesso.Text &= "channel.url=" & child.Item("channel").Item("url").ToString() & "<br>"
lblMensagemSucesso.Text &= "channel.views=" & child.Item("channel").Item("followers").ToString() & "<br>"
lblMensagemSucesso.Text &= "channel._links.self=" & child.Item("channel").Item("_links").Item("self").ToString() & "<br>"
lblMensagemSucesso.Text &= "channel._links.teams=" & child.Item("channel").Item("_links").Item("teams").ToString() & "<br>"
lblMensagemSucesso.Text &= "<br>"
Next
'Console.ReadLine()
End If
End If
I tried everything, but nothing seems to work!
How the do I put a breakline?!
Dim textMsg as String
textMsg = Body.text & Environment.Newline & _ q1.text & Environment.Newline & _ q2.text & Environment.Newline & _ q3.text & Environment.Newline & _ q4.text '
please help
(with corrent code I get an error cuz of the & Environment.Newline & _ ")
Since you tagged this asp.net, I'll guess that this newline should appear in a web page. In that case, you need to remember that you are creating html rather than plain text, and html ignores all whitespace... including newlines. If you view the source for your page, you'll likely see that the new lines do make it to your html output, but they are ignored, and that's what is supposed to happen. If you want to show a new line in html, use a <br> element:
textMsg = Body.text & "<br>" & _ q1.text & "<br>" & _ q2.text & "<br>" & _ q3.text & "<br>" & _ q4.text
The code above will place the text on several lines. It's interesting that if you view the source now, you'll see that everything is all on the same line, even though it uses several lines for display.
You should add a br:
textMsg = Body.text & "<BR/>" & _ q1.text & "<BR/>" & _ q2.text & "<BR/>" & _ q3.text & "<BR/>" & _ q4.text
Or you can try:
Str & VBNewLine OR Str & VBCrLf
Or set the email message to html. The the will work.
thats the right one:
& (vbCrLf) &
Try this:
dim textMsg as String
textMsg = Body.text & vbNewLine
I preffer .Net Style:
& Environment.NewLine &
It's Is exactly the same that
& (vbCrLf) &
For a web application, I am creating a SMS module that can send an SMS from the application. My SMS provider has an API that I can call over HTTP.
The API is called via an XmlTextReader who just reads the XML response from the API.
Now my problem is: When I send the SMS from a web page (basically just doing an HTTP request) it takes more than a minute before I receive the SMS.
But when I run the exact same code from a Windows console application, my SMS arrives in less then 5 seconds.
I have done multiple tests with this, and it's not really my SMS provider who is slow.
Somehow, the HTTP request gets delayed from within the ASP.NET engine, and it does not delay directly from an console application. Is there a solution?
This is the way I'm calling the HTTP API:
Dim strPostString As String = Convert.ToString(muriPostUrl) & mstrPostPath
If mblnUseSecureConnection Then
strPostString = Convert.ToString(muriSecurePostUrl) & mstrPostPath
End If
Dim strDataString As String = "username=" & mstrUsername
strDataString += "&" & "password=" & mstrPassword
strDataString += "&" & "originator=" & mstrOriginator
strDataString += "&" & "recipients=" & mstrRecipients
strDataString += "&" & "gateway=" & mstrGateway
strDataString += "&" & "reference=" & mstrReference
strDataString += "&" & "message=" & mstrMessage
If mstrType <> String.Empty Then
strDataString += "&" & "type=" & mstrType
End If
If mstrUDH <> String.Empty Then
strDataString += "&" & "udh=" & mstrUDH
End If
If Not mdtDeliveryDate = Nothing Then
Dim objDeliveryDate As New StringBuilder()
objDeliveryDate.Append(mdtDeliveryDate.Year)
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Month.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Day.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Hour.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Minute.ToString(), 2))
objDeliveryDate.Append(Prefix(mdtDeliveryDate.Second.ToString(), 2))
strDataString += "&" & "deliverydate=" & Convert.ToString(objDeliveryDate)
End If
Dim strReturnValue As String = ""
Dim xmlReader As New XmlTextReader(String.Format("{0}?{1}", strPostString, strDataString))
While xmlReader.Read()
If xmlReader.NodeType = XmlNodeType.Element Then
Select Case xmlReader.LocalName
Case "recipients"
If True Then
mintSuccessCount = Integer.Parse(xmlReader.ReadString())
strReturnValue += "recipients : " & mintSuccessCount.ToString() & vbCr & vbLf
Exit Select
End If
Case "success"
If True Then
mblnSuccess = Boolean.Parse(xmlReader.ReadString())
strReturnValue += "success : " & mblnSuccess.ToString() & vbCr & vbLf
Exit Select
End If
Case "resultcode"
If True Then
mintResultCode = Integer.Parse(xmlReader.ReadString())
strReturnValue += "resultcode : " & mintResultCode.ToString() & vbCr & vbLf
Exit Select
End If
Case "resultmessage"
If True Then
mstrResultMessage = xmlReader.ReadString()
strReturnValue += "resultmessage : " & mstrResultMessage & vbCr & vbLf
Exit Select
End If
End Select
End If
End While
Also, when performing an HTTP request from ASP.NET, it does not appear in Fiddler, while the actual HTTP request happens. How can I track the HTTP fastback from within the ASP.NET engine?
I still don't know what the problem is, but I worked around it by doing the postback via an HttpWebRequest directly. I think the problem was somewhere in the while loop.