checking if row was inserted - asp.net

I am trying to check whether a row is getting inserted into my database. It is throwing an error even when it does insert (it's a database issue that will get resolved later when I get a newer version of Microsoft Access), so I can't check whether the insert is successful based on whether there's an error or not. I think I need to check the AffectedRows of something, but I'm not sure what. I've been looking for info on how to do this but I can't figure out how to make it work for my exact situation. Here's a general idea of what my code looks like:
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
'code for collecting data...
'Define Connection
Dim myConn As New OleDbConnection
myConn.ConnectionString = AccessDataSource1.ConnectionString
myConn.Open()
'Insert command
Dim myIns1 As New OleDbCommand("INSERT INTO tableCourse 'long insert command here...
'Execute command and handle errors
Try
myIns1.ExecuteNonQuery()
Catch myException5 As Exception
End Try
'Close connection
myConn.Close()
-UPDATE-
I tried it like this:
'Execute command, handle errors, and check if row was inserted
Dim numInserted As Integer = 0
Try
numInserted = myIns1.ExecuteNonQuery()
Catch myException As Exception
Finally
If numInserted = 0 Then
Label1.Text = "Sorry, an error occured."
Else
Label1.Text = "Thank you! Your new course approval request has been submitted."
End If
End Try
But the numInserted is coming out as 0 every time even though the insert is successful. It may have to do with the fact that myIns1.ExecuteNonQuery() throws an error even though the insert is successful.
-EDIT- I discovered that the "duplicate values" error is because it is somehow attempting to insert the record twice. I have no idea why it's doing that though.

The ExecuteNonQuery function returns the affected number of rows...
Dim numInserted as Integer = myIns1.ExecuteNonQuery()
If numInserted = 0 Then
' no rows were inserted...throw exception?
End If

The symptoms you are describing (known no duplicates, but inserts throw duplicate errors) sound like your Access database needs Compacting and Repairing.
You should do this on a regular basis. (Always backup up first).

Related

InvalidOperationException: Timeout - recursive DB access

currently I have a serious problem with one of my web applications which runs into a Timeout Exception around half a dozen times a day.
Error: "The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached".
After a lot of googling I found out that the problem has something to do with unclosed connections. So I checked all functions that access the database in any way until I stumbled upon this one:
Private Sub getOrgas(ByVal orgID As String)
Dim Id = orgID
orgColl.Add(Id)
While (Not IsNothing(Id))
Dim conn = Database.DbWrapper.GetConnection(1, Integration.Mandanten.DatabaseType.AddonSQL)
Dim paras As New HashSet(Of System.Data.Common.DbParameter)
Dim orgatmp As String
paras.Add(New SqlClient.SqlParameter("#Id", orgID))
Dim dr = Database.DbWrapper.GetDataReaderFromStoredProcedure("stp_Orgas_Get", paras, conn)
While dr.Read
If Not valueInColl(CStr(dr(0))) Then
orgatmp = dr(0).ToString
orgColl.Add(orgatmp)
getOrgas(orgatmp)
End If
End While
dr.Close()
conn.Close()
Id = Nothing
End While
End Sub
As you can see this function executes a stored procedure and runs the results through a while loop where it calls the function again if a specific condition -valueInColl-. Now in that way it is possible that there are 20 or more open connections. It has nothing to do with the timeout-value which is set via the GetDataReaderFromStoredProcedure to 600 which actually should be enough. To be sure I doubled the value and will roll it out this evening. I'll see whether that helped within the next day then.
I believe the problem is that there are too many open connections at the same time, because of the recursive function, but I have no clue how to solve this.
I couldn't find anything as to how to edit the max connections. I'm not even entirely sure where have to set it. Is it the IIS, the DB itself or is it a programming-parameter (VB.net/ASP.NET).
Would be nice if you guys could help me out here.
[EDIT]
Ok, somebody had the idea to reuse the connection variable, but this won't work as the datareader is still running. As long as it is not closed I can't reuse the connection in any way and I can't close the datareader, because I might lose data if I do so. The while-loop for dr.read hasn't ended, yet ..
On the other hand I deleted the (pretty much useless) outer while and used an If-clause in exchange:
Private Sub getOrgas(ByVal orgID As String, ByVal con As DbConnection)
Dim Id = orgID
Dim conn As DbConnection
Dim tmpOrga As String
orgColl.Add(Id)
If Not IsNothing(Id) Then
If IsNothing(con) Then
conn = Database.DbWrapper.GetConnection(1, Integration.Mandanten.DatabaseType.AddonSQL)
Else
conn = con
End If
Dim paras As New HashSet(Of System.Data.Common.DbParameter)
paras.Add(New SqlClient.SqlParameter("#Id", orgID))
Dim dr = Database.DbWrapper.GetDataReaderFromStoredProcedure("stp_Orgas_Get", paras, conn)
While dr.Read
If Not valueInColl(CStr(dr(0))) Then
tmpOrga = dr(0).ToString
orgColl.Add(tmpOrga)
getOrgas(tmpOrga, conn)
End If
End While
dr.close()
conn.Close()
Id = Nothing
End If
End Sub
Is there any reason you cannot refactor things so that each recursion uses the same db connection?
I am not a VB coder but I would tackle it as follows
Change getOrgas() to take a connection parameter defaulting to 'nothing'.
Change the Dim conn line to if IsNothing(connParameter) conn = GetConnection() else conn := connParameter;
Change your recursion line to getOrgas(orgatmp, conn);
Test the F%%%% out of it.
I have just noticed the outer While Loop. Is it there just to confuse you ? How many times will it execute ? ...
I did wonder about the datareader -
try this - I see that your datareader needs to close before you recurse, so close it.
in pseudocode -
dim locallist = new list();
while dr.read
{
LocalList.Add dr.thing;
}
dr.close;
foreach(thing in locallist)
{
if Not ValueInColl(thing) Then
CallYourFunctionTRecursively()
end if;
}
Are you with me ?
If you are trying to put together all the members of a family then it depends which database system you are using how it is done, but look up 'Heirarchical queries' in your documentation.

Inserting null values into date fields?

I have a FormView where I pull data from one table (MS Access), and then insert it (plus more data) into another table. I'm having issues with the dates.
The first table has two date fields: date_submitted and date_updated. In some records, date_updated is blank. This causes me to get a data mismatch error when attempting to insert into the second table.
It might be because I'm databinding the date_updated field from the first table into a HiddenField on the FormView. It then takes the value from the HiddenField and attempts to insert it into the second table:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
myDateRequestUpdated = hfDateRequestUpdated.Value
'... It then attempts to insert myDateRequestUpdated into the database.
It works when there is a value there, but apparently you can't insert nothing into a date/time field in Access. I suppose I could make a second insert statement that does not insert into date_updated (to use when there is no value indate_updated), but is that the only way to do it? Seems like there should be an easier/less redundant way.
EDIT:
Okay. So I've tried inserting SqlDateTime.Null, Nothing, and DBNull.Value. SqlDateTime.Null results in the value 1/1/1900 being inserted into the database. "Nothing" causes it to insert 1/1/2001. And if I try to use DBNull.Value, it tells me that it cannot be converted to a string, so maybe I didn't do something quite right there. At any rate, I was hoping that if there was nothing to insert that the field in Access would remain blank, but it seems that it has to fill it with something...
EDIT:
I got DBNull.Value to work, and it does insert a completely blank value. So this is my final working code:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
Dim myDateRequestUpdated = Nothing
If hfDateRequestUpdated.Value = Nothing Then
myDateRequestUpdated = DBNull.Value
Else
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value)
End If
Thanks everyone!
Sara, have you tried casting the date/time before you update it? The data mismatch error likely comes from the fact that the hfDateRequestUpdated.Value you're trying to insert into the database doesn't match the column type.
Try stepping through your code and seeing what the type of that value is. If you find that it's a string (which it seems it might be, since it's coming from a field on a form), then you will need a check first to see if that field is the empty string (VBNullString). If so, you will want to change the value you're inserting into the database to DBNull, which you can get in VB.Net using DBNull.Value.
We can't see your code, so we don't know exactly how you get the value into the database, but it would look something like this
If theDateValueBeingInserted is Nothing Then
theDateValueBeingInserted = DBNull.Value
EndIf
Keep in mind that the above test only works if the value you get from the HiddenField is a string, which I believe it is according to the documentation. That's probably where all this trouble you're having is coming from. You're implicitly converting your date/time values to a string (which is easy), but implicitly converting them back isn't so easy, especially if the initial value was a DBNull
aside
I think what Marshall was trying to suggest was the equivalent of the above code, but in a shortcut expression called the 'ternary operator', which looks like this in VB.Net:
newValue = IF(oldValue is Nothing ? DBNull.Value : oldValue)
I wouldn't recommend it though, since it's confusing to new programmers, and the syntax changed in 2008 from IFF(condition ? trueResult : falseResult)
Your code
Dim myDateRequestUpdated As DateTime
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value) : DBNull.Value()
has a couple of problems:
When you declare myDateRequestUpdated to be DateTime, you can't put a DbNull.Value in it.
I'm not sure you need the () for DbNull.Value: it's a property, not a method (I don't know enough VB to say for sure)
VB doesn't know that : operator
What you probably want is a Nullable(Of DateTime) to store a DateTime value that can also be missing.
Then use something like this to store the value:
myDateRequestUpdated = If(String.IsNullOrWhiteSpace(hfDateRequestUpdated.Value),
Nothing, DateTime.Parse(hfDateRequestUpdated.Value))
If hfDateRequestUpdated.Value is empty, then use Nothing as the result; else parse the value as date (which might fail if it is not a valid date!).
Try this:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
If TextBox1.Text.Length <> 0 Then
str = "'" & TextBox1.Text & "'"
Else
str = "NULL"
End If
sql = "insert into test(test1) values(" & str & ")"
dsave_sql(sql)
End Sub
Function save_sql(ByVal strsql As String, Optional ByVal msg As String = "Record Saved Sucessfully") As String
Dim sqlcon As New SqlConnection(strConn)
Dim comm As New SqlCommand(strsql, sqlcon)
Dim i As Integer
Try
sqlcon.Open()
i = CType(comm.ExecuteScalar(), Integer)
save_sql = msg
Catch ex As Exception
save_sql = ex.Message
End Try
sqlcon.Close()
Return i
End Function

database update sql not affecting database

i have this code to update a database, but when ever i run it with the right data, it executes without errors but the databse is not update
Dim conn As New SqlClient.SqlConnection(My.Resources.conn_str)
Dim SQL As String = "Update vehicle SET make=#make,reg_no=#reg_no,model=#model,year=#year,type=#type,last_service=#last_service Where (id = #id)"
conn.Open()
Try
Dim cmd As New SqlClient.SqlCommand(SQL, conn)
Try
cmd.Parameters.AddWithValue("#make", strMake)
cmd.Parameters.AddWithValue("#reg_no", strRegnNum)
cmd.Parameters.AddWithValue("#model", strModel)
cmd.Parameters.AddWithValue("#year", intYear)
cmd.Parameters.AddWithValue("#type", strType)
cmd.Parameters.AddWithValue("#last_service", LastService)
cmd.Parameters.AddWithValue("#id", ID.ToString)
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
Return ex.Message
End Try
Catch ex As Exception
Return ex.Message
Finally
conn.Dispose()
End Try
can anyone help me with the reason its not working, as i don get an error message?
thanks
EDIT
i replaced the cmd.ExecuteNonQuery() with
Dim intAffected As Integer = cmd.ExecuteNonQuery()
Debug.Print(intaffected)
and i get 1 in the output window
A few thoughts:
If you have access to SQL Profiler, you can see the query, the values, the result, any triggers, any transactions, etc. This is the easiest way to identify what is going on.
If you don't have access to Profiler, update your query to include the OUTPUT clause, and return the values from inserted.* and deleted.* into a SqlDataReader using ExecuteReader. Check the results.
If the id is an int, don't use ID.ToString() on the parameter.AddWithValue. Use the integer itself, as the AddWithValue method with a string value could cause the ID parameter to be configured as a varchar/nvarchar.

checking for duplicate values before attempting insert (ASP.NET)

I have a form where two fields on the first page of the form make up the primary key. I want to check for duplicate values before attempting to insert the record, since I don't want the user to go all the way through the form only to find out they can't submit it. So I'm trying to check for duplicate values when the user tries to go to the next page of the form. I wasn't quite sure how to do it, and sure enough I'm getting an error. ("Object reference not set to an instance of an object.") The problem is apparently in my if statement, "If myValue.Length > 0 Then", but I'm not sure what needs to be in place of that.
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'get values
Dim checkPrefix = txtCoursePrefix.Text
Dim checkNum = txtCourseNum.Text
'db connectivity
Dim myConn As New OleDbConnection
myConn.ConnectionString = AccessDataSource1.ConnectionString
myConn.Open()
'select records
Dim mySelect As New OleDbCommand("SELECT prefix, course_number FROM tableCourse WHERE prefix='checkPrefix' AND course_number='checkNum'", myConn)
'execute(Command)
Dim myValue As String = mySelect.ExecuteScalar()
'check if record exists
If myValue.Length > 0 Then
CustomValidator1.ErrorMessage = "some exp text"
CustomValidator1.SetFocusOnError = "true"
CustomValidator1.IsValid = "false"
End If
End Sub
Thought I'd post the final solution:
'select records
Dim mySelect As New OleDbCommand("SELECT 1 FROM tableCourse WHERE prefix=? AND course_number=?", myConn)
mySelect.Parameters.AddWithValue("#checkPrefix", checkPrefix)
mySelect.Parameters.AddWithValue("#checkNum", checkNum)
'execute(Command)
Dim myValue = mySelect.ExecuteScalar()
'check if record exists
If myValue IsNot Nothing Then
CustomValidator1.SetFocusOnError = True
args.IsValid = False
End If
This error indicates that the content of myValue variable is null. If it's null you can't use Length property (or any other property for that matter) on it. You have to check for null explicitly:
If myValue IsNot Nothing Then
EDIT 1
Your sql query is wrong. I don't know what would be the right query, as I don't know your database, but I think you intender to write this:
Dim mySelect As New OleDbCommand("SELECT prefix, course_number FROM tableCourse WHERE prefix=" + checfkPreix + " AND course_number=" + checkNum, myConn)
or something to that effect. You might want to consider using string.Format function for forming the string. And you also need to make sure that there is some kind of protection against SQL Injection, since you form your query from user input. In your case using of OleDbParameter might be appropriate.
Edit 2
You also right to mention that there might be a problem with ExecuteScalar. ExecuteScalar is supposed to return a single value and your select query are returning two (prefix and course_number). Change it so that it returns a single parameter SELECT prefix FROM or simply SELECT 1 FROM and then the rest of the query:
Dim mySelect As New OleDbCommand("SELECT 1 FROM tableCourse WHERE prefix=? AND course_number=?", myConn)
mySelect.Parameters.AddWithValue("#checkPrefix", checkPrefix)
mySelect.Parameters.AddWithValue("#checkNum", checkNum)
Edit 3
You are not setting failed validation properly in your validator.
Add
args.IsValid = False
inside your if statement.
First ExecuteScalar will only return a single value, so in this case you are only going to get the column prefix from the result. Second if there is no match with your query it will return null, so your next length check should account for that scenario:
if String.IsNullOrEmpty(myValue) Then
...
Reference: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
myValue is null if there is no duplicate, so you have to apply .Length only if myValue is not null (which means checking for null only is enough; without .Length)
If Not string.IsNullOrEmpty(myValue) Then
try something like this instead (you will have to adapt it to VB.Net) DBNull is different from Null or Nothing so you have to compare it to both
If myValue <> DBNull and not myvalue is nothing Then

Insert asp.net Membership-generated UserId into custom table (vb)

I've spent a couple of hours trying to find the answer to this, and although there are tutorials all over the 'net none of them work for me (or I am too n00b to understand what they're telling me...)
Anyway, I'm creating users in asp.net using Membership. What I want to do is add the generated UserId to a column in a custom table I've created, to link the stuff in the custom table with the user created in aspnet_Users.
Here's the code I've got for the registration submit button:
Private Sub submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("edinsec").ConnectionString
Dim createStatus As MembershipCreateStatus
Membership.CreateUser(fname.Text, password.Text, email.Text, sq.Text, sa.Text, False, createStatus)
''#Something has to happen here!
Dim insertSQL As String
insertSQL = "INSERT INTO clients (UserId)"
insertSQL &= "VALUES (#userId)"
Using con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand(insertSQL, con)
cmd.Parameters.AddWithValue("#firstname", firstname.Text)
Try
Try
con.Open()
Catch ex As SqlException
MsgBox("Connection Problem - Please Retry Later", 65584, "Connection Error")
End Try
cmd.ExecuteNonQuery()
MsgBox("Thank you for joining us - we will be in touch shortly.", 65600, "Join Up")
Response.Redirect("Default.aspx")
Catch Err As SqlException
MsgBox("Error inserting record - please retry later.", 65584, "Insertion Error")
End Try
con.Close()
End Using
End Sub
As you can see I'm trying to grab the Membership-generated userid and insert it into the clients table. I've tried numerous approaches to grabbing the UserId but none work.
Membership works to create the user, it's just the part afterwards that I'm stuck on.
Any help would be much appreciated :)
I managed it in the end using this code:
Dim userid As Guid = New Guid(Membership.GetUser(username.Text).ProviderUserKey.ToString())
...where username.Text is the content of the username form input, where the user chooses their username.
The relevant parameter line is this:
cmd.Parameters.Add("#UserId", g)
I get a warning about the method I'm using being deprecated, but it works at least!
Membership.CreateUser returns a MembershipUser object. You can get the UserId from that returned object.
MembershipUser user = Membership.CreateUser(...);
Guid userId = (Guid)user.ProviderUserKey;

Resources