Passing a Session.Item to a MySQL query - asp.net

I have a aspx web page that has a session variable:
Dim UserName As String = CType(Session.Item("UserName"), String)
I am attempting to include this variable in the MySQL query of a SqldataSource for a Databound GridView control:
Dim Sql As String = "SELECT DeviceDescription, DeviceType, DeviceID
FROM validate WHERE ClientID='" & UserName & "'"
However, this does not work.
How do you pass/include this session variable in the DataSource of the GridView?

Related

Parameterizing sql in asp

I'm not terribly familiar with asp, but I have one project with a page of it.
<%
'declare the variables
Dim Connection
Dim ConnString
Dim Recordset
Dim SQL
Dim userName
userName = Request.Form("userName")
'define the connection string, specify database driver
ConnString="JJJJJ"//connection information
'declare the SQL statement that will query the database
SQL = "SELECT info AS Lunch, "
SQL = SQL & "FROM dbo.AgentActivityLog WHERE UserId = '" & userName & "'
'create an instance of the ADO connection and recordset objects
Set Connection = Server.CreateObject("ADODB.Connection")
Set Recordset = Server.CreateObject("ADODB.Recordset")
'Open the connection to the database
Connection.Open ConnString
'Open the recordset object executing the SQL statement and return records
Recordset.Open SQL,Connection
'first of all determine whether there are any records
If Recordset.EOF Then
Response.Write("No records returned.")
Else
'process record
Next
Recordset.MoveNext
Loop
End If
'close the connection and recordset objects to free up resources
Recordset.Close
Set Recordset=nothing
Connection.Close
Set Connection=nothing
%>
How do I parameterize the username? I have no way to debug, no knowledge of how this language works, so whatever I tried failed and I have no idea why.
I would suggest you look at the Answer on following link as it will fill in the answers you seek:
VBA, ADO.Connection and query parameters
From the code provided critical missing piece is the ADODB.Command for the SQL to actually be run and to add the parameter the query you would :
Set Param = Command.CreateParameter("#userid",adVarChar,adParamInput)
Param.Value = userName
Command.Paramters.Append Param

Checking if there is an exception coming from the server

I have an ASP.NET web application written in vb.net. I have uploaded the application on a web server in the wwroot folder and once I type in the URL with a QueryString, on page_Load it should request that QueryString and store it in the database once in Table1 and another in Table2. Well it is inserting the QueryString to Table 1 but not to Table2. The insertion code is within a Try Catch block but the problem is that I have no idea how to display a server MsgBox with the exception on the client-side.
I have also tried writing a txtFile containing any ex.message on the WebServer itself, but with no luck, even without an exception firing, the txtFile is not created I guess its a path issue. Whether to write the physical path or virtual path both tested without luck.
I am really desperate to know in anyway possible why its inserting the QueryString to Table1 and not Table2.
I am using a class.vb to insert the Querystring. On the main page, I request the QueryString which is a variable (changing) table name (Table2), pass it to a function defined in class.vb and then apply an Insert statement for a predefined un-changing table (Table1) and also using the retrieved QueryString (Table2) name to insert a date and time to both tables.
On MainPage.aspx:
Dim classOBJ AS new Projet.class1
classOBJ.Fun(Request.QueryString("Table"))
In Class1.vb:
Public Sub Fun(ByVal value As String)
Dim date_T As Date = Date.Today
Try
Using myconn As New SqlConnection(ConnString)
myconn.Open()
Dim cmd1 = New SqlCommand("INSERT INTO Table1 (Date_T,Time_T) values (#paramdate, #paramtime)", myconn)
cmd1.Parameters.AddWithValue("#paramdate", date_T)
cmd1.Parameters.AddWithValue("#paramtime", Now().ToString("HH:mm:ss"))
cmd1.ExecuteNonQuery()
cmd1.Dispose()
Dim cmd2 = New SqlCommand("Insert into [" & value & "] (Date_T, Time_T) values (#paramdate, #paramtime)", myconn)
cmd2.Parameters.AddWithValue("#paramdate", date_T)
cmd2.Parameters.AddWithValue("#paramtime", Now().ToString("HH:mm:ss"))
cmd2.ExecuteNonQuery()
cmd2.Dispose()
myconn.Close()
End Using
I am using this notation [ ] because Table's 2 name is a number.

ASP.NET / VB.NET : Generate Insert Command

I have all of my form variables in my codebehind, they were all retrieved using "Request.Form".
As Far as I Know..If I use the SQLDataSource to do this I have to use ASP.NET Controlls(which I do not want).
INSERT INTO Orders(FirstName, LastName, Email, PhoneNumber, Address, City, State, ZipCode, PaymentMethod, PromoCode, OrderStatus, Tracking, PPEmail, SubmissionDate) VALUES (#FirstName, #LastName, #Email, #Phone, #Address, #City, #State, 11111, #PaymentMethod', '0', 'New Order - Pending', '0', #PPEMAIL, #Date)
CodeBehind
Dim fPrice As String = CType(Session.Item("Qprice"), String)
Dim DeviceMake As String = CType(Session.Item("Make"), String)
Dim PaymentMethod As String = Request.Form("Payment Type")
Dim DeviceModel As String = CType(Session.Item("Model"), String)
Dim DeviceCondition As String = CType(Session.Item("Condition"), String)
Dim SubmissionDate As String = Date.Now.ToString
Dim FirstName = Request.Form("First")
Dim LastName = Request.Form("Last")
Dim City = Request.Form("City")
Dim Phone = Request.Form("Phone")
Dim Address = Request.Form("Address")
Dim State = Request.Form("State")
Dim Zip = Request.Form("Zip")
Dim Email = Request.Form("EMail")
Is there a way I can attatch my variables to the insert statment generated by the SQLDatasource, without having to manually code the parameters?
You could use FormParameter. This doesn't require any ASP.NET control so far I'm aware.
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind %>"
selectcommand="SELECT CompanyName,ShipperID FROM Shippers"
insertcommand="INSERT INTO Shippers (CompanyName,Phone) VALUES (#CoName,#Phone)">
<insertparameters>
<asp:formparameter name="CoName" formfield="CompanyNameBox" />
<asp:formparameter name="Phone" formfield="PhoneBox" />
</insertparameters>
</asp:sqldatasource>
Pay special attention to Microsoft warning in relation to this mechanism
The FormParameter does not validate the value passed by the form element in any way; it uses the raw value. In most cases you can validate the value of the FormParameter before it is used by a data source control by handling an event, such as the Selecting, Updating, Inserting, or Deleting event exposed by the data source control you are using. If the value of the parameter does not pass your validation tests, you can cancel the data operation by setting the Cancel property of the associated CancelEventArgs class to true.
Its probably better that you forcibly attach the parameters. As you are getting your values from Form and Session (ick), parameterizing the SQL will give you some measure of protection.
You may want to explore code generation (A-la T4), this way you can point the codegen at a proc/table and it will generate the vb code to call it, attach the params and execute the statement.

asp question ADODB.Recordset and calling a procedure

I have to make an quick update on a legacy asp page never really having done anything with classical asp want to check if this is valid.
Can I do this:
set conn = server.CreateObject("ADODB.Connection")
conn.Open ("connection string info")
Set rsIdent = server.CreateObject("ADODB.Recordset")
SQL = "EXEC procedureName #sParam = '" & someVariable & "'"
rsIdent.Open SQL, conn
iSome_ID = rsIdent.Fields("ident_value")
rsIdent.Close()
Set rsIdent = nothing
Where procedureName is a stored procedure that accepts a paramter, does some processing and returns a single record in a column called "ident_value"?
#Curtis: See How to call SQL Server stored procedures from ASP.

How to fetch user details by user name in multilingual website in asp.net

In my multilingual website i select arabic language.
I created a user from registration page.
Now if i login with that username following error comes:
Failed to convert parameter value from a String to a Int64.
I have created stored procedure given below:
SQL:
CREATE PROCEDURE [dbo].[UserLogin]
#UserName NVARCHAR(100)
AS
BEGIN
SELECT * FROM Users WHERE UserName = #UserName
END
ASPX CODE BEHIND:
Dim UserName As String = "N'" & txtLogin.Text & "'"
Dim _dtLogin As DataTable = oUser.UserLogin(UserName)
BUSINESS LOGIC:
Public Function UserLogin(ByVal UserName As String) As DataTable
_dbCommand = _database.GetStoredProcCommand("UserLogin")
_database.AddInParameter(_dbCommand, "UserName", SqlDbType.NVarChar, UserName)
_Dt = _database.ExecuteDataSet(_dbCommand).Tables(0)
End Function

Resources