Get value from JArray item with has inconsistent values - asp.net

I'm reading a JSON file from an external partner which is not totally consistent (and they are not changing it anytime soon).
I want to check the value of the field bathroom and store that in an integer. So here's a mapping of the potential values there are and what I would like to get:
"" = 0
= 0 (here no value is present)
2 = 2
"2" = 2
But whatever I try (see below) I get the error:
Input string was not in a correct format.
Dim json as string = "[{""bathrooms"": """"}, {""bathrooms"": }, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim iBathrooms As Integer
Dim jsonArray As Newtonsoft.Json.Linq.JArray = JArray.Parse(json)
For Each item In jsonArray
iBathrooms= If(item.Value(Of Integer?)("bathrooms"), 0)
iBathrooms = If(CType(item("bathrooms"), Integer?), 0)
Int32.TryParse(item("bathrooms").Value(Of Integer).ToString, iBathrooms)
Next
I already checked here: Get value from JToken that may not exist (best practices)

If the problem with the JSON is consistently that it is missing the value, you could insert, say, an empty string:
Dim json As String = "[{""bathrooms"": """"}, {""bathrooms"": }, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim re = New Text.RegularExpressions.Regex(":\s*}")
Dim json2 = re.Replace(json, ": """"}")
Console.WriteLine(json2)
Outputs:
[{"bathrooms": ""}, {"bathrooms": ""}, {"bathrooms": 2},{"bathrooms": "1"}]
which is valid JSON.
Then you could check if the value can be parsed as an integer:
Dim json As String = "[{""bathrooms"": """"}, {""bathrooms"": """"}, {""bathrooms"": 2},{""bathrooms"": ""1""}]"
Dim re = New Text.RegularExpressions.Regex(":\s*}")
json = re.Replace(json, ": """"}")
Dim nBathrooms As Integer
Dim jsonArray As Newtonsoft.Json.Linq.JArray = JArray.Parse(json)
For Each item In jsonArray
Dim q = item("bathrooms")
If q IsNot Nothing AndAlso Integer.TryParse(q.Value(Of Object).ToString(), nBathrooms) Then
Console.WriteLine(nBathrooms)
Else
Console.WriteLine("Not specified.")
End If
Next

Related

Serializing a Dataset in vb.net using Newtonsoft

All
I have a dataset with 11 Columns and 5 rows which I need to form into a json string.
The DataSet is created thus:-
For liCounter = 1 To liTotalCounter
If IsDBNull(dt.Rows(liCounter).Item(0)) = False Then
Dim dr As DataRow = PlayerTable.NewRow()
dr("id") = CType(dt.Rows(liCounter).Item(0), Integer)
dr("teamid") = CType(dt.Rows(liCounter).Item(1), Integer)
dr("Team_Name") = CType(dt.Rows(liCounter).Item(2), String)
dr("pno") = CType(dt.Rows(liCounter).Item(3), String)
dr("Player_Name") = CType(dt.Rows(liCounter).Item(4), String)
dr("Goals") = CType(dt.Rows(liCounter).Item(6), Integer)
dr("Games") = CType(dt.Rows(liCounter).Item(5), Integer)
dr("Assists") = CType(dt.Rows(liCounter).Item(7), Integer)
dr("Points") = CType(dt.Rows(liCounter).Item(8), Integer)
dr("Pens") = CType(dt.Rows(liCounter).Item(9), Integer)
dr("Misc") = CType(dt.Rows(liCounter).Item(10), Integer)
PlayerTable.Rows.Add(dr)
End If
Next
ds.AcceptChanges()
JsonString = JsonConvert.SerializeObject(dt)
Now an example of the returned Json String is :-
"[{""id"":3,""teamid"":1,""name"":""Team 1"",""pno"":3,""name1"":""Player 1 "",""games"":2,""goals"":3,""assists"":4,""points"":5,""penalties"":8,""misc"":7},{""id"":4,""teamid"":1,""name"":""Bandit"",""pno"":7,""name1"":""Player 2"",""games"":0,""goals"":0,""assists"":0,""points"":0,""penalties"":0,""misc"":0},{""id"":5,""teamid"":1,""name"":""Bandit"",""pno"":8,""name1"":""Player 3"",""games"":0,""goals"":0,""assists"":0,""points"":0,""penalties"":0,""misc"":0},{""id"":6,""teamid"":1,""name"":""Bandit"",""pno"":9,""name1"":""Player 4 "",""games"":0,""goals"":0,""assists"":0,""points"":0,""penalties"":0,""misc"":0},{""id"":7,""teamid"":1,""name"":""Bandit"",""pno"":11,""name1"":""Player 5 "",""games"":0,""goals"":0,""assists"":0,""points"":0,""penalties"":0,""misc"":0}]"
When I go to check that the json string is valid using json checker, the error indicates that there is a problem with the string e.g.
Parse error on line 1:
"[{""id"":3,""teamid"":1
Expecting 'EOF', '}', ':', ',', ']', got 'STRING'
I have tried other forms of serializing a dataset or datatable, but the same error is produced, so I have to be doing something wrong somewhere...
Any Advice would be appreciated.
-Colin

Length cannot be less than zero. Parameter name: length when trying to split token

hello i have this line of code am trying to split the tokens gotten from the http readerGetResponse stream,
whle breaking the code it shows this error "Length cannot be less than zero. Parameter name: length when trying to split token"
Dim tokens As New Dictionary(Of String, String)()
Dim url As String = String.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}", app_id, "http://localhost:28782/webform2.aspx", scope, Me.Request("code").ToString(), app_secret)
Dim request As HttpWebRequest = TryCast(WebRequest.Create(url), HttpWebRequest)
Using response As HttpWebResponse = TryCast(Request.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(response.GetResponseStream())
Dim vals As String = reader.ReadToEnd()
For Each token As String In vals.Split("&"c)
**tokens.Add(token.Substring(0, token.IndexOf("=")), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1))**
Next
End Using
Dim access_token As String = tokens("access_token")
Context.Session("AccessToken") = access_token
Response.Redirect("http://localhost:28782/allproducts.aspx")
where i highlighted is where the error is. Thank you
To check that the = is present & to handle the length, such that it handles it if its in the first position as mentioned in the comments of the other answer, try something like:
For Each token As String In vals.Split("&"c)
dim i as integer = token.IndexOf("=")
if (i <> -1) Then
dim newLength as integer = token.length - i
if newLength > 0 then
newLength -= 1
end if
tokens.Add(token.Substring(0, i), token.Substring(i + 1, newLength))**
end if
Next

Index was out of range. Must be non-negative and less than the size of the collection - chart databind

I'm trying to build a datatable and then bind it to a gridview and chart object. The gridview appears fine but when I build the x,y array and bind them to the chart object I get the error above.
I've read many forums to understand that the index is looking at a field that is out of range but I've queried in the immediate window all the fields and the are clearly values there. There error occurs as soon as I bind it to the chart object and I don't know why the chart object doesn't just display properly.
This is my aspx codebehind:
Dim dt As DataTable = New DataTable()
dt.Columns.Add("CompanyName")
dt.Columns.Add("Amount")
dt.Columns.Add("Proportion")
Using DBContext As New fundmatrixEntities
Dim queryUnits = (From c In DBContext.Units Where c.SavingApplicationId = savAppId Select New With {.LoanAppId = c.LoanApplicationId}).Distinct().ToList()
Dim companyName As String = ""
Dim savingsAmount As String = ""
Dim totalProportion As String = ""
Dim totalSavingsAmount As String = ""
For Each loan In queryUnits
If Not loan.LoanAppId Is Nothing Then
companyName = classSQLDirect.ExecQuery("SELECT companyname FROM companyprofile where loanapplicationid='" & loan.LoanAppId.ToString & "'")
savingsAmount = classSQLDirect.ExecQuery("SELECT SUM(Amount) from unit where SavingApplicationId='" & savAppId.ToString & "' and LoanApplicationId='" & loan.LoanAppId.ToString & "'")
totalSavingsAmount = classSQLDirect.ExecQuery("SELECT amount FROM SavingApplication WHERE SavingApplicationId='" & savAppId.ToString & "'")
totalProportion = ((savingsAmount / totalSavingsAmount) * 100) & "%"
dt.Rows.Add(companyName, savingsAmount, totalProportion)
End If
Next
gvwBusinesses.DataSource = dt
gvwBusinesses.DataBind()
End Using
Dim x As String() = New String(dt.Rows.Count - 1) {}
Dim y As String() = New String(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(0).ToString()
y(i) = dt.Rows(i)(2).ToString()
Next
chart1.Series(0).Points.DataBindXY(x, y)
chart1.Series(0).ChartType = SeriesChartType.Pie
The code errors on the line
chart1.Series(0).Points.DataBindXY(x, y)

Cannot get the last row of data

In my ASP.NET application, i need to read the CSV file and insert into sql server.
and it was strange that it treat the 1st row (column name) as LineNumber=2.
but i found that my code cannot read the last row of the CSV file.
Dim CSV_content As String = ""
Dim CSVFilePathName As String = Server.MapPath("~/XXX/" & filename)
If File.Exists(CSVFilePathName) = True Then
'Response.Write("exists")
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(CSVFilePathName)
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {","}
afile.HasFieldsEnclosedInQuotes = True
Dim LastName As String = ""
Dim FirstName As String = ""
Dim DisplayName As String = ""
Dim EmailName As String = ""
Dim dc As New dcHRISDataContext
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
'insert into tmp db
If afile.LineNumber > 2 Then
Dim newRecord1 As New XXX
dc.XXX.InsertOnSubmit(newRecord1)
newRecord1.LastName = CurrentRecord(0).Trim
newRecord1.FirstName = CurrentRecord(1).Trim
newRecord1.DisplayName = CurrentRecord(1).Trim
newRecord1.DirEmail = CurrentRecord(3).Trim
newRecord1.GetFileDate = DateTime.Now
newRecord1.GetFileName = filename
dc.SubmitChanges()
End If
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
End If
Wow, this is the dumbest issue that I have seen.
Anyhow, Apparently the last row in the TextFieldParser is -1, and not LastRowWithValuesIndex + 1. So what happens is this.
You read the data of the last line (this is fine)
The reader skips to the next line to prepare the next line to read (this is fine)
You get the afile.LineNumber, now set to the next line. Which is -1
at this point. (this is dumb although understandable, not your fault)
Your if statement wont let you in because hey you are on line -1.
Loop ends, skipping last row in the CSV.
All you have to do is to read the line number of the row before reading the data:
Dim i As Integer = afile.LineNumber
CurrentRecord = afile.ReadFields
If i > 2 Then
etc

Array list error second array replace the first array

I have a problem.
Dim Maxis As String
'Dim MaxisExtra As String
Dim b As New ArrayList
Dim WS As New WebService1.Service1
Dim cnt As String
Dim MRWS As New MobileReload_WS.MobileReload_WS
cnt = WS.StockCountTelco(1, Session("Maxis"))
If CInt(cnt) >= CInt(DropDownList1.SelectedItem.Text) Then
Dim sLock As String
sLock = MRWS.LockAStock(1, 1, "Online", Session("Maxis"), DropDownList1.SelectedItem.Text)
Session("sLock") = sLock
If sLock = "" Then
PopupMsgBox("Unable to allocate Stock")
Else
Maxis = "Maxis" & ";" & Session("Maxis") & ";" & DropDownList1.SelectedItem.Text & ";" & Session("Cost")
'If MaxisExtra = "" Then
' b.Add(Maxis)
' Elseif
' MaxisExtra = MaxisExtra + Maxis
' b.Add(MaxisExtra)
'End If
End If
Else
PopupMsgBox("Not enough stock")
End If
b.Add(Maxis)
Session("Transaction") = b
End Sub
The first time i enter the string into the arraylist it is okay. But when the user press the button add again the second time, it replace the first string. Can anyone help me how to save the string into the second slot based on my coding?
If you're talking about the b ArrayList, then you're creating a new one each time and storing the new ArrayList in Session("Transaction")
Maybe you mean something like this instead...
Dim b as ArrayList = Session("Transaction")
If b Is Nothing Then
b = new ArrayList
End If
...
Session("Transaction") = b
Although it's difficult to say exactly, because your code is very messy and not clear
You put the array list in a session variable, but you never read it back. You create a new array list each time, so it will always be empty and replace the previous one.
Get the array list from the session variable if there is one:
Dim b As ArrayList = Session("Transaction")
If b Is Nothing Then b = New ArrayList

Resources