Error parsing - Insert value Textbox inside database - asp.net

I have this form ASP.NET that have two textbox and a label, where the user enters only the expiration date in the last textbox, while the others are inserted automatically if the user clicks on another button inside the repeater where the customer code and company name are found.
The problem is that I created a class to do the insertion: I used a stored procedure for the insertion and I used the query parameterization.
When I parse the code and date it gives me 0 and a default date as a result, while my goal is to insert them into a table inside a db and then have it displayed inside the repeater.
P.S. I add that for reading the data I have another class with another stored procedure and that I have some values ​​that are inside another table (the code and the name of the company).
This is the method:
Public Sub INSERT_EXP_DATE_TABLE()
Dim id_customer As Integer
Dim exp_date As Date
Try
cmd.Connection = cn
cmd.CommandType = CommandType.StoredProcedure
MyParm = cmd.Parameters.Add("#COD_CUSTOMER", SqlDbType.Int)
If (Integer.TryParse(txt_COD_CUSTOMER.Text, id_customer)) Then
MyParm.Value = id_customer
Else
MsgBox("customer not found", vbCritical)
End If
MyParm = cmd.Parameters.Add("#COMPANY_NAME", SqlDbType.NVarChar)
MyParm.Value = lbl_COMPANY_NAME.Text.ToString
MyParm = cmd.Parameters.Add("#EXP_DATE", SqlDbType.Date)
If (Date.TryParse(txt_EXP_DATE.Text, exp_date)) Then
MyParm.Value = exp_date
Else
MsgBox("Exp Date not found", vbCritical)
End If
cmd.CommandText = "LST_INSERT_TABLE_01"
cmd.Connection.Open()
cmd.ExecuteNonQuery()
MsgBox("Date registred", vbInformation)
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
End Sub
And this is the stored procedure:
#ID_CUSTOMER int,
#COMPANY_NAME varchar(50),
#EXP_DATE date,
AS
BEGIN
INSERT INTO TABLE
(
ID_CUSTOMER,
COMPANY_NAME,
EXP_DATE,
)
VALUES(
#ID_CUSTOMER,
#COMPANY_NAME,
#EXP_DATE,
)
END

Keep your connection local to the method where it is used. Connections use unmanaged resources so they include a .Dispose method which releases these resources. To ensure that the database objects are closed and disposed use Using...End Using blocks.
Do you parsing before you start creating database objects. Exit the sub so the user has a chance to correct the problem.
Side note: I don't think a message box will work in an asp.net application.
You set up the company name parameter as an NVarChar but your stored procedure declares it as a VarChar. Which is correct?
It is not necessary to call .ToString on a .Text property. A .Text property is already a String.
You are providing a parameter called "#COD_CUSTOMER" but your stored procedure does not have such parameter.
Public Sub INSERT_EXP_DATE_TABLE()
Dim id_customer As Integer
If Not Integer.TryParse(txt_COD_CUSTOMER.Text, id_customer) Then
MsgBox("Please enter a valid number.", vbCritical)
Exit Sub
End If
Dim exp_date As Date
If Not Date.TryParse(txt_EXP_DATE.Text, exp_date) Then
MsgBox("Please enter a valid date.")
Exit Sub
End If
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("LST_INSERT_TABLE_01", cn)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
.Add("#ID_CUSTOMER", SqlDbType.Int).Value = id_customer
.Add("#COMPANY_NAME", SqlDbType.VarChar, 50).Value = lbl_COMPANY_NAME.Text
.Add("#EXP_DATE", SqlDbType.Date).Value = exp_date
End With
Try
cn.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Sub

{
string CN = Interaction.InputBox("Enter Company Name","Customer","",-1,-1);
string Cname = Interaction.InputBox("Enter Customer Name", "Customer", "", -1, -1);
SqlConnection con = new SqlConnection(#"Data Source=Adnan;Initial Catalog=Production;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO hello(Company_Name,Customer_name ) VALUES ( #Company_Name,#Customer_name )");
cmd.Connection = con;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#Company_Name", CN.ToString() );
cmd.Parameters.AddWithValue("#Customer_name", Cname.ToString());
}

Related

Different output from stored procedure in SSMS and ASP.NET

I created a stored procedure to include a new user for my system. Parameters are: Name, Mail and Password (all varchar). The stored procedure first checks if the mail is already in the database. If not, then the information in added to the table. At the end, the output is a table with the user data.
CREATE PROCEDURE [dbo].[user_new]
(#name VARCHAR(50),
#mail VARCHAR(50),
#password VARCHAR(100)
)
AS
BEGIN
SET NOCOUNT ON
DECLARE #exist INT
SELECT #exist = COUNT([id])
FROM [dbo].[User]
WHERE [mail] = #mail
IF #exist = 0
INSERT INTO [dbo].[User] ([name], [mail], [password])
VALUES (#name, #mail, #password)
SELECT
#exist AS [exist], [id], [name], [mail]
FROM
[dbo].[User]
WHERE
[mail] = #mail
END
GO
When I execute the stored procedure in SSMS, everything works fine: when I insert a new mail, field [exist] returns 0. When I insert a mail that already exist, field [exist] returns 1. So far, so good.
When I execute the stored procedure from my .NET application (which has a lot of other calls that are working fine), the error happen: no matter if I try to add a new or an existing mail, [exist] always returns 1. I tried to change the logic several times, but I always get the wrong result.
Here is the .NET code:
Public Function api_v2_player_new(<FromBody> s As User) As Object
Dim arrParameters(,) As String = {{"#name", s.Name}, {"#mail", s.Mail}, {"#password", s.Password}}
Dim dtc As Data.DataTableCollection = SQL.Execute("dbo.user_new", arrParameters)
Return SQL.toJson(dtc(0))
End Function
Public Class SQL
Public Shared Function runStoredProcedure(ByVal cmd As SqlCommand) As Data.DataTableCollection
Dim spName As String = cmd.CommandText.ToString
cmd.CommandTimeout = 120
Dim cs As String = System.Configuration.ConfigurationManager.ConnectionStrings("csKickerliga").ConnectionString
Dim connection As SqlConnection = Nothing
connection = New SqlConnection(cs)
Dim dt As DataTable = New DataTable()
cmd.Connection = connection
connection.Open()
Dim adp As New SqlDataAdapter(cmd)
Dim ds As DataSet = New DataSet()
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Return ds.Tables
connection.Close()
End Function
Shared Function Execute(spName As String, arrParameters(,) As String) As Data.DataTableCollection
Dim cmd As SqlCommand = New SqlCommand(spName)
cmd.CommandType = CommandType.StoredProcedure
With cmd.Parameters
For i = 0 To (arrParameters.Length / 2) - 1
.AddWithValue(arrParameters(i, 0), arrParameters(i, 1))
Next
End With
Dim dtc = runStoredProcedure(cmd)
Return dtc
End Function
Shared Function toJson(dt As DataTable) As List(Of Object)
Dim oList As New List(Of Object)
Dim o As New Dictionary(Of String, Object)
Dim data As Object
For Each r As DataRow In dt.Rows
o = New Dictionary(Of String, Object)
For Each c As DataColumn In dt.Columns
If IsNumeric(r(c.ColumnName)) Then
If Not r(c.ColumnName).ToString.Contains(".") Then
data = CInt(r(c.ColumnName))
Else
data = r(c.ColumnName).ToString
End If
Else
data = r(c.ColumnName).ToString
End If
o.Add(c.ColumnName, data)
Next
oList.Add(o)
Next
Return oList
End Function
End Class
Found the issue. The code was executing the stored procedure twice:
cmd.ExecuteNonQuery()
adp.Fill(ds, spName)
Therefore on the recond run the record already existed because it was created on the first run. I removed one of the lines and now it's working!

Get Oracle.DataAccess.Types.OracleClob instead of actual value

I'm having an issue, I'm calling a procedure on oracle 11g, the prucedure receives a clob and responds with a different CLOB, a VARCHAR2 and a Number. The procedure is called from a ASP.NET (on Visual Basic) webpage using oracle data provider (ODP.NET), I can call the procedure successfully, view the VARCHAR2 and NUMBER returned values, but when I try to see the returned value of the returning CLOB all I get is "Oracle.DataAccess.Types.OracleClob" instead of a expecting XML
I know the returned XML is generated because on the store procedure I create a txt file where it shows the expected result
My code it's pretty simple right now:
Function Index() As String 'ActionResult
Dim xml_message As String
Dim oradb As String = "Data Source=127.0.0.1;User Id=id;Password=pass;"
Dim conn As New OracleConnection(oradb)
Dim oracleDataAdapter As New OracleDataAdapter
oracleDataAdapter = New OracleDataAdapter()
Dim cmd As New OracleCommand
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Common.GetDriverPoints"
cmd.BindByName = True
Dim driver_input As New OracleParameter()
driver_input = cmd.Parameters.Add("p_driver", OracleDbType.Clob)
driver_input.Direction = ParameterDirection.Input
driver_input.Value = <THE_SENDED_XML_VALUE>
Dim driver_output As New OracleParameter()
driver_output = cmd.Parameters.Add("p_output", OracleDbType.Clob)
driver_output.Direction = ParameterDirection.Output
Dim error_flag As New OracleParameter()
error_flag = cmd.Parameters.Add("p_Return", OracleDbType.Int16)
error_flag.Direction = ParameterDirection.Output
Dim error_desc As New OracleParameter()
error_desc = cmd.Parameters.Add("p_ReturnDesc", OracleDbType.Varchar2, 100)
error_desc.Direction = ParameterDirection.Output
conn.Open()
cmd.ExecuteNonQuery()
Dim output As String
output = driver_output.Value.ToString() 'This only returns Oracle.DataAccess.Types.OracleClob
conn.Close()
conn.Dispose()
Return output
End Function
Also, the generated xml is around 55Kb, sometimes it's bigger
Thank you
I manage to find the answer, In case someone have the same problem, basically what has to be done is create another clob, used only on for vb.net, that clob will receive the value of the parameter output from the procedure, then cast to a string variable the local clob.
Example:
Dim output As String
Dim myOracleClob As OracleClob = driver_output.Value
output = System.Convert.ToString(myOracleClob.Value)
Now the "output" variable holds the actual message of the clob.
Hope this helps anybody with the same problem.

ASP.NET VB.NET -- SQL UPDATE Command Not Working

I have been working on this particular issue for a couple of days, and scouring over SO, MSDN and other google searches has not proven to be of any use. I am trying to make a simple update to a SQL table. My SELECT and INSERT statements all work fine, but for some reason, this update will not work. I have set breakpoints and stepped through, and the code seems to be working fine -- the Catch ex as Exception is never reached after the .ExecuteNonQuery() fires off.
Could anyone give me an idea of why I've been unable to get a SQL update?
Protected Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim currentUser = Membership.GetUser(User.Identity.Name)
Dim username As String = currentUser.UserName
Dim userId As Guid = currentUser.ProviderUserKey
UserNameTextBox.Text = username
' Get Root Web Config Connection String so you don't have to encrypt it
Dim rootWebConfig As System.Configuration.Configuration
rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")
Dim connString As System.Configuration.ConnectionStringSettings
connString = rootWebConfig.ConnectionStrings.ConnectionStrings("LocalSqlServer")
Dim conn As String = connString.ToString
Dim commandString As String = "UPDATE UserDetails SET FirstName ='" + FirstNameTextBox.Text + "' WHERE UserId ='" + userId.ToString + "'"
Dim fname As String = FirstNameTextBox.Text
Dim commandText As String = "UPDATE UserDetails SET FirstName=#firstname WHERE UserId=#UID;"
Using connection As New SqlConnection(conn)
Dim command As New SqlCommand(commandText, connection)
command.CommandType = CommandType.Text
' Add UserId parameter for WHERE clause.
command.Parameters.Add("#UID", SqlDbType.UniqueIdentifier).Value = userId
' command.Parameters("#UID").Value = userId
' command.Parameters.AddWithValue("#UID", userId)
' Use AddWithValue to assign Demographics.
command.Parameters.Add("#firstname", SqlDbType.VarChar, 255).Value = fname
'command.Parameters.AddWithValue("#firstname", fname)
' command.Parameters("#firstname").Value = FirstNameTextBox.Text.ToString
Try
connection.Open()
command.ExecuteNonQuery()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Console.WriteLine("RowsAffected: {0}", rowsAffected)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
connection.Close()
End Try
End Using
End Sub
You're running "command.ExecuteNonQuery()" twice, meaning the second execution will likely return 0 rows affected since you already updated what you needed to update, and that's what you're assigning to rowsAffected. Are you sure the UPDATE isn't occurring?
Edit: Re your comment, did you check for IsPostBack when you LoadUser? If not, when you click SaveButton, you're going to reload the existing values, and then you'll be updating with those existing values.

Adding Session Variable as OleDbParameter - running into error "

I am using a custom ASP.NET control that I found here: http://www.codeproject.com/Articles/5347/DataCalendar
I have used one of the templates in the source file download-able from the page above as a starting point for my custom calendar. My aim is to only display events that the current user has created. I am doing this by creating a session variable called "userName" and I am parameterizing it in a query like so:
Function GetEventData(startDate As DateTime, endDate As DateTime) As DataTable
'--read data from an Access query
Dim con As OleDbConnection = GetConnection()
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.Connection = con
cmd.Parameters.AddWithValue("#currentUser", Session("currentuser"))
cmd.CommandText = String.Format("Select EventDate, CreatedBy, Count(*) From EventInfo Where (CreatedBy = #currentUser) and EventDate >= #{0}# And EventDate <= #{1}# Group By EventDate", _
startDate, endDate)
Dim ds As DataSet = New DataSet()
Dim da As OleDbDataAdapter = New OleDbDataAdapter(cmd)
da.Fill(ds)
con.Close()
Return ds.Tables(0)
End Function
Unfortunately I am receiving this error:
Parameter[0] '' has no default value.
I have ensured that I am logged in so it is not a problem of there being no value for User.Identity.Name (I don't think). I am creating the session variable in the Page Load sub:
Sub Page_Load(o As Object, e As EventArgs)
Session("currentuser") = User.Identity.Name
End Sub
So, what's going wrong?
From MSDN :
The OLE DB.NET Provider does not support named parameters for passing
parameters to an SQL Statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text. In this case, the
question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the
OleDbParameterCollection must directly correspond to the position of
the question mark placeholder for the parameter.
Try:
cmd.CommandText = String.Format("Select EventDate, CreatedBy, Count(*) From EventInfo Where ([CreatedBy = ?]) and EventDate >= #{0}# And EventDate <= #{1}# Group By EventDate,CreatedBy", startDate, endDate)

ASP.NET - Could not find stored procedure

I've been searching the depths of the internet and all the solutions I found did not solve this problem.
I am using Visual Web Developer 2010 Express with SQL Server 2008, using VB.
I am trying to execute a stored procedure to insert some data coming from a textbox control to a database, if the id doesn't exist it inserts both the id given in the textbox and the current date (time_scanned_in), if the id exists already, it will insert the current datetime in the [time_scanned_out] column, if all 3 fields in the db are full, it will return #message = 1.
Here is the sql stored procedure:
ALTER PROCEDURE dbo.InsertDateTime
#barcode_id nchar(20),
#message char(1) = 0 Output
AS
BEGIN
if not exists(select * from tblWork where barcode_id = #barcode_id)
begin
INSERT INTO [tblWork] ([barcode_id], [time_scanned]) VALUES (#barcode_id, GetDate())
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NOT NULL )
begin
SET #message=1
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NULL)
begin
UPDATE [tblWork] SET [time_scanned_out] = GetDate() WHERE [barcode_id] = #barcode_id
end
RETURN #message
end
If I execute this (by right clicking on the SP), it works flawlessly and returns the values when all fields have been filled.
But when executed through the vb code, no such procedure can be found, giving the error in the title.
Here is the vb code:
Dim opconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim sqlConnection1 As New SqlConnection(opconn)
Dim cmd As New SqlCommand
Dim returnValue As Object
cmd.CommandText = "InsertDateTime"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
With cmd.Parameters.Add(New SqlParameter("#barcode_id", TextBox.Text))
End With
With cmd.Parameters.Add(New SqlParameter("#message", SqlDbType.Char, 1, Label3.Text))
End With
returnValue = cmd.ExecuteScalar()
sqlConnection1.Close()
Note, I haven't done the code for the return part yet, will do that once I get it to locate the SP.
Tried listing all objects with the sys.objects.name for each of the databases in a gridview, it listed everything but the stored procedure I want.
Why is this, any ideas? Would be much appreciated, spent hours trying to find a solution.
If anyone needs any more code or information feel free to ask.
try cmd.parameters.clear() first and then start adding parameters in cmd object. also instead of cmd.executescaler(), try cmd.executenonquery or cmd.executeReader()
Try this
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
SqlParameter prmOut = cmd.Parameters.Add("#message",SqlDbType.Char, 1)
prmOut.Value = Label3.Text
prmOut.Direction = ParameterDirection.InputOutput
cmd.ExecuteNonQuery()
returnValue = prmOut.Value.ToString()
Recreated the whole project with a whole new database, copied all the same code, and now it all works flawlessly! Still have no idea what was wrong, but thank you all, you were all prompt and knowledgable.
Here was the final VB code for anyone who's interested:
Dim myConnection As New SqlConnection(opconn)
Dim cmd As New SqlCommand()
Dim myReader As SqlDataReader
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = myConnection
cmd.CommandText = "InsertTimes"
cmd.Parameters.AddWithValue("#message", OleDbType.Integer)
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
cmd.Parameters("#message").Direction = ParameterDirection.Output
Try
myConnection.Open()
myReader = cmd.ExecuteReader()
Dim returnMessage As String = cmd.Parameters("#message").Value
If returnMessage = 1 Then
label_confirmation.Text = "Record successfully submitted!"
TextBox.Text = ""
ElseIf returnMessage = 2 Then
label_confirmation.Text = "A finish time already exists for the record '" & TextBox.Text & "', would you like to override the finish time anyway?"
button_yes.Visible = True
button_no.Visible = True
ElseIf returnMessage = 3 Then
label_confirmation.Text = "Record submitted, work operation status complete!"
TextBox.Text = ""
End If
Catch ex As Exception
label_confirmation.Text = ex.ToString()
Finally
myConnection.Close()
End Try

Resources