Storing a Dictionary to a Session - asp-classic

I created this function but it seems to give me a problem. I want to store a dictionary into an Session variable so I can access the dictionary throughout the website. I keep getting the error Object required: DictionaryObject or it will say This key already exist in the dictionary. Can someone please tell me what I am doing wrong?
I did look storing dictionary in session at this posting but didn't really fit what I am trying to do!
Function LoadPermissions()
Dim SQLString
SQLString ="SELECT datafields here... FROM " & TBL_employees_permissions & " AS p WHERE p.eid = '" & Clng(12) & "';"
If IsObject(Session("dicPermissions")) = True Then
Set dicPermissions = Session("dicPermissions")
Else
Set dicPermissions = Server.CreateObject("Scripting.Dictionary")
End If
db_conn conn, rs '
Set myRS = conn.Execute (SQLString)
For each item in myRS.Fields
If IsObject(Session("dicPermissions")) = True AND DictionaryObject.Exists(Trim(item.Name)) = False Then
dicPermissions.Add Trim(item.Name), Trim(myRS(item.Name))
End If
Next
db_disconn conn, rs
Set Session("dicPermissions") = dicPermissions 'Store Dictionary to session array.
End Function

I was able to get it working and here is what I did? If anyone see anything wrong or if I need to add in any error trapping. This is load once when the user logs in.
Dim SQLString
SQLString ="SELECT Datefields here... & " AS p WHERE p.eid = '" & Clng(12) & "';"
'Create the dictionary object.
Set Session("dicPermissions") = Server.CreateObject("Scripting.Dictionary") 'Create the Dictionary object.
'sets up a connection to the database
db_conn conn, rs 'Open account table.
Set myRS = conn.Execute (SQLString) ' Uses any ADODB connection
For each item in myRS.Fields 'Create the dictionary with the field names and cell data.
'dicPermissions.Add fieldname, feild value
Session("dicPermissions").Add Trim(item.Name), Trim(myRS(item.Name))
Next
db_disconn conn, rs 'Close the database
You can access it like so:
Response.write Session("dicPermissions").Item("itemnamehere...")

Related

MS Access.adp to ASP.Net conversion: DLookup to SQL

Inherited a SQL database with an MS Access .adp front end which is being converted to ASP.net VB. Using a conversion tool which has done a good job on most of it after debugging. It however could not convert DLookup functions used in combo boxes as it is not supported. Being relativley new to .net am unclear how to convert the DLookup function to a SQL statement. The table name: dbo.Contact
The main form name: Contact_Edit
The sub form name: Contact_Edit_Sub
There are a number of combo boxes with many Dlookup functions. Once I have one I can rework the balance. Any help with converting the statement is appreciated.
The current code is listed below:
*If Not IsDBNull(Me.Contact_Edit.Contact_Edit_Sub.Intake_Worker_Code) Then
Intake_Worker_Code_Desc.Text = DLookup("[Name]", "Staff", "Code ='" & Intake_Worker_Code.SelectedValue & "'")
Else
Intake_Worker_Code_Desc.Text = ""
End If*
Try this, where [Name] is the field and Staff is the table
SELECT [Name] FROM Staff WHERE Code = '" & Intake_Worker_Code.SelectedValue & "';
Here you can read more about what DLookup does:
http://www.techonthenet.com/access/functions/domain/dlookup.php
https://support.office.com/en-us/article/DLookup-Function-8896cb03-e31f-45d1-86db-bed10dca5937
Update based on comment
VB.Net SQL code sample
If Not IsDBNull(Me.Intake_Worker_Code) Then
Dim conn_str As String = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString
Dim myconn As New SqlConnection(conn_str)
Dim sc As New SqlCommand()
sc.CommandText = "Select [Name] FROM [Staff] WHERE (Code = '") & (Intake_Worker_Code.SelectedValue & "')"
sc.Connection = myconn
myconn.Open()
Intake_Worker_Code_Desc.Text = sc.ExecuteScalar().ToString()
myconn.Close()
Else
Intake_Worker_Code_Desc.Text = ""
End If

Creating dynamic ADODB connections in Classic ASP

I have a list of Database connection strings, Database Name. These databases have the same table structure. What I am trying to do is dynamically create a connection to each one, add/delete/modify a table, however, if an error pops up anywhere, then RollbackTrans, else, CommitTrans.
My basic question to get my on the correct path is this:
Is this code possible in Classic ASP to make Dynamically named connections?
'create the dynamic object
execute("Set Con" & index & " = Server.CreateObject(""ADODB.connection"")")
'connect to the dynamic object
execute("Con" & index & ".Open " & DBString(index))
The error I get is 'Expected end of statement' on the .open line (the last one)
This might do the trick: Just use an array of connection strings. From this you create an array of connections. Then you can iterate over this array and send your commands to the separate databases.
dim connectionStrings(1)
dim connections(1)
dim curConn
connectionStrings(0) = "Provider=sqloledb;Server=.\EXPRESS2012;Database=master;uid=youruser;pwd=yourpwd"
connectionStrings(1) = "Provider=sqloledb;Server=.\EXPRESS2012;Database=model;uid=youruser;pwd=yourpwd"
for curConn = 0 to ubound( connectionStrings)
set connections(curConn) = Server.CreateObject("ADODB.Connection")
connections(curConn).Open connectionStrings(curConn)
next
dim cmd : cmd = "select ##servername, db_name()"
for curConn = 0 to ubound( connectionStrings)
dim rs
set rs = connections(curConn).Execute( cmd)
Response.write( rs( 0) & ":" & rs(1) & "<br />")
rs.close
set rs = nothing
next
for curConn = 0 to ubound( connectionStrings)
call connections(curConn).Close
set connections(curConn) = nothing
next
Mysql Dynamic Connection String , sample for t=1 to 4 , four different database connection conns(t)
dim conns(4)
Set Conns(1)=Server.Createobject("ADODB.Connection")
Conns(1).Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=localhost;port=3306;DATABASE=dbname;UID=root;PASSWORD=pass;OPTION=3"
Conns(1).Execute "SET NAMES 'latin5'"
Conns(1).Execute "SET CHARACTER SET latin5"
Conns(1).Execute "SET COLLATION_CONNECTION = 'latin5_turkish_ci'"

Transaction with ReadCommited can block selects from other threads?

I am trying to create unique policies with a ASP webservice and an Oracle 10.2g database.
I used to have a select query and an insert query to create policy numbers
But yesterday the webservice was called from 2 different threads and in the same exactly time and two same policy numbers where created.
So i changed the code to use a transation.
If the webservice is called from two different threads in the same time how will the transaction work?
Will the readcommited block the second thread or i will face the same problem again?
The select query will work or will there be a problem?
Public Function ExecutePolicyNumberTransaction(ByVal conet_key As String) As String
Dim policyno As String = ""
Dim sqlstring As String = ""
Dim conStr As String = ConfigurationManager.ConnectionStrings("con1").ConnectionString
Using connection As New OleDbConnection(conStr)
Dim transaction As OleDbTransaction
Try
connection.Open()
transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
Dim insertcommand As New OleDbCommand()
insertcommand.Connection = connection
insertcommand.Transaction = transaction
sqlstring = " INSERT into POLICYNUMBERS ( " & _
" RECID, POLICYNO, REFERNCEKEY, ISUSED, ISUSEDDATE ) " & _
" (SELECT NVL(MAX(RECID),0)+1, concat('P0130',concat(to_char(SUBSTR('000000', 0, 6-length(to_char(NVL(MAX(RECID),0)+1)))),to_char(NVL(MAX(RECID),0)+1))), '" & ref_key & "', 1, sysdate " & _
" FROM POLICYNUMBERS )"
insertcommand.CommandText = sqlstring
insertcommand.ExecuteNonQuery()
transaction.Commit()
Dim selectcommand As New OleDbCommand()
selectcommand.Connection = connection
sqlstring = "SELECT POLICYNO FROM POLICYNUMBERS WHERE REFERNCEKEY = '" & ref_key & "'"
selectcommand.CommandText = sqlstring
policyno = selectcommand.ExecuteScalar()
Catch ex As Exception
Try
transaction.Rollback()
Catch
End Try
policyno = ""
End Try
End Using
Return policyno
End Function
In Oracle, readers don't block writers and writers don't block readers. So neither session will block the other.
In a multi-user environment, however, you cannot generate primary keys using MAX(key)+1 unless you specifically introduce some form of serialization. Unless you want to build slow, unreliable systems, you don't want to introduce serialization. Instead, you really, really, really want to be using a sequence to generate your keys. Sequences are specifically designed to give primary keys to multiple concurrent sessions with a minimal overhead.
CREATE SEQUENCE policy_recid_seq
START WITH 1
INCREMENT BY 1
CACHE 100;
INSERT INTO policynumbers
SELECT policy_recid_seq.nextval, ...

second ExecuteReader() doesn't work

I have a code which checks the validity of user and then, if a user is valid it inserts certain values in the database.
My problem is when After I query my database to check if a user is valid and after that i try to pass the additional value to its account the flow stops when I invoke ExecuteReader() for the second time.
There is no error, or anything like that. I tried to substitute ExecuteReader() with ExecuteNoneQuery but still it's not working. I tried all the query in mysql command prompt they are working perfectly. I really can't understand what am I doing wrong there. Can anyone help me please?
Here is the code:
Try
myconn.Open()
Dim stquery As String = "SELECT * from accountstbl WHERE SE_ID = " & Id.Text
Dim smd = New MySqlCommand(stquery, myconn)
Dim myreader = smd.ExecuteReader()
If Not myreader.HasRows Then
errorUser.Visible = True
Else
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
Dim Myreader2 As MySqlDataReader
'smd.ExecuteNonQuery()'
'THE CODE STOPS HERE'
Myreader2 = smd2.ExecuteReader()
'Myreader2.Read()'
MsgBox("The BACKUP INFORMATION HAS BEEN SAVED")
End If
myconn.Close()
Catch ex As Exception
Dim ErrorMessage As String = "alert('" & ex.Message.ToString() & "');"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "ErrorAlert", ErrorMessage, True)
myconn.Close()
End Try
Because your second query is an update, not a select, you need to execute it using the ExecuteNonQuery method. Your commented-out code shows an attempt to call ExecuteNonQuery but on the wrong command object (smd when it should be smd2). Try something like this instead:
myreader.Read()
Dim name As String = myreader.Item("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES (" & name & ", '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd2.ExecuteNonQuery()
The ExecuteNonQuery method returns the number of rows updated as an int value, so you can capture it if it's valuable to you. In your case it's probably not, but here's how you'd check anyway:
int rowsAdded = smd2.ExecuteNonQuery();
if (rowsAdded == 1) {
// expected this
} else {
// didn't expect this
}
Finally, concatenating strings to build SQL commands can leave you vulnerable to SQL Injection attacks. Please take a look at using parameterized queries. There's a decent example here.
If you want to execute nested Reader, you have to create another connection. You need somethig like
smd2 = New MySqlCommand(stquery2, myconn2)' myconn2 is another connection
OR
Set "MultipleActiveResultSets=True in your connection string.
Also, use ExecuteNonQuery() for Inserting
Dim name As String = myreader("user_name").ToString()
Dim stquery2 = "INSERT into backup VALUES ('" & name & "', '" & Info & "')"
Dim smd2 = New MySqlCommand(stquery2, myconn)
smd.ExecuteNonQuery()
Please use Parameterized query to avoid SQL Injection
The logic is that you need to close your first reader (myreader) before executing another reader (MyReader2) on the same connection.

Update SQL Server tables using textboxes

I'm programming an education website using asp.net vb.net and SQL Server. I have 4 stackholders, if any body log in in his profile he will see his information
If he wants to update them he just change the textboxes then click update
My problem is how to update.
I wrote a method to update but it always show me a syntax error in the query. I made sure there is no problem. I'm updating two tables and I made to sql statements!
My qustion is can I Insert instead of update?
If not: how to upade one record based on the session I have?
please help me
this my code
' Private Sub UpdateInfo(ByVal USER_ID As Integer)
'Dim User As Integer = USER_ID
'Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET MobileNumber =" + tbmobile.Text + ", HomeNumber=" + tbhome.Text + ", AltRelation = " + DDLRelationShip.SelectedValue + ", AlTitle = " + DDLTitle.SelectedValue + ", AltName = " + tbemname.Text + ", AltMobile = " + tbemmobile.Text + " WHERE USER_ID = User)"
'Dim sql2 As String = "UPDATE DIP_USERS SET USER_Email=" + tbEmail.Text.Trim + " WHERE USER_ID = User)"
' Try
' Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("mydbConnectionString").ConnectionString)
' Dim cmd1 As New SqlCommand(sql1, conn)
' Dim cmd2 As New SqlCommand(sql2, conn)
' cmd2.Parameters.AddWithValue("#FirstName", tbname.Text)
' cmd2.Parameters.AddWithValue("#USER_PASSWORD", tbnewpassword.Text)
' cmd2.Parameters.AddWithValue("#USER_Email", tbEmail.Text)
' cmd1.Parameters.AddWithValue("#MobileNumber", tbmobile.Text)
' cmd1.Parameters.AddWithValue("#HomeNumber", tbhome.Text)
' cmd1.Parameters.AddWithValue("#AltRelation", DDLRelationShip.SelectedValue)
' cmd1.Parameters.AddWithValue("#AlTitle", DDLTitle.SelectedValue)
' cmd1.Parameters.AddWithValue("#AltName", tbemname.Text)
' cmd1.Parameters.AddWithValue("#AltMobile", tbemmobile.Text)
' conn.Open()
'Dim ra As Integer = cmd1.ExecuteNonQuery()
'Dim ra1 As Integer = cmd2.ExecuteNonQuery()
'cmd1.Dispose()
'cmd2.Dispose()
' conn.Close()
' Catch ex As Exception
' MsgBox(ex.Message)
' End Try
'End Sub
you have not specified your parameters in your query, you're directly concatenating the values of controls inside your query. And still you have added parameters.
Firstly, do not concatenate your sql query like that, its prone to SQL Injection.
construct your query like this:
Dim sql1 As String = "UPDATE AdminCoordinatorInformation SET
MobileNumber =#MobileNumber,
HomeNumber=#HomeNumber,
AltRelation = #AltRelation,
AlTitle = #AlTitle,
AltName =#AltName,
AltMobile = #AltMobile
WHERE USER_ID = #User"
Dim sql2 As String = "UPDATE DIP_USERS SET
USER_Email=#USER_Email
WHERE USER_ID = #User"
and also, add this parameter too
cmd1.Parameters.AddWithValue("#User", USER_ID)
cmd2.Parameters.AddWithValue("#User", USER_ID)
And one very important thing. you need to assign proper datatype to your columns in the query i.e.
remember these things.
txtBox.Text returns String value, you might need to convert it to Int32 using Convert.Int32 or you need to wrap it in single quote, based totally upon datatype of your column
Put parameters which you declare in your SQL Command query:
"UPDATE AdminCoordinatorInformation SET MobileNumber=#MobileNumber,HomeNumber=#homeNumber...
You get syntax error because your string data in sql query must be wrapped with "'".
"UPDATE AdminCoordinatorInformation SET MobileNumber='0987654321',....
Note: creating sql queries by concating query with user inputs ("...SET MobileNumber='" + txtbox.Text + "',...") is not good/dangerous practice because of SQL Injection

Resources