Problem calling a stored procedure from VB.NET - asp.net

I am pretty new to VB and I am not sure why this is not working, basically I am trying to run a stored procedure from my web code. The sp runs just fine in SQL, I've tried it several times so I am sure that is not the problem. I don't want to return any results, I just want to see an "ok" statement if it runs and an error message if it doesn't. The code I am using for the lables (warnings and confirmation) is reused from earlier on the same page, the same goes for the validations (valUpload). I am sure the solution is simple...
Protected Sub RunValidation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RunValidation.Click
Try
Dim bl As New BL.ORG
Dim db As Database = DatabaseFactory.CreateDatabase("MyConnection")
Dim dbCommand As DbCommand
db = DatabaseFactory.CreateDatabase("MyConnection")
dbCommand = db.GetStoredProcCommand("Company.dbo.uspMyStoredProcedure")
dbCommand.CommandTimeout = 300
db.AddInParameter(dbCommand, "ClientID", DbType.String, ddlCompany.SelectedValue)
db.AddInParameter(dbCommand, "startPeriod", DbType.String, ddlStartPeriod.SelectedValue)
db.ExecuteDataSet(dbCommand)
lblWarning.Text = "Please confirm that the <strong>ClientID and startPeriod </strong> are populated in the dropdown list."
lblWarning.Visible = True
lblConfirmation.Visible = False
Catch ex As Exception
valUpload.ErrorMessage = "There has been an unexpected error generating the page<br>(" + Err.Description + ")"
valUpload.IsValid = False
End Try
End Sub

I think the issue here is the line
db.ExecuteDataSet(dbCommand)
From what I can see, the command you want to run is
db.ExecuteNonQuery(dbCommand)
Here is an example site. The code is in C# but I think you can get the basic understanding of it. You could also use a translator on it if you really needed to.
http://msdn.microsoft.com/en-us/magazine/cc188702.aspx#S2

I would rewrite it to something similar to this:
Protected Sub RunValidation_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RunValidation.Click
Using cnn As New SqlClient.SqlConnection("MyConnection")
cnn.Open()
Using cmd As New SqlClient.SqlCommand("Company.dbo.uspMyStoredProcedure", cnn)
cmd.CommandTimeout = 30
cmd.Parameters.Add(New SqlClient.SqlParameter("ClientID", SqlDbType.NVarChar, 50) With {.Value = ddlCompany.SelectedValue})
cmd.Parameters.Add(New SqlClient.SqlParameter("startPeriod", SqlDbType.NVarChar, 50) With {.Value = ddlStartPeriod.SelectedValue})
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
valUpload.ErrorMessage = "There has been an unexpected error generating the page<br>(" + Err.Description + ")"
valUpload.IsValid = False
End Try
lblWarning.Text = "Please confirm that the <strong>ClientID and startPeriod </strong> are populated in the dropdown list."
lblWarning.Visible = True
lblConfirmation.Visible = False
End Using
End Using
End Sub
A few notes:
Wrap as little code as possible in a try-catch. In this case, only the database should be a cause of concern (granted you validated the inputs).
The using statement very neatly disposes your connection and command objects in case of problems.
You probably want to refactor the code even futher, keeping the database-calling section in a separate function/sub, and setting labels and UI messages somewhere else.

Related

Error: "No value given for one or more required parameters" on UPDATE query from ASP.NET

I receive the error
No value given for one or more required parameters
when I try to execute the following code
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim t2 = TextBox2.Text
Dim dbcmd As OleDbCommand
dbcmd = New OleDbCommand("UPDATE login1 SET height ='" + TextBox2.Text + "' WHERE username =" + str, dbcon) //This is the part where the error is ....
dbcon.Open()
dbcmd.ExecuteNonQuery()
dbcon.Close()
End Sub
End Class
I've tried making changes in this statement like using different methods with parameters...but all the code shows the same error.
Using a parameterized query is definitely the way to go, but using named parameters should be discouraged in this context because OleDbCommand objects ignore the parameter names when the CommandType is Text. They only rely on the order in which the parameters appear in the CommandText (ref: here).
Therefore, the preferred approach would be
Using dbcmd As New OleDbCommand(
"UPDATE login1 SET height=? WHERE username=?",
dbcon)
dbcmd.Parameters.AddWithValue("?", TextBox2.Text) ' height
dbcmd.Parameters.AddWithValue("?", str) ' username
dbcmd.ExecuteNonQuery()
End Using
You don't supply the user name properly at the end of the query. But that's not the only problem here. Let me edit the code a bit:
Using dbcon As New OleDbConnection(cString)
dbcon.Open()
Using dbcmd As New OleDbCommand(
"UPDATE login1 SET height = #height WHERE username = #username",
dbcon)
dbcmd.Parameters.AddWithValue("#height", TextBox2.Text)
dbcmd.Parameters.AddWithValue("#username", str)
dbcmd.ExecuteNonQuery()
End Using
End Using
NOTE: the using statement to ensure the objects are disposed property and also, do not share connections. When you need a connection, build it, open it, use it, and dispose it.

how to create session in asp.net using vb

I have a gridview which shows the details of passenger who have booked their ticket
on page load event i have following code.
Label1.Text = Session("Pid").ToString()
Dim Sql As String = "select * from Plist where Pid='" & Label1.Text & "'"
Try
con.ConnectionString = strCon
Dim cm As New SqlClient.SqlCommand(Sql, con)
con.Open()
cm.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
Finally
If con.State = ConnectionState.Open Then
con.Close()
End If
End Try
I am getting this error:
System.NullReferenceException: Object reference not set to an instance of an object.
the session Session("Pid") is null, you should fill it with data before and you also should check the session:
If Session("Pid") IsNot Nothing Then
' write your code
End If
Check all your "SESSIONS" for null before using it...................
And Refer
and also IRequiresSessionState Interface
Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.

ASP.NET - VB.NET - Updating MS_Access table

I'm trying to update a record from an Ms-Access table with VB.NET and ASP.NET. I'm getting 2 errors:
On the web page that's opened I'm getting Thread was being aborted
Web Developer 2010 gives me an error says there's an error in the
UPDATE statement
This is the code so far:
Imports System.Data.OleDb
Partial Class ChangePassword
Inherits System.Web.UI.Page
Protected Sub btnChange_Click(sender As Object, e As System.EventArgs) Handles btnChange.Click
Dim tUserID As String = Session("UserID")
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\WebSite3\db.mdb;")
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [User] where UserID=?", conn)
Dim cmd2 = New OleDbCommand("UPDATE USER SET [Password] = '" + txtConfPass.Text + "' where UserID = '" + tUserID + "'", conn)
cmd.Parameters.AddWithValue("#UserID", tUserID)
Dim read As OleDbDataReader = cmd.ExecuteReader()
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
lblUser.Text = tUserID.ToString
lblUser.Visible = True
If read.HasRows Then
While read.Read()
If txtOldPass.Text = read.Item("Password").ToString Then
cmd2.ExecuteNonQuery()
lblPass.Visible = True
End If
End While
Else
lblPass.Text = "Invalid Password."
lblPass.Visible = True
End If
conn.Close()
lblPass.Text = tUserID.ToString
lblPass.Visible = True
Any help would be appreciated.
Thanks !
First, your cmd2 fails because USER is a reserved word. Enclose in
square brackets as you already do in the first OleDbCommand.
Second, to execute a statement like UPDATE, INSERT, DELETE you call
cmd2.ExecuteNonQuery not ExecuteReader. Don't really needed that call
after the first for cmd.
Third, in the first OleDbCommand (cmd) you use a parameter for
UserID, why in the second one you revert to string concatenation for
user and password? This opens the door to any kind of Sql Injection
Attack.
Fourth, the Using statement assure that every Disposable object
used in your code will be CLOSED thus freeing the memory used by
this commands ALSO IN CASE OF EXCEPTIONS. An example of Using
statement here
(1)
Dim read2 As OleDbDataReader = cmd2.ExecuteReader()
and then
(2)
cmd2.ExecuteNonQuery()
Remove (1) - ExecuteNonQuery should do the update.
USER is a keyword in Access, add brackets the same way you have added in the Select statement. Next time, you are faced with a similar problem, print out the statement as Access would see it and try executing it on the database directly - that will point out the errors accurately.
Please use place holders for the update statement similar to the select statement.

.NET Framework Data Provider for Oracle multiple open connection

I have the below mentioned code in a seperate class file for establishing connection and carry out DB transactions. I have an issue where multiple connections being opened which sometime exceed the connection pool. When I stepped through the code I found that there are codes which call ConnectDB() in a loop without calling DisconnectDB(). But I expected that the condition OraConn.State = ConnectionState.Closed should handle the situation. Somehow the condition is always satisfied hence openning another set of connection. Can you suggest where am I going wrong and also what best practice can be adopted here?
Public Class Connection
Dim Str_conn As String = "Data Source=...; User=...; password=...; Min Pool Size=10; Max Pool Size=500;"
Public OraConn As OracleConnection
Dim cmd As OracleCommand
Dim dr As OracleDataReader
Dim data_adapt As OracleDataAdapter
Dim dt As DataTable
Dim ds As DataSet
Public Sub ConnectDB()
OraConn = New OracleConnection(Str_conn)
If OraConn.State = ConnectionState.Closed Then
OraConn.Open()
End If
End Sub
Public Sub DisconnectDB()
If OraConn.State = ConnectionState.Open Then
OraConn.Close()
End If
End Sub
Public Function get_dataset(ByVal query As String, ByRef ds As DataSet) As DataSet
data_adapt = New OracleDataAdapter(query, OraConn)
data_adapt.Fill(ds)
Return ds
End Function
Public Function get_datareader(ByVal query As String) As OracleDataReader
cmd = New OracleCommand(query, OraConn)
dr = cmd.ExecuteReader()
Return dr
End Function
Public Sub UpdateDB(ByVal query As String)
cmd = New OracleCommand(query, OraConn)
cmd.ExecuteNonQuery()
cmd.Dispose()
End Sub
The class is refered in other classes or directly in the aspx.vb pages like this.
Public Function InsertData(ByVal var1 As String, ByVal var2 As String) As Integer
conn.ConnectDB()
Dim qryInsert As String
qryInsert = " INSERT INTO TABLE VALUES ('" & var1 & "', "
qryInsert = qryInsert & var2 & "')"
Try
conn.UpdateDB(qryInsert)
Catch ex As OracleException
If ex.Code = 1 Then
updData(var1, var2)
ElseIf ex.Code = 2091 Then
msgprompt("Duplicate Unique Key!", "Warning")
End If
Finally
conn.DisconnectDB()
End Try
Return count
End Function
The connection is again opened in function updData(). While I understand that it has to be closed correctly but keeping tab on every developer is not possible. Hence I want to control it directly from the connection class by using the same connection but the condition If OraConn.State = ConnectionState.Closed is not helping.
UPDATE
I have put the code in UpdateDB under a Using block and removed call to ConnectDB and DisconnectDB from function like InsertData(...). It seems that the issue has been resolved. But I would like to know in case of exception will the connection remain open? and also OraConn is a public variable defined outside Using block so will it be disposed of by the GC?
Public Sub UpdateDB(ByVal query As String)
Using OraConn = New OracleConnection(Str_conn)
cmd = New OracleCommand(query, OraConn)
Try
OraConn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw
Finally
cmd.Dispose()
End Try
End Using
End Sub
You must close all the connections as soon as you are done with it, no matter what.
Suggestion:
The best practice for closing the connection is to do it in finally block. So that even if there is any error, catch it (log it if required) in catch block, and then connection will get close in finally block.
UPDATE
You can put one private static counter in your Connection class. When ever ConnectDB() is called you increment this counter and decrement it in every DisconnectDB(). Now in ConnectDB() you check the value of counter, if it exceeds a minimum threshold you throw error, by doing this way; you can come to know idle connection present in your code and refactor it. On production keep this threshold value high or ignore it in code.

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