Multiple user accessing Webservice simultaneously - asp.net

We have a WebMethod created in an ASP.NET 2.0 Web Service (VB), which is accessed throughout the application very frequently. The WebMethod gets the query as a parameter and returns the DataSet. It works fine when the number of users is 1 or 2. If ~30 users are using the system simultaneously, the WebMethod returns the DataSet of a different query. We have tried the synclock (lock in C#) option, but it does not work.
Public Function ExecuteQry(ByVal StrText As String) As DataSet
Dim AdoDs As New DataSet()
Dim SqlDp As New SqlDataAdapter
Dim SqlCmd As New SqlCommand
Dim SqlParam As New SqlParameter
Try
SyncLock AdoDs
MakeConnect()
With SqlCmd
.Connection = SqlCon
.CommandText = "rExecuteQry"
.CommandType = CommandType.StoredProcedure
End With
SqlParam = SqlCmd.Parameters.AddWithValue("#strText", Trim(StrText))
SqlDp.SelectCommand = SqlCmd
SqlDp.Fill(AdoDs)
DisposeConnect()
Return AdoDs
End SyncLock
Catch ex As SqlException
DisposeConnect()
Debug.Write(ex.Message)
Finally
SqlCmd = Nothing
SqlParam = Nothing
End Try
End Function
Below is the stored procedure:
ALTER PROCEDURE [dbo].[rExecuteQry]
#strText Varchar (max)
as
Exec( #StrText)

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

Web asp.net calling SQL stored procedure creating multiple sessions on SQL Server, occasionally, under heavy activity the web app fails

Under heavy usages, the web app occasionally fails. When this happens the only error message I get is
Stored procedure failed
The problem is it works 80 to 90% of the time and only fails when the website is getting multiple hits over a couple of minutes of time, say 150 from six different locations over a two minute interval.
We are using IIS Manager 6.2 on Windows Server 2012 R2 to host the intranet web app that is used for collecting time punches from six pi terminals. The app was created with Visual Studio 2017
Dim sqlConnection1 As New SqlClient.SqlConnection("Data Source=SLDB;Initial Catalog=SyteLine_AWP;Persist Security Info=True;User ID=sa;Password=sqladmin")
Dim cmd As New SqlClient.SqlCommand
Dim parm As New SqlParameter()
Server.ClearError()
Dim ex As Exception = Server.GetLastError
parm.Direction = Data.ParameterDirection.ReturnValue
parm.ParameterName = "ReturnValue"
cmd.Parameters.Add(parm)
cmd.CommandText = "AWP_TimeClock_Web"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
cmd.Parameters.AddWithValue("#VAR_badge_num", badgenum)
cmd.Parameters("#VAR_badge_num").Direction = ParameterDirection.Input
cmd.Parameters.AddWithValue("#VAR_term_id", TermID)
cmd.Parameters("#VAR_term_id").Direction = ParameterDirection.Input
cmd.Parameters.Add("#VAR_emp_name", SqlDbType.VarChar, 40).Value = ""
cmd.Parameters("#VAR_emp_name").Direction = ParameterDirection.Output
cmd.Parameters.Add("#VAR_error", SqlDbType.Int, 1).Value = 0
cmd.Parameters("#VAR_error").Direction = ParameterDirection.Output
sqlConnection1.Open()
cmd.ExecuteNonQuery()
As I stated earlier, 80 to 90% of the time this works fine. During heavy use any number of the apps freeze, with some or all eventually dropping with the error message "stored procedure failed". I suspect the issue is not with the stored procedure but with the ability to connect to the server. Although I can rule out nothing at this time.
I changed to ASP.NET VB code to include the Using and try/catch command. The web app has been working without issue since moved to live.
Dim sqlConnection1 As New SqlClient.SqlConnection("Data Source=SLDB;Initial catalog=SyteLine_AWP;Persist Security Info=True)
Dim cmd As New SqlClient.SqlCommand
Dim parm As New SqlParameter()
Server.ClearError()
Dim ex As Exception = Server.GetLastError
parm.Direction = Data.ParameterDirection.ReturnValue
parm.ParameterName = "ReturnValue"
cmd.Parameters.Add(parm)
cmd.CommandText = "AWP_TimeClock_Web"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
cmd.Parameters.AddWithValue("#VAR_badge_num", badgenum)
cmd.Parameters("#VAR_badge_num").Direction = ParameterDirection.Input
cmd.Parameters.AddWithValue("#VAR_term_id", TermID)
cmd.Parameters("#VAR_term_id").Direction = ParameterDirection.Input
cmd.Parameters.Add("#VAR_emp_name", SqlDbType.VarChar, 40).Value = ""
cmd.Parameters("#VAR_emp_name").Direction = ParameterDirection.Output
cmd.Parameters.Add("#VAR_error", SqlDbType.Int, 1).Value = 0
cmd.Parameters("#VAR_error").Direction = ParameterDirection.Output
Using cmd
Try
sqlConnection1.Open()
cmd.ExecuteNonQuery()
Catch err As Exception
error_code = "5"
End Try
End Using
sqlConnection1.Close()

getting data from database asp.net

i am trying to get data from ms access database using this code but i can not this is my code is this correct
Dim query As String = "SELECT [data] FROM tabless WHERE user = '" & user.Text & "'"
Using connection As New OleDbConnection(connectionString)
Dim cmd As New OleDbCommand(query)
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(query, connection)
Dim com As New OleDbCommand(query, connection)
connection.Open()
'on the line below I get an error: connection property has not been initialized
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
Label1.Text = (reader(0).ToString())
End While
reader.Close()
End Using
Database
|data|
asl
trying to get data from database and trying to show it in a label is this possible
You never associated cmd with the connection, and you never use com or adapter. This is the sort of thing you can figure out by stepping through your code line by line and inspecting the state of it.
Dim query As String = "SELECT [data] FROM tabless WHERE user = '" & user.Text & "'"
Using connection As New OleDbConnection(connectionString)
Dim cmd As New OleDbCommand(query, connection)
connection.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
While reader.Read()
Label1.Text = (reader(0).ToString())
End While
reader.Close()
End Using
Also, your code is vulnerable to a SQL Injection Attack. You should not be concatenating strings together to form your queries. You should instead use parameterized queries.

oRecordset in ASP.NET mySQL

I have this mySQL code that connects to my server. It connects just fine:
Dim MyConString As String = "DRIVER={MySQL ODBC 3.51 Driver};" & _
"SERVER=example.com;" & _
"DATABASE=xxx;" & _
"UID=xxx;" & _
"PASSWORD=xxx;" & _
"OPTION=3;"
Dim conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "select * from userinfo WHERE emailAddress = '" & theUN & "'""
MyCommand.ExecuteNonQuery()
conn.Close()
However, i have an old Classic ASP page that uses "oRecordset" to get the data from the mySQL server:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=example.com; PORT=3306; DATABASE=xxx; USER=xxx; PASSWORD=xxx; OPTION=3;"
sqltemp = "select * from userinfo WHERE emailAddress = '" & theUN & "'"
oRecordset.Open sqltemp, oConnection,3,3
And i can use oRecordset as follows:
if oRecordset.EOF then....
or
strValue = oRecordset("Table_Name").value
or
oRecordset("Table_Name").value = "New Value"
oRecordset.update
etc...
However, for the life of me, i can not find any .net code that is similar to that of my Classic ASP page!!!!!
Any help would be great! :o)
David
This is what you have to do:
instead of MyCommand.ExecuteNonQuery you should use MyCommand.ExecuteQuery and assign it to DataReader.
Check out this sample:
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()
'declaring the objects
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection. you need to provide password for sql server
Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
HTH
Dim conn As OdbcConnection = New OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=xxx.com; DATABASE=xxx; UID=xxx; PASSWORD=xxx; OPTION=3;")
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "SELECT * FROM userinfo"
Dim rst = MyCommand.ExecuteReader()
While rst.Read()
response.write(rst("userID").ToString())
End While
conn.Close()
Dim email As String = "anyone#anywhere.com"
Dim stringValue As String
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql = "Select ... From userInfo Where emailAddress = #Email"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
Dim reader As OdbcDataReader = cmd.ExecuteReader()
While reader.Read()
stringValue = reader.GetString(0)
End While
End Using
conn.Close()
End Using
'To do an Update
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Update userInfo Set Column = #Value Where PK = #PK"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
cmd.ExecuteNonQuery()
End Using
End Using
'To do an Insert
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Insert userInfo(Col1,Col2,...) Values(#Value1,#Value2...)"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Col1", value1)
cmd.Parameters.AddWithValue("#Col2", value2)
...
cmd.ExecuteNonQuery()
End Using
End Using
First, even in ASP Classic, it is an absolutely horrid approach to concatenate a value directly into a SQL statement. This is how SQL Injection vulnerabilities happen. You should always sanitize values that get concatenated into SQL statements. In .NET, you can use parametrized queries where you replace the values that go into your query with a variable that begins with an # sign. You then add a parameter to the command object and set your value that way. The Command object will sanitize the value for you.
ADDITION
You mentioned in a comment that your ASP Classic code is shorter. In fact, the .NET code is shorter because there are a host of things happening that you do not see and have not implemented in your ASP Classic code. I already mentioned one which is sanitizing the inputs. Another is logging. Out of the box, if an exception is thrown, it will log it in the Event Log with a call stack. To even get a call stack in ASP Classic is a chore much less any sort of decent logging. You would need to set On Error Resume Next and check for err.number <> 0 after each line. In addition, without On Error Resume Next, if an error is thrown, you have no guarantee that the connection will be closed. It should be closed, but the only way to know for sure is to use On Error Resume Next and try to close it.
Generally, I encapsulate all of my data access code into a set of methods so that I can simply pass the SQL statement and the parameter values and ensure that it is called properly each time. (This holds true for ASP Classic too).

database search function

i want to search a record from sql database searching by first name so im using a function in the data layer but it is not working please correct me where i went wrong here is my function:
Public Function searchCustomer(ByVal custFname As String) As DataTable
Dim tabletdata As New DataTable
Dim conn As New SqlConnection(con_string)
conn.Open()
Dim dCmd As New SqlCommand("selectCustomerByFname", conn)
dCmd.CommandType = CommandType.StoredProcedure
Try
dCmd.Parameters.AddWithValue("#Cust_Fnam", custFname)
'dCmd.ExecuteNonQuery()
Dim dadaptr As New SqlDataAdapter(dCmd)
dadaptr.SelectCommand = dCmd
dadaptr.SelectCommand.ExecuteNonQuery()
dadaptr.Fill(tabletdata)
Return tabletdata
Catch
Throw
Finally
dCmd.Dispose()
conn.Close()
conn.Dispose()
End Try
End Function
Fill method opens and close connection implicitly. Fill Method
SUMMARY: The Fill method retrieves
rows from the data source using the
SELECT statement specified by an
associated SelectCommand property. The
connection object associated with the
SELECT statement must be valid, but it
does not need to be open. If the
connection is closed before Fill is
called, it is opened to retrieve data,
then closed. If the connection is open
before Fill is called, it remains
open.
Public Function searchCustomer(ByVal custFname As String) As DataTable
Dim tabletdata As New DataTable
Dim conn As New SqlConnection(con_string)
Dim dCmd As New SqlCommand("selectCustomerByFname", conn)
dCmd.CommandType = CommandType.StoredProcedure
dCmd.Parameters.AddWithValue("#Cust_Fnam", custFname)
Dim dadaptr As New SqlDataAdapter(dCmd)
dadaptr.SelectCommand = dCmd
dadaptr.Fill(tabletdata)
Return tabletdata
End Function

Resources