Cannot get the last row of data - asp.net

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

Related

Get value from JArray item with has inconsistent values

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

How I read XLMS file row by row after a condition?

I have a problem with a XLSM Excel of which I want to get some data by condition.
Excel image
In the picture I have "Name", and "Status", if the status is "Completed" I want to take their value on "Time Assembly -> Post Assembly" where the value is "1.11". For each value of "Time Assembly" in the end I want to do media.
my code:
If FileUpload1.HasFile = False Then
Exit Sub
Else
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
'Dim FolderPath As String = ConfigurationManager.AppSettings("Upload")
Dim FilePath As String = Server.MapPath("~") & "\Upload\" & FileName
FileUpload1.SaveAs(FilePath)
Dim existingFile = New FileInfo(FilePath)
Dim pack As ExcelPackage = New ExcelPackage(existingFile)
Dim workBook As ExcelWorkbook = pack.Workbook
If workBook.Worksheets.Count > 0 Then
Dim currentWorksheet As ExcelWorksheet = workBook.Worksheets.First()
End If
End If
In that "if" I want to read Excel row by row, after that condition.
Thanks a lot!
Try to find the last row in the sheet and use for loop to iterate the condition
Sub test()
Dim lastRow As Long
Dim workBook As workBook
workBook = ThisWorkbook
lastRow = workBook.ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
For i = 3 To lastRow
'for checking value in the 4 column(D column)
If (workBook.ActiveSheet.Cells(i, 4).Value) = "completed" Then
workBook.ActiveSheet.Cells(i, 6).Value = "xx"
End If
'for adding value in the 6 column
Next
End Sub

Formatting a column to use a phone number format in EPPlus

I have phone numbers stored as a string of numbers, e.g.: 6028035615, but CAST them as integers when querying. I want to format the data in the cell in proper phone number format, such as (602) 803-5615 as Excel would. But how do I state the format type I want to use?
If I use:
objData.Columns.Add("HPhone", GetType(Integer))
wshUS.Column(i).Width = 15 ' PhoneH
wshUS.Column(i).Style.Numberformat.Format = "###-###-####"
or
wshUS.Column(i).Style.Numberformat.Format = "(###) ###-####"
a blank cell is shown as either -- in the former case or ()- in the latter.
Is there a format type that I can put after the = to get phone numbers as Excel would?
How would I use conditional formatting to overcome that problem?
I am writing in VB.NET in codebehind for web pages.
What is objData? Generally speaking, you shouldn't need to add columns to a sheet - EPPlus will do this automatically when your reference the cell for the first time. My VB is a little rusty but this works fine for me:
<TestMethod> _
Public Sub PhoneNumberFormatTest()
Dim file = New FileInfo("c:\temp\temp.xlsx")
If file.Exists Then
file.Delete()
End If
Dim pck = New ExcelPackage(file)
Dim workbook = pck.Workbook
Dim worksheet = workbook.Worksheets.Add("newsheet")
Const number As String = "6028035615"
Const format As String = "(###) ###-####"
Dim startcell = worksheet.Cells(1, 1)
startcell.Value = Int64.Parse(number)
startcell.Offset(1, 0).Value = Int64.Parse(number) + 1
worksheet.Column(1).Width = 15
worksheet.Column(1).Style.Numberformat.Format = format
pck.Save()
End Sub
I downloaded the source code solution of EPPlus 3 (stable) and ran this as a unit test...
EDIT: Added string manipulation:
<TestMethod> _
Public Sub PhoneNumberFormatTest()
Dim file = New FileInfo("c:\temp\temp.xlsx")
If file.Exists Then
file.Delete()
End If
Dim pck = New ExcelPackage(file)
Dim workbook = pck.Workbook
Dim worksheet = workbook.Worksheets.Add("newsheet")
Const number As String = "6028035615"
Const format As String = "(###) ###-####"
Dim startcell = worksheet.Cells(1, 1)
'Directly to numbers with parse
startcell.Value = Int64.Parse(number)
startcell.Offset(1, 0).Value = Int64.Parse(number) + 1
'OR as a string back to a number.
Dim stringcell = startcell.Offset(2, 0)
stringcell.Value = number
stringcell.Value = Int64.Parse(DirectCast(stringcell.Value, String))
stringcell.Style.Numberformat.Format = "(###) ###-####"
'As string - does not work as number
stringcell.Offset(0, 1).Value = number
stringcell.Offset(0, 1).Style.Numberformat.Format = "(###) ###-####"
worksheet.Column(1).Width = 15
worksheet.Column(1).Style.Numberformat.Format = format
pck.Save()
End Sub
The exact formatting that excel use for phone numbers is: "[<=9999999]###-####;(###) ###-####".
I suggest you also check this answer: EPPlus Format Cell as "Accounting" Number. It shows how to get all built-in formatting formula.

How to limit the number of rows to be read in a CSV file using CSVReader in ASP.NET

I am using a csvReader in order to retrieve data from a csv file. My csv file consists of 500elements and I only need the first 300. How do I limit my csvReader in order to return only 300 elements?
Dim PressureTable As DataTable = GetDataTabletFromCSVFile(BackUpDirDminus1)
Console.WriteLine("Rows count:" + PressureTable.Rows.Count.ToString)
Console.ReadLine()
Using CSVReader As New TextFieldParser(BackUpDirDminus1)
CSVReader.SetDelimiters(New String() {","})
CSVReader.HasFieldsEnclosedInQuotes = True
'read column names
Dim colFields As String() = CSVReader.ReadFields()
'For Each column As String In colFields
While Not CSVReader.EndOfData
Dim fieldData As String() = CSVReader.ReadFields()
'Making empty value as null
For i As Integer = 0 To fieldData.Length-1
If fieldData(i) = "" Then
fieldData(i) = Nothing
End If
Next
PressureTable.Rows.Add(fieldData)
End While
End Using
Please help. Thanks
I suppose there should be a method name "ReadNextRecord()", so your while loop should be like
While CSVReader.ReadNextRecord()
Declare a int k =0
and do k++
Once K++ reaches 300, then you can End While.

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