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
Related
I'm trying to provide on the save button a validation error saying a certain field can't be left blank.
I'm honestly not sure what to try.
If txtGEMFeeWBS.Text = "" Or lblGEMFeeWBS.Text = "" Then
MsgBox("Error Gem Fee WBS Code must be provided before you can save")
End If
Save_Validation()
If blnValidation = True Then
If Me.lblInvoiceShipmentID.Text = "" Then
Save(1)
Else
SaveAllKitUnits()
Save(2)
End If
End If
After where the message box is thrown I want to close out and not hit save data information
I'm not sure about having understood the question but...
It depends on a lot of things. Do you want to completely close the program? Are you inside a method?, etc...
If you want to close the entire program (I don't think so) just try
Application.Exit()
If you are on a method you can just use the instruction return nothing
And in other cases use the GoTo: Anywhere on the code (almost
anywhere) you can put SampleGoToLine: (don't forget the ':')
and then call the instruction GoTo SampleGoToLine anywhere you
want or, in your case, after showing the messagebox.
(The name SampleGoToLine is invented, you can put any not reserved VB keyword)
Finally what I would personally do is to reestructure the code. Maybe split validation and save into two different methods or something similar so you can always control what method do you go to depending on certain conditions. (With a simple if-else structure)
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.
I have a DataGridView and have the AutoGenerateColumns property set to false, but the when I build my project the columns are Auto Generated.
I can see the property set to false in the Designer.vb code for the Form.
I've had this problem before and I'm not sure how to fix it.
Any advise would be greatly appreciated.
Thanks.
I know this is an old question, but maybe it helps someone who searches for the same issue:
I ran in this problem today. It is important to set the 'AutoGenerateColumns'-property before you set the DataSource, otherwise the columns get generated before you told the DataGridView not to do so:
DataGridView1.AutoGenerateColumns = False
DataGridView1.DataSource = mySource
I have re-added the control and it seems to be working for the time being. I believe something became corrupted, causing the problem. As I mentioned in the question I've had this happen before. If anyone else has a problem like this it would be great if you could provide some details.
I have found that if you're trying to setup columns during load of the form, then you expierence weird issues like this. Instead, just before populating the grid, I check to see if there are columns defined and if not, then I go ahead and configure the columns at that point. This is working consistenly for me -- when populating the columns, I set the property to auto add columns = false first thing:
Private Sub Populate_dgvQuoteSelection(status_id As Int32)
dgvQuoteSelection.DataBindings.Clear()
If dgvQuoteSelection.Columns.Count = 0 Then
Setup_dgvQuoteSelection()
End If
Try
dgvQuoteSelection.DataSource = DataService.Quote_HeaderDataService.Quote_GetListView_byStatus(status_id)
Catch ex As Exception
MessageBox.Show(String.Format("An error occured while trying to get the grid data: {0}", ex.Message), "Error populating grid", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
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
I know, I know, I could have used a for loop, dont tell me anything about that. Please, help!
Private Function LoadSaved() ''//Loads saved clippings if the user wants us to
Dim ZomgSavedClips As StringCollection
If IsDBNull(My.Settings.SavedClips) = False Then ''//If it is null this would return a rather ugly error. Dont want that do we?
ZomgSavedClips = My.Settings.SavedClips ''//ZomgSavedClips name was a joke, I just felt like it.
ZomgSavedClips.Add(" ") ''//This line ought to fix the error, but doesnt
i = 0
While i < ZomgSavedClips.Count ''//This is where the error occurs
ClipListings.Rows.Add(ZomgSavedClips(i))
i = i + 1 ''//First time I wrote this function I forgot this line. Crashed mah comp. Fail.
End While
End If
End Function
The line While i < ZomgSavedClips.Count is bugging, I know that the .count should return null but I even added a blank piece of text just to stop that. Whats up with this? Should I add actual text?
SavedClips is null no? If it is null it could pass the test IsDBNull beacuse the both are not the same
Obviously, My.Settings.SavedClips is still set to Nothing.
SavedClips is regular 'ole null (nothing in VB). Include a check for "My.Settings.SavedClips is nothing". If that evaluates to true then just leave the function.
I even added a blank piece of text just to stop that.
All you did was move where the error happens. You can't call .Add() on a null/Nothing object.
'''<summary>Loads saved clippings if the user wants us to</summary>'
Private Sub LoadSaved() ''//Loads saved clippings if the user wants us to
''//Load saved clips into memory
Dim ZomgSavedClips As StringCollection = My.Settings.SavedClips
If ZomgSavedClips Is Nothing Then ZomgSavedClips = New StringCollection()
''//Apply loaded clips to visible listings
Dim i As Integer
While i < ZomgSavedClips.Count ''
ClipListings.Rows.Add(ZomgSavedClips(i))
i += 1
End While
End Sub
Some notes on this code:
Don't use Function when you mean Sub
Since you'll be selling this code to others, you want to use xml comments at the top so that Visual Studio can give better intellisense helps.
IsDBNull() doesn't do what you think it does.
Yes, you should use a for loop, but since you already commented on that I left the while loop alone with the assumption that there's more code you didn't show us.