"System.NullReferenceException" while filling dictionary with keys from an array - arrays

I have a problem in my code. here is the problematic snippet. The reading of the line does work, but at the point where he should fill the zeilendict with the keys and the values, he throws an "System.NullReferenceException" and I dont know why.
Did I do something wrong in the loop, or is the dictionary not right iniziated? or is arr1 empty?
Module Module1
Public zeilendict As Dictionary(Of String, Integer)
Public insertdict As Dictionary(Of String, String)
Public Sub einlesen()
Form1.ID = 0
Form1.OpenFileDialog1.ShowDialog()
Form1.path = Form1.OpenFileDialog1.FileName
Form1.OpenFileDialog1.Dispose()
Dim fs As FileStream = New FileStream(Form1.path, FileMode.Open, FileAccess.Read)
Dim sr As StreamReader = New StreamReader(fs)
Dim ersteZeile = sr.ReadLine()
Form1.arr1 = ersteZeile.Split(New Char() {";"c})
sr.Close()
fs.Close()
Dim i As Integer
For i = 0 To Form1.arr1.Length - 1
Form1.DataGridView1.Rows.Add(Form1.arr1(i))
Next
Dim i1 As Integer
For i1 = 0 To Form1.arr1.Length - 1
zeilendict.Add(Form1.arr1(i1), 0)
Next

It seems you have not initiated your dictionary. There for adding items will give a NullRefException
Try adding:
Public zeilendict As Dictionary(Of String, Integer) = new Dictionary(Of String, Integer)()
or set this as first line in your method:
zeilendict = new Dictionary(Of String, Integer)()
Also do this for the other Dictionary

Add the keyword "New" to your declartion to initialize your dictionary:
Public zeilendict As New Dictionary(Of String, Integer)
Otherwise it will only be declared but contain nothing, therefore the Exception when you try to add something.
More information: http://msdn.microsoft.com/en-us/library/7zc73115%28v=vs.90%29.aspx

Related

What is the type of JSON Array in JSON.Net?

I have following json data:
{
"cgFinishing": {
"a3colorfn": [{
"type": "Cacah",
"kode": "CCH"
},
{
"type": "Cutting",
"kode": "CUT"
}
]
}
}
And my JSON Class:
Public Class A3colorfn
Public Property type As String
Public Property kode As String
End Class
Public Class CgFinishing
Public Property a3colorfn As A3colorfn()
End Class
Public Class CGSave
Public Property cgFinishing As CgFinishing
End Class
I want to write a method in VB.NET that pull values from this JSON array using JSON.NET. This code works for me:
Public Sub fillCBfromJson(ByVal cb As ComboBox, json As Object, Optional ByVal value As String = "", Optional display As String = "")
....
End Sub
But I'd like to replace json As Object with something that are more specific, because I'd like to retrieve the count of items in the array (something like Count or GetLength, I cannot expose those property with Object type)
For your reference this code works for me...
Dim count As Integer = jsonObj.cgFinishing.a3colorfn.GetLength(0)
But I have no idea to turn it as a method.
Any help is appreciated.
More code listing:
Private Sub PublishDigital_Load(sender As Object, e As System.EventArgs) Handles MyBase.Load
jsonPath = Application.StartupPath + "\Addons\CG_Tools\cgSave.json"
jsonObj = JsonConvert.DeserializeObject(Of CGSave)(File.ReadAllText(jsonPath))
initfinishingA3()
End Sub
Public Sub initfinishingA3() 'I want to make this as a method, so I'll only need to input the Array object as argument.
Dim cbdata As Object = jsonObj.cgFinishing.a3colorfn '<- I want to put this line as argument instead
Dim count As Integer = jsonObj.cgFinishing.a3colorfn.GetLength(0)
Dim myCb As New List(Of CheckBox)
For Each cur In cbdata
Dim cb = New CheckBox()
tb_finishinga3.Controls.Add(cb)
Dim txt As JObject = JsonConvert.DeserializeObject(Of JObject)(JsonConvert.SerializeObject(cur))
...
cb.Text = txt("type")
...
Next
End Sub
Following method I wrote does not work..
Public Sub fillTabwithCB(ByVal cbdata As JArray, XOffset As Integer, YOffset As Integer, maxRow As Integer)
Dim count As Integer = cbdata.Count
Dim loopIndex As Integer
Dim i As Integer = 0
Dim myCb As New List(Of CheckBox)
For Each cur In cbdata
Dim cb = New CheckBox()
tb_finishinga3.Controls.Add(cb)
Dim txt As JObject = JsonConvert.DeserializeObject(Of JObject)(JsonConvert.SerializeObject(cur))
.........
cb.Text = txt("type")
..........
Next
End Sub
Then I tried it in this line...
fillTabwithCB(jsonObj.cgFinishing.a3colorfn, 7, 7, 5)
It generates following error:
Value of type '1-dimensional array of
CG_FileManagement.A3colorfn' cannot be converted to
'Newtonsoft.Json.Linq.JArray'.

Loading file into array using streamreader

I'm trying to get a file and iterate through it using StreamReader and load each line into an array. I know the file is coming in correctly and it is a text file of data coming in lines.
Dim req As WebRequest = WebRequest.Create("http://www.blahahahaha.com/data/myfile.csv")
Dim res As WebResponse = req.GetResponse()
Dim stream As Stream = res.GetResponseStream()
Dim lines2 As String()
Using r As StreamReader = New StreamReader(stream, Encoding.ASCII)
Dim line As String
line = r.ReadLine
Do While (Not line Is Nothing)
lines2(lineCount2) = r.ReadLine
lineCount2 += 1
Loop
End Using
But the resulting array is empty. What am I doing wrong and how do I fix it?
This line:
Dim lines2 As String()
Just declares that lines2 will be a string array. The array itself is not intialized:
Dim lines2(9) As String ' THIS one has elements
But since you likely do not know how many lines there will be, use a List:
Dim Lines As New List(Of String)
Using r As StreamReader = New StreamReader(Stream, Encoding.ASCII)
Dim line As String
line = r.ReadLine
Do Until String.IsNullOrEmpty(line)
Lines.Add(line)
line = r.ReadLine
Loop
End Using
If the calling code really needs an array:
Return Lines.ToArray()
This will return 6 lines as a string array, first line is column names
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim csvAddress As String =
"https://download.microsoft.com/download/4/C/8/4C830C0C-101F-4BF2-8FCB-32D9A8BA906A/Import_User_Sample_en.csv"
Dim Lines As String() = GetCsvData(csvAddress)
For Each line As String In Lines
Console.WriteLine(line)
Next
End Sub
Public Function GetCsvData(ByVal csvAddress As String) As String()
Dim request As WebRequest = WebRequest.Create(csvAddress)
request.Credentials = CredentialCache.DefaultCredentials
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
Dim LineList As New List(Of String)
Using r As StreamReader = New StreamReader(dataStream, Encoding.ASCII)
Dim currentLine As String = r.ReadLine
Do While (Not String.IsNullOrWhiteSpace(currentLine))
LineList.Add(currentLine)
currentLine = r.ReadLine
Loop
End Using
Return LineList.ToArray
End Function

String array replace not updating original string

I'm trying to replace all double quotes in a file but when I try to update the string array I just get the original line again instead of the cleaned string. (The Boolean's in the ReplaceQuotes function are just for testing and they come back true when there's a " in the line). If I look at the cleanLine string, the quotes have been removed, but when I return the fileContent array, it looks just like the original with the quotes.
Private Sub CleanFile(currentFileInfo As FileInfo)
Dim fullName As String = currentFileInfo.FullName
Dim fileContent As String() = GetFileContent(currentFileInfo.FullName)
Dim cleanFileContent As String() = ReplaceQuotes(fileContent)
End Sub
Private Function GetFileContent(fileName As String) As String()
Return System.IO.File.ReadAllLines(fileName)
End Function
Private Function ReplaceQuotes(fileContent As String())
For Each line As String In fileContent
Dim cleanLine As String
Dim quoteTest As Boolean
quoteTest = line.Contains("""")
Dim quoteTest2 As Boolean = line.Contains(ControlChars.Quote)
cleanLine = line.Replace(ControlChars.Quote, "")
line = cleanLine
Next
Return fileContent
End Function
You have to re-assign the new strings in the original array instead of replacing the local string variables. Therefore you can't use a For Each but only a For-loop. And the method can be shorter:
Private Sub ReplaceQuotes(fileContent As String())
For i As Int32 = 0 To fileContent.Length - 1
fileContent(i) = fileContent(i).Replace(ControlChars.Quote, "")
Next
End Sub

multidimensional array using list class and dictionary

//Declaration
Dim values As New List(Of Dictionary(Of String, String))()
I am trying to create a multidimensional array.
this is my code:
con.Open()
ccsfreader = ccsfcomm.ExecuteReader
ccsfreader.Read()
If ccsfreader.HasRows Then
Do
values.Add(New Dictionary(Of String, String)() From {{"CostCentre", ccsfreader.Item("CostCentre")}})
values.Add(New Dictionary(Of String, String)() From {{"ProcessDescription", ccsfreader.Item("ProcessDescription")}})
Loop While ccsfreader.Read()
End If
con.Close()
For Each value As Dictionary(Of String, String) In values
Dim CostCentre As String = value("CostCentre")
Dim ProcessDescription As String = value("ProcessDescription")
cmblaborcost.Items.Add(CostCentre)
Next
My error is:
The given key was not present in the dictionary.
i want an output like this:
1 => array(
CostCentre=>10.00
ProcessDescription=>"up"
)
2 => array(
CostCentre=>20.00
ProcessDescription=>"sided"
)
3 => array(
CostCentre=>110.00
ProcessDescription=>"cutted"
)
You have two dictionaries in the list. One of which contains only "CostCentre" key, and the other contains only "ProcessDescription" key. So when you try to access both keys from a dictionary, one key must be missing.
You may want to use List(Of Tuple(Of String, String)) instead of List(Of Dictionary(Of String, String)). This example works for me :
Dim values As New List(Of Tuple(Of String, String))
values.Add(Tuple.Create("a1", "a2"))
values.Add(Tuple.Create("b1", "b2"))
values.Add(Tuple.Create("c1", "c2"))
'generate array from List of Tuple'
Dim result = values.Select(Function(x) New String() {x.Item1, x.Item2}).ToArray()
For Each s As String() In result
Console.WriteLine(s(0) & ", " & s(1))
Next
And for your case, it could be something like this :
'example to add item to list'
Dim values As New List(Of Tuple(Of String, String))
......
If ccsfreader.HasRows Then
Do
'values.Add(Tuple.Create(ccsfreader.Item("CostCentre"), ccsfreader.Item("ProcessDescription"))'
values.Add(New Tuple(Of String, String)(ccsfreader.Item("CostCentre"), ccsfreader.Item("ProcessDescription")))
Loop While ccsfreader.Read()
End If
.......
'example to access item from list'
For Each value As Tuple(Of String, String) In values
Dim CostCentre As String = value.Item1
Dim ProcessDescription As String = value.Item2
cmblaborcost.Items.Add(CostCentre)
Next

multidimentional array of strings in vb.net

I have a text file like:
[edit] the number of line is unknown, it could be hundreds of lines.
How would I store them in a multidimensional array? I want my array to look like:
sample(0)(0) = "--------"
sample(0)(1) = "Line1"
..and so on
sample(1)(0) = "--------"
sample(1)(3) = "Sample 123"
..and so on
What I have done so far was to open the file and store in a 1-dimentional array:
logs = File.ReadAllLines("D:\LOGS.TXT")
I have tried creating an Array of string like:
Dim stringArray as String()()
stringArray = New String(varNumber0)(varNumber1)
But it returns and error.
You can use File.ReadLines/File.ReadAllLines to get the lines and a simple For Each-loop to fill a List(Of List(Of String)). Then you can use
list.Select(Function(l) l.ToArray()).ToArray()
to get the String()() (jagged array):
Dim lines = File.ReadLines("D:\LOGS.TXT")
Dim list As New List(Of List(Of String))
Dim current As List(Of String)
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
list.Add(current)
Else
current.Add(line)
End If
Next
Dim last = list.LastOrDefault()
If last IsNot Nothing Then
If Not current Is last AndAlso current.Any() Then
list.Add(current)
ElseIf Not last.Any() Then
list.Remove(last) ' last line was ("----------")'
End If
End If
Dim stringArray As String()() = list.Select(Function(l) l.ToArray()).ToArray()
If you want to include the --------- in the array at the first position:
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
current.Add(line)
list.Add(current)
Else
current.Add(line)
End If
Next
Try like this but you need to customize according to you
Dim mArray(10,10) As String
Dim i As Integer = 0
For I=0 to 10
For J=0 to 10
For Each line As String In System.IO.File.ReadAllLines("file.txt")
mArray(i,j) = cmdReader.Item(line)
Next
Next
Next
Use declaration like this (this is just a generic)
Dim dim1 As Integer = 0
Dim dim2 As Integer = 0
Dim strings(,) As String
Do
dim1 = NewDimensionNumberFromFile
dim2 = NewSecondDimensionNumberFromFile
ReDim Preserve strings(dim1, dim2)
strings(dim1, dim2) = ValueFromfile
Loop While (Not EOF()) 'this will determine

Resources