InsertOnSubmit not triggering a database insert on SubmitChanges - asp.net

I'm experiencing an odd scenario and I'm looking for ways to figure out what's going wrong. I've got a piece of code that inserts a row into a table - the kind of thing I've done in dozens of other apps - but the end result is nothing happens on the database end, and no errors are generated. How do I find out what's going wrong?
Here's my code:
Partial Class MyDatabaseDataContext
Public Sub CreateEnrollee(subId, depId)
dim newEnrollee = New enrolee With {.subId = subId, .depId = depId}
Me.enrollees.InsertOnSubmit(newEnrollee)
Me.SubmitChanges()
dim test = NewEnrollee.id '<-- auto-incrementing key'
End Sub
End Class
After SubmitChanges is called, no new row is created, and "test" is zero. No errors are generated. I have no idea why it's not trying to insert the row. Any ideas on how to debug this?

You could enable logging:
Me.Log = Console.Out;
You could check the ChangeSet for your object.

FOUND IT! Part of the debugging I did for some other issues included adding some logging to some of the extensibility methods:
Partial Private Sub InsertEnrollee(instance As Enrollee)
End Sub
I thought "InsertEnrollee" existed so I could perform actions after the Enrollee was inserted, so I added logging code here and that's when the trouble started. Now I'm guessing this is how you would override the Enrollee insert and do it yourself if you so desired. Since I was essentially overriding with logging code, that's why nothing was happening (from a database perspective).

Related

Using a timer to move between Views in a MultiView control

I'm trying to get a timer to move between 3 Views in a MultiView control here is the code I'm using:
Protected Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim activeView As String
activeView = MultiView1.GetActiveView().ID
If activeView = "View1" Then
MultiView1.SetActiveView(View2)
End If
If activeView = "View2" Then
MultiView1.SetActiveView(View3)
End If
If activeView = "View3" Then
MultiView1.SetActiveView(View1)
End If
End Sub
On page load I have the MultiView Control set to View1 (MultiView1.SetActiveView(View1))
The page loads correctly and the data (being pulled from an SQL server is visible. After the first tick on timer1 the second view appears again showing the correct data. Then nothing I can see the reload button on the browser going at the timer interval but I never see View3 or a return to View1
Before anyone suggests I had build the If statement as If, ElseIf, EndIf but I broke it out into separate If statements to see if that would help.
It didn't.
I Hope someone can help
Cheers
Have you tried to debug your code with breaks, try to put a break in the If...End If blocks and watch if it is reachable.
You may be having different IDs set for your views, or maybe some cASE mismatching. I will suggest, rather comparing view's ID string, it is safe to compare views index by MultiView1.ActiveViewIndex, this will return only an integer which is lot safer to compare.
Hope it will work.
Sometimes I wonder if I should be let out without a carer.
I found out why the views or label.text changes weren't progressing. I had set the startup info in page_load so even though the timer was firing it was doing a page_load which was defaulting back to the original data.
Sorry for the waste of your time.
I'm off to slowly bang my head against the wall until it doesn't hurt anymore then return to my project.

how to handle exceptions in vb.net?

I am creating a program in which a user can search and add their desired order. The problem that I'm facing now is that when I throw the exception, the program does not read the exception so that the user will know if the id that is entered is on the database or not. I will provide the code snippet of the program that I'm working on.
Problems
Your code will not throw an error if the item_code does not exist in your database. It will simply not enter the while loop.
This is not the proper use of an exception. It is not an error if the record is not found. The proper way of checking if the item_code exists is a check if the datareader has results.
You must properly defend yourself again SQL injection. By concatenating the sql query you are opening yourself up to a whole host of problems. For example, if a user maliciously enters the following text, it will delete the entire Products table: ';DROP TABLE Products;-
You are not disposing of the OleDbConnection or the OleDbCommand objects correctly. If an exception occurs, your code will not run the Dispose() method. This can cause you to quickly run out of resources.
Solutions
You should check if the dataRead has any rows. If it does not, then you can alert the user via javascript. Like so:
If dataRead.HasRows Then
//READ DATA
Else
//ALERT USER
End If
Solution #1 address Problem #2 as well
Use a parameterized query. The .NET framework will prevent these kinds of attacks (SQL Injection).
selectProductQuery = "SELECT * FROM Products WHERE item_code = #item_code"
...
newCmd.Parameters.AddWithValue("item_code", txtItemCode.Text);
Wrap all objects that implement Dispose() in a using block. This will guarantee everything is properly disposed of, whether an error is thrown or not.
Using newCon As New OleDbConnection(....)
Using newCmd As New OleDb.OleDbCommand(...)
...
End Using
End Using
To be perfectly honest, there is quite a bit "wrong" with your code, but this should get you headed in the right direction.
The line:
Response.Write(<script>alert('The ...')</script>)
Needs to be (note the quotes):
Response.Write("<script type='text/javascript'>alert('The ...')</script>")
Same for the other one at the top, but I dont think that will fix your overall problem.
Instead, use javascript like this:
if(!alert('Whoops!')){window.location.reload();}
to pop up an alert box and then reload the page after they click on the button.

Executing a VB WebMethod from javascript

I'm trying to eliminate a VB.NET button on my aspx page. Trying to use javascript and ajax to execute the same code my vb had.
I put in a script manager, set EnablePageMethods to true, added a static subroutine, and referred to it in my javascript function (BTW -- this seems a lot of work just to execute an existing subroutine). The javascript calls my code-behind and it almost works.
Problem is, now I'm getting a NullReferenceException when SimulatePrintBatchClick tries to do anything with the controls.
Error is 'Object reference not set to an instance of an object', line is 'pnlVars.Controls.Clear'
Here's the code from UW.aspx:
<WebMethod()> _
Public Shared Sub PrintBatchFromJSWM()
Dim UWI As New UW
UWI.SimulatePrintBatchClick()
End Sub
Sub SimulatePrintBatchClick()
Dim Client As New LetterWriterClient
'Run ExStream and get the PDF File
Globals.PDF_Data = Nothing
Globals.PDF_Data = Client.ProcessDatFile(Session("SessionID").ToString)
'Reload the form -- turn off all controls, initialize variables and make the PDF iFrame visible
pnlVars.Controls.Clear() 'Bombs out on THIS line of code
pnlPDF.Visible = True
Me.SendToBach.Visible = False
Session.Contents("LetterVariables") = Nothing
Session.Contents("PolicyInformation") = Nothing
Session.Contents("Submitted") = True
Response.Redirect("UW.aspx")
End Sub
Funny, when I run the above code in PrintBatch_Click it all executes just fine. I really don't understand why it bombs out as a subroutine.
Perhaps this is not the way to do this, but I'm at a loss for finding a different way. Originally this code was handled by an ASP/VB button, but the specs have called for it to be deleted.
Any way I can get the above code to do it's job?
Thanks,
Jason
You cannot use any server controls in WebMethod or AjaxMethod as they are not part of Page life cycle, access these controls in Javascript.

asp.net global synclock object

is there a way in asp.net to make sure that a certain threaded sub is not run twice concurrently, no matter what?
the code i have now is
Public Class CheckClass
ReadOnly Property CheckSessionsLock As Object
Get
If HttpRuntime.Cache("CheckSessionsLock") Is Nothing Then HttpRuntime.Cache("CheckSessionsLock") = New Object
Return HttpRuntime.Cache("CheckSessionsLock")
End Get
End Property
Sub TryThreads()
Dim thread = New Thread(AddressOf TryLock)
thread.Priority = ThreadPriority.Lowest
thread.Start()
End Sub
Sub TryLock()
SyncLock CheckSessionsLock
DoTrace("entered locker")
For x = 0 To 10000
Next
DoTrace("exiting locker")
End SyncLock
DoTrace("exited locker")
End Sub
End Class
if i run this code on every page then several times the code overlaps. the DoTrace function in the code simply writes the message to a table.
the messages in the table should appear in order (entered,exiting,exited) again and again, but in reality, they don't. i get like entered, exiting,entered,exited,exiting...
this means that the synclock is not complete. is that true?
if so, how can we implement a complete synclock on a block of code, across requests and across sessions?
EDIT: i need this lock, as the real code will be sending emails, according to a list of mailing types in a db. after each mailing type is sent, its marked, then it continues with the next mailing. i cant have in middle of processing, another thread should see this mailing as unprocessed.
please advise
Rather than using the HttpRuntime Cache have you considered using a static variable?
Just as a note (it might be helpful to explain why you want this functionality) your website is not going to be very scalable if this can only be run once at a time.
In C# (sorry, don't know VB syntax) I use this:
private static readonly object Padlock = new object();
It's a field, not a property,
It's static (in VB, that's "shared" if I'm not mistaken) so it's the same throughout the entire application
It's initialised once as soon as you use this class, not when you explicitly use the field.
With your property/cache version, you could have two threads trying to get the lock-object and each creating a different one:
Thread 1 checks the cache and doesn't find the object
Thread 1 is parked
Thread 2 checks the cache, doesn't find the object
Thread 2 creates the object and caches it, retrieves it again and returns from the property
Thread 1 resumes
Thread 1 creates a new object and caches it, retrieves it again and returns a different lock object than thread 2 uses
Any further threads will use the lock object of thread 1

Error handling using events, checking if an error happened and react accordingly

I have an object, say Order where if an error occurs, it raises the ErrorOccurred event. If I'm running some code in say, the codebehind for a .aspx page with an public Order registered as WithEvents and I want to check to see if an error has occurred before I run more code, how do I do this? I can't simply check theOrder.ErrorOccurred. Do I have to create a local boolean flag that switches over in the event handler (OnErrorOccurred)? Or is there a better way to do this?
Thanks!
Example:
Public WithEvents theOrder As New Order
Public Sub DoStuff()
theOrder.DoSomething()
If theOrder.ErrorOccurred Then
do stuff
End If
End Sub
That seems like a reasonable approach. If there is lots of logic going on with an Order object that depends on knowing about errors, having a Status field would allow easy communication to any consumer what the status of the order was, rather than everyone having to subscribe to the event and track it themselves.
Alternately you could track it internally in the Order and just throw exceptions when critical methods were accessed if the Order was in an error state. This has the disadvantage of making you do more error handling, but would have the advantage of making sure that any Order consumer handled them explicitly.
Why not use structured error handling?
Try
'Code that may raise an error.
Catch
'Code to handle the error.
Finally
'Code to do any final clean up.
End Try
http://support.microsoft.com/kb/315965
This is what it is intended for.
Problems may arize if someone calls DoSomething but thay are unaware that they need to check theOrder.ErrorOccurred. based on what DoSomething is doing, allowing one to call a method and letting it fail quietly can be a problem.
If do something is doing logging sure, let it fail. If it is finalizing an order process..
Brian
Use the Try Catch Block
Try
'try your code here
Catch somevariablenamehere As Exception
'use methods from Exception class to get to know the error better and how to deal with it
Finally
'this is optional, If you want to do something finally, like cleaning up etc. You can do here
End Try
'to end the Try block

Resources