Different output from stored procedure in SSMS and ASP.NET - 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!

Related

Error parsing - Insert value Textbox inside database

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());
}

Get User Collection Type Object (Table) as Out Parameter from Oracle stored procedure

I need to get back from an Oracle stored procedure (inside a package) an output parameter defined as user collection type object (a table).
Procedure GetCon (DataRif IN VARCHAR2,Results OUT my_collectiontype)
IS
BEGIN
select my_ObjectType(Col1,Col2)
bulk collect into Results
FROM
TABLE(PMS.myfunc(DataRif ,'31-12-2019');
END;
....
The Function PMS.myfunc returns a my_collectiontype object
In my code (Asp.net 4.0 VB.NET with Oracle ManagedDataAccess Drivers), I've tried
strConn = "Data Source=XE.WORK;User Id=PMS;Password=xxxx"
Dim con As New OracleConnection(strConn)
Dim dt As DataTable = New DataTable()
Dim da As OracleDataAdapter = New OracleDataAdapter()
con.Open()
Dim cmd As New OracleCommand()
cmd.Connection = con
cmd.CommandText = "MySchema.MyPackage.GetCon"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("DataRif", OracleDbType.Varchar2,"23-07-2019", ParameterDirection.Input)
cmd.Parameters.Add("Results", OracleDbType.RefCursor).Direction = ParameterDirection.Output
da.SelectCommand = cmd
cmd.ExecuteNonQuery()
da.Fill(dt)
.....
I get this error
ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'GETCONT'
ORA-06550: line 1, column 7: PL/SQL: Statement ignored"
Sure the out parameter is not a ref cursor but I can't find the right object.
I need to use a stored procedure because I know it's possible execute something like this as simple view
SELECT * FROM TABLE (PMS.myfunc('01-01-2019', '31-12-2019')
but this solution is not the best at the moment.
Thanks in advance.
Solved in this following way that permits to receive a cursor and put it in a dataset.
Create Stored Procedure in Oracle like this
CREATE OR REPLACE PROCEDURE get_emp_rs (p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT DIP_ID,DIP_NAME
FROM TABLE(fn_GetDataFunction('01-01-2019','31-12-2019','15-09-2019'));
END get_emp_rs;
/
In Asp.net
Public Function TestCursor() As DataSet
Dim strConn As String = "Data Source=MYSOURCE;User Id=MYID;Password=xxxxx"
Dim dsReturn As DataSet = Nothing
Try
Using con As New OracleConnection(strConn)
Using sda As New OracleDataAdapter()
Dim cmd As New OracleCommand()
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "get_emp_rs"
cmd.Parameters.Add("p_recordset", OracleDbType.RefCursor).Direction = ParameterDirection.Output
sda.SelectCommand = cmd
Using ds As New System.Data.DataSet("results")
sda.Fill(ds, "MyTableName")
Return ds
End Using
End Using
End Using
Catch ex As Exception
'---------
End Try
End Function

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 - can i store the user's reference to database?

I want to store the reference of customers to database , and when they login , they can view their own reference . but some how i still got some troubles , can you have a look ? and show me the solution , thanks in advance.
Table aspnet_User
![][1]
http://i.stack.imgur.com/2YpEL.jpg
http://i.stack.imgur.com/SGX45.jpg
Table Userinfo, its a FK of table aspnet_User
![][2]
Here is my code :
Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString2").ToString())
conn.Open()
'Customer Reference
Dim chars As String = "1234ABCD"
Dim orderref As String = ""
Dim r As New Random()
Dim i As Integer
For i = 1 To 8
orderref += chars.Substring(r.Next(chars.Length), 1)
Next
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString2").ConnectionString
Dim insertSql As String = "INSERT INTO Userinfo(UserId,HomeTown,HomePage,Orderref) VALUES(#UserId,#HomeTown,#HomePage,#Orderref)"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(insertSql, myConnection)
'myCommand.Parameters.AddWithValue("#UserId", DBNull.Value)
myCommand.Parameters.AddWithValue("#HomeTown", DBNull.Value)
myCommand.Parameters.AddWithValue("#HomePage", DBNull.Value)
myCommand.Parameters.AddWithValue("#Orderref", orderref)
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
it showed this error "Cannot insert the value NULL into column 'UserId', table ' APP_DATA\ASPNETDB.MDF.dbo.Userinfo'; column does not allow nulls. INSERT fails. The statement has been terminated."
Since you are not passing a value for the parameter #UserId, then your INSERT statement when executed against the database uses NULL and the table constraint triggers an error because the column UserId does not allow NULL values.
Uncomment this line:
'myCommand.Parameters.AddWithValue("#UserId", DBNull.Value)
and pass in a real value, something besides DBNull.Value.

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)

Resources