StackOverflow in List(Of T) - vb.net

I have a program that uses Lucene.net in ASP.NET (VB.NET), when you search a term, results are stored in the Lucene.net data structure "hits".
I want to read out the hits into an data structure and work with them, after that I display them in a DataGrid.
By searching a term with a lot of results, often (but not always) there is an error by following code :
For i = 0 To results - 1 Step 1
Try
Dim tmpobj As New object_hit(( _
hits.Doc(i).Get("title") + _
hits.Doc(i).Get("doc_typ")), _
hits.Doc(i).Get("pfad"), _
hits.Doc(i).Get("last_change"), _
hits.Doc(i).Get("doc_typ"), _
CStr(hits.Score(i)))
list_of_results.Add(tmpobj) 'works'
Catch
meldung.Text = "Stackoverflow- zuviele Ergebnisse "
myexception = True
End Try
I checked the server; it's a dwh server and has no problems to execute the program.
At first I used a ReDim Array, but now I use a List(Of T). I heard that should solve the problem, but it doesn't - now I'm very confused and don't know what to do-
can someone help me please?

Change the Catch block so that you actually can see what is happening here:
Catch ex as Exception
meldung.Text = ex.Message ' or ex.ToString() to see full details '
throw
End Try
You are probably not getting a StackOverflowException here.

my browser crashed, so i have to write as an guest : < sorry.
i tried that:
Exception of type 'System.OutOfMemoryException' was thrown.
now i have an correct for loop, with only one line of code in it
list_of_results.Add(New object_hit((hits.Doc(i).Get("title") + hits.Doc(i).Get("doc_typ")), hits.Doc(i).Get("pfad"), hits.Doc(i).Get("last_change"), hits.Doc(i).Get("doc_typ"), CStr(hits.Score(i))))
so what happened? (the server is an dwh server, it should make it ...)
thanks

Related

DataReader running very slow

I'm currently working with a database of over 50 million records, where I read a file which a person wants to search the database for etc. I have noticed my data reader part is running particularly slow, where as the query seems almost instant (database is indexed). I was just wondering does anyone know as to why it seems to be running slow?
con.Open()
Using sw As New StreamWriter("G:\USER\SEARCH-RESULTS.txt")
Try
For Each word As String In result
Using com As New SqlCommand("select t.SmeNbr, t.FilPth, r.MaxDate, t.DteAdd, t.LnePos from (Select SmeNbr, MAX(FilDte) as MaxDate from Test_Table where SmeNbr = #word group by SmeNbr)r inner join Test_Table t on t.SmeNbr = r.SmeNbr and t.FilDte = R.MaxDate", con)
com.Parameters.AddWithValue("#word", word)
Using RDR = com.ExecuteReader
If RDR.HasRows Then
Do While RDR.Read
MyFilePath = RDR.Item("FilPth").ToString()
linePos = RDR.Item("LnePos").ToString()
Using sr As New StreamReader(MyFilePath)
sr.BaseStream.Seek(4096 * (linePos - 1), SeekOrigin.Begin)
FoundWords.Add(sr.ReadLine)
For Each item As String In FoundWords
sw.WriteLine(item)
Next
FoundWords.Clear()
End Using
Loop
Else
Continue For
End If
End Using
End Using
Next
Catch ex As Exception
MessageBox.Show("Couldn't process search")
Finally
con.Close()
End Try
End Using
MsgBox("Complete!")
So it works perfect, as in it gets the records and bits of info I want very quickly through the query and all and even the writing reults to a new file is near instant, I used breakpoints and like I said it seems to take ages between the "Using RDR = com.ExecuteReader" and "If RDR.HasRows Then"
Any help or ideas would be greatly appreciated.
com.Parameters.AddWithValue("#word", word)
AddWithValue infers the parameter data type from the provided .NET object value. Since .NET strings are Unicode, this code is will add an nvarchar(n) parameter with the length of the actual value. I see from your comments that the actual column data type is char(13) so it would be best to explicitly specify that as the parameter data type:
com.Parameters.Add("#word", SqlDbType.Char, 13).Value = word
The implications with AddWithValue are that indexes might not be used due to the mismatched data type and there may be many variations of the same query in the SQL Server procedure cache that differ only by length. For these reasons, I suggest one avoid AddWithValue.

How do I rollback a failed InsertOnSubmit? (VB.NET LINQ)

I'm having a problem with undoing a failed InsertOnSubmit when SubmitChanges fails. Here's the code:
Dim NewFac As New t_Facility With
{.FK_Instance_ID = guInstance_ID,
.FK_AccountType_ID = guAccountType_ID,
.FK_ATP_ID = guATP_ID,
.FK_Repayment_ID = guRepaymentType_ID,
.FK_InterestType_ID = guInterestType_ID,
.FK_FT_ID = guFacilitiesType_ID,
.NewRecord = bNewRecord,
.IndexNum = iIndexNum,
.SortCode = sSortCode,
.AccountNumber = sAccountNumber,
.Balance = decBalance,
.LastSanction = decLastSanctioned,
.Proposed = decProposed,
.Term_MTHs = iTerm_MTHS,
.Term_Expiry = dTerm_Expiry,
.InterestRate = decInterestRate,
.ArrangementFee = decArrangementFee,
.DateTime_From = Now(),
.ID = guFacilities_ID}
db.t_Facilities.InsertOnSubmit(NewFac)
Try
db.SubmitChanges()
Catch e As Exception
Console.WriteLine(e)
MessageBox.Show(e.Message & ". Please correct the field and try again", "ERROR", MessageBoxButton.OK, MessageBoxImage.Stop)
Exit Sub 'Takes the user back to the form to correct the value
End Try
When they hit submit again, it comes back around and fails at the same point with the same values as the original submission ignoring the new values that the user input.
The values in "NewFac" are the corrected new values. I've checked them on this line manually in debug: "db.t_Facilities.InsertOnSubmit(NewFac)"
I assume i need to somehow remove the failed "NewFac" that contains the incorrect values from "db.t_Facilities.InsertOnSubmit(NewFac)" in the catch somehow, but i don't see a way to do this?
FYI: I got the principal of this approach from here: https://msdn.microsoft.com/en-us/library/bb763516
Any help would be appreciated.
Now this is probably not going to be technically correct, so someone informed; please feel to give the real reason this worked (So its not really based on any statement of fact other than it worked, and is entirely my opinion - but it worked):
The solution dawned on me while reading through several questions from various other people having similar issues (all using various ways of Programmatically looping through the DataContext looking for a match), that the changes are just added the DataContext which appears to effectively act like an offline CLR of the database, so if InsertOnSubmit added to it, it stands to reason DeleteOnSubmit should remove it right?
So with that in mind, i tried this:
db.t_Facilities.InsertOnSubmit(NewFac)
Try
db.SubmitChanges()
Catch e As Exception
Console.WriteLine(e)
MessageBox.Show(e.Message & ". Please correct the field and try again", "ERROR", MessageBoxButton.OK, MessageBoxImage.Stop)
db.t_Facilities.DeleteOnSubmit(NewFac)
Exit Sub 'Takes the user back to the form to correct the value
End Try
It worked! :D
So i may be totally wrong as to why it worked (please inform me why - i'd genuinely like to know), but it worked.
EDIT:
If someone can give the correct reason it worked, i'll accept their answer instead of my own

Changing system time dynamically win7

Sub change_the_time(ByVal NewDateTime As DateTime)
'
Dim NewDateTime2 As DateTime
'
NewDateTime2 = #5/1/2016 5:52:15 PM# ' try setting the time to this
'
'set the system date and time to this date and time - throw an exception if it can't
Try
TimeOfDay = NewDateTime2
Catch ex As Exception
MessageBox.Show("Could not set time. " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
End Try
End Sub
Hi.
New to the site so hopefully I follow the rules :-)
My questions is how do I successfully change the system time? The above code I found on this site (as well as much info on other parts of my project - thank you!) and there are no errors, but it always throws an exception. I run as admin and I've tried changing the UAC and I still can't change the time. I read that I need to have the SE_SYSTEMTIME_NAME privilege set, but I have this set so that all users (ie me) have the right, still nothing. The MS reference here does not provide much insight. I suspect it's an issue with privileges, but i can't seem to see how to set what i need. What do I need to do to allow my application to change the system time to a value?
More info...there is another question along the same lines, but it's c# not Vb and I've tried something similar to that code, which is below. Still
Private Sub change_the_time2(ByRef NewDateTime As DateTime)
Dim d As DateTime
d = #6/10/2011# ' try setting the date to this before using NewDateTime
Dim worked As Boolean
'
Try
worked = setlocaltime(d)
MsgBox(" 1. Did it work " & worked)
Catch ex As Exception
MsgBox(" 2. Did it work " & worked)
End Try
End Sub
<DllImport("kernel32.dll", setLastError:=True)> _
Private Shared Function setlocaltime(ByRef time As System.DateTime) As Boolean
End Function
This is essentially a duplicate of this question as has been mentioned in the comments. But to clarify for VB.NET as oposed to C#, per one of the answers in that question:
On Windows Vista, 7, 8 OS this will require a UAC Prompt in order to
obtain the necessary administrative rights to successfully execute the
SetSystemTime function.
The reason is that calling process needs the
SE_SYSTEMTIME_NAME privilege. The SetSystemTime function is expecting
a SYSTEMTIME struct in coordinated universal time (UTC). It will not
work as desired otherwise.
Depending on where/ how you are getting
your DateTime values, it might be best to play it safe and use
ToUniversalTime() before setting the corresponding values in the
SYSTEMTIME struct.
Code example (modified for VB.NET):
Dim tempDateTime As DateTime = GetDateTimeFromSomeService()
Dim dateTime As DateTime = tempDateTime.ToUniversalTime()
Dim st As SYSTEMTIME
'All of these must be short
st.wYear = dateTime.Year.ToInt16()
st.wMonth = dateTime.Month.ToInt16()
st.wDay = dateTime.Day.ToInt16()
st.wHour = dateTime.Hour.ToInt16()
st.wMinute = dateTime.Minute.ToInt16()
st.wSecond = dateTime.Second.ToInt16()
// invoke the SetSystemTime method now
SetSystemTime(ByRef st)
Yes, you need Administrator privileges.

VB not stopping at exceptions

I like VB.Net, but there is something that is driving me nuts. Too many times when an exception occurs, it simply continues somewhere else, usually by exiting the sub or function, but otherwise keeps on rolling. As an example, I was using Asc() instead of AscW(). It didn't throw an exception, it just left the function as if a Return was executed. Meanwhile I'm leaving red dot stop points all over like it has chicken pox trying to figure out what is causing it.
Is there a setting that can be used to used to actually cause VB to stop and give a line number?
Try catch statements will help you out greatly.
Take a read here: https://msdn.microsoft.com/en-us/library/fk6t46tz.aspx
Have you tried using a Try..Catch..Finally statement. E.g. The ex.string will put the exception into a string in the message and tell you the vb line.
Try
'code here
Catch ex as Exception
MessageBox.Show("Something went wrong. " & ex.ToString, "Data Error ")
End Try

Object Reference Error Using List.FindAll [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have a bizzare issue that I am struggling to resolve:
I have a form that performs a number of different searches using LINQ queries. 99% of the time the code will execute fine without any errors what so ever, however, on total random occasions, my form falls over on the following line:
'Find all tickets belonging to a user
Dim _userTicketsList As List(Of Ticket) = Tickets.FindAll(Function(p)
p.ticket_firstname.ToUpper = NewSearchString And
CDate(p.ticket_created_at.Value.ToShortDateString) >= date1
And CDate(p.ticket_created_at.Value.ToShortDateString) <= date2)
The error I get is Object Reference Not Set To An Instance Of An Object
From then on, any search will continue to bomb out on this line of code, until I restart my app. I execute the search again and everything works fine.
I cannot understand what is causing this error to occur. It can happen if .FindAll returns 0 results or if it returns any number of results.
Is there anyway I can determine what Object is trying to get set? I'm assuming its _userTicketsList but it doesn't make sense why sometimes it works and sometimes it doesn't.
I know it's probably hard to comment without seeing every bit of code, but is there anyway I can try and debug this differently? The debugger sits on this line of code for 23,000+ Ticket items, so I can't even work out if there is a specific Ticket that is causing the issue.
Any help or direction is greatly appreciated.
Thanks
Well, you can basically decorate your lambda expression with try catch statements, just to log / do something with the error.
'Find all tickets belonging to a user
Dim _userTicketsList As List(Of Ticket) = Tickets.
FindAll(Function(p)
Dim condition1 As Boolean
Dim condition2 As Boolean
Dim condition3 As Boolean
Try
condition1 = p.ticket_firstname.ToUpper = NewSearchString
Catch ex As Exception
'Do Something
End Try
Try
condition2 = CDate(p.ticket_created_at) >= date1
Catch ex As Exception
'Do Something
End Try
Try
condition3 = CDate(p.ticket_created_at) <= date2
Catch ex As Exception
'Do Something
End Try
Return condition1 And condition2 And condition3
End Function)
Code Addition Edited Per OP's comment
If _userTicketsList.Any = False Then
_userTicketsList = Nothing
End If
I also wanted to make sure you are aware of the difference in using And vs. AndAlso clause in vb.net.
When writing something like If(A and B)
both A and B will execute.
While using AndAlso, will not execute B if A is false,
since you are using And, I thought I'll mention it.