Can someone point me in the right direction for information on how to push data to Active Directory from Classic ASP?
There are a couple of ways this can be done from classic ASP.
Use ADO with ADSI
Use the ADSI Objects of LDAP
Here's a sample from Modifying an ADSI Object from ADO
'Replace department for all users in OU=sales.
Set con = Server.CreateObject("ADODB.Connection")
con.Provider = "ADsDSOObject"
Set command = CreateObject("ADODB.Command")
Set command.ActiveConnection = con
command.CommandText = "SELECT AdsPath, cn FROM 'LDAP://OU=Sales,DC=Fabrikam,DC=com' WHERE objectClass = 'user'"
command.Properties("searchscope") = ADS_SCOPE_ONELEVEL
Set rs = command.Execute
While Not rs.EOF
Set usr = GetObject(rs.Fields("AdsPath").Value)
usr.Put "department", "1001"
usr.SetInfo
rs.MoveNext
Wend
Here's a sample from the article Getting Started with ASP for ADSI.
<%# Language=VBScript %>
<%
' Get the inputs.
containerName = Request.Form("inpContainer")
' Validate compName before using.
If Not ("" = containerName) Then
' Bind to the object.
adsPath = "LDAP://" & containerName
Set comp = GetObject(adsPath)
' Write the ADsPath of each of the child objects.
Response.Write("<p>Enumeration:</p>")
For Each obj in comp
Response.Write(obj.ADsPath + "<BR>")
Next
End If
%>
Related
I'm new to this old scripting language but it's all we have right now. I'm trying to get this code work.
I would like to compare USERID servervariable with the same USERID from a recordset, then if true it will redirect the name of that USERID.
<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Driver={Microsoft Access Driver (*.mdb)}; DBQ=I:\storyData.mdb"
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "SELECT USERIDFROM preprod", conn
strName = "John"
strNo = "This is not you"
If Request.ServerVariables("HTTP_USERID") = (rs.Fields.Item("USERID").Value) Then
Response.Redirect("story.html?" & "name=" & strName)
Else
Response.Redirect("story.html?" & "name=" & strNo)
End If
%>
I hope this makes any sense. It seems simple but can't get it to work.
thanks
what "doesn't" work?
looking at your code, it seems you're only checking the the first record of your query. I think you want to do something like this:
<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Driver={Microsoft Access Driver (*.mdb)}; DBQ=I:\storyData.mdb"
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "SELECT count( USERID ) FROM preprod where userID = " & Request.ServerVariables("HTTP_USERID"), conn
strName = "John"
strNo = "This is not you"
if CInt( rs( 0 ) ) > 0 then
Response.Redirect("story.html?" & "name=" & strName)
Else
Response.Redirect("story.html?" & "name=" & strNo)
End If
%>
this code does a count of userIDs in your table and if there are more than 1, it'll do the redirect properly. A lot more efficient this way.
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...")
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
A few years ago we (as a company) faced the scenario of getting our developers to stop writing classic asp pages and switch to .net (and in turn system.data for data access).
As a supposedly ‘short term’ measure I wrote the following class to make the switchover easier for those not used to system.data & all its new objects:
http://www.heavencore.co.uk/forum/viewthread.php?thread_id=185
The main purpose of this class was to keep usage as similar to classic asp as possible & keep the usage VERY simple (plus to add email alerts for error catching yada yada yada):
Public db As New SimpleDataAccess
Public RS As New DataTable
ConnectDatabase()
db.Execute_Query(RS, "SELECT * FROM whatever WHERE IntColumn = " & tools.parseint(EmployeeID, 0) & " or TextColumn = '" & db,Escape("bla'blabla") & "' ORDER BY IntColumn")
For Each DB_Row As DataRow In RS.Rows
response.Write(DB_Row("IntColumn"))
Next
CloseDatabase()
Now, the two main reasons why this class sucks:
Sql Injection stuff (parseint & quote escaping) has to be done outside the class - prone to forgetfulness - Parameterised queries definitely need to be introduced here!
CloseDatabase() has to be called manually at the end of the page - this is often forgot and a connection is left open to the server - even after the page has finished rendering etc
Reasons why this class was good:
Usage of the class was very simple and allowed old classic asp code to be VERY easily converted to .net
Email alerts for query & connection errors was handled invisibly in the class itself
It has worked perfectly for 2+ years now, no problems
My Question:
Are there any other classes / suggestions out there that will allow me to either replace this class but retain the VERY simple usage OR what would be the best way to modify the Execute_Query() and Execute_NonQuery() methods to handle parameterised queries?
Simplicity is key!
PS: Where is a good place to post large chunks of code for use in SO questions? Pastebin etc only keep stuff for a month...
I think this might help you. A large chunk of code. This handles almost every thing you need. You can pass parameters in an array. Also can use with stored procedures as well. Nothing to worry about connection closing.
Hope this helps.
I've always used the functions that came from http://www.fmstocks.com/ (A sample Asp Classic MS application). It's very simple and works with parameters
Example usage:
set rs = RunSQLReturnRs("Select * from Usuario where UsuarioID = ?", _
array(mp("#UsuarioID", adInteger, 0, UsuarioID)))
If not rs.eof then
UsuarioName = rs("FullName")
end if
DbHelper.ASP full code (slightly modified over the years)
<!--#include file="../bus/adovbs.inc"-->
<%
Function GetConnectionString()
GetConnectionString = "file name=c:\udl\miconnstring.udl"
End Function
Function mp(PName , PType , PSize, PValue)
mp = Array(PName, PType, PSize, PValue)
End Function
Function RunSPReturnRS(strSP, params())
On Error Resume next
' Create the ADO objects
Dim rs , cmd
Set rs = server.createobject("ADODB.Recordset")
Set cmd = server.createobject("ADODB.Command")
' Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = GetConnectionString()
cmd.CommandText = strSP
cmd.CommandType = adCmdStoredProc
cmd.CommandTimeout = 900 ' 15 minutos
collectParams cmd, params
' Execute the query for readonly
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
If err.number > 0 then
BuildErrorMessage()
exit function
end if
' Disconnect the recordset
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing
' Return the resultant recordset
Set RunSPReturnRS = rs
End Function
Function RunSP(strSP , params())
On Error resume next
' Create the ADO objects
Dim cmd
Set cmd = server.createobject("ADODB.Command")
' Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = GetConnectionString()
cmd.CommandText = strSP
cmd.CommandType = adCmdStoredProc
cmd.CommandTimeout = 900 ' 15 minutos
collectParams cmd, params
' Execute the query without returning a recordset
cmd.Execute , , adExecuteNoRecords
If err.number > 0 then
BuildErrorMessage()
exit function
end if
' Disconnect the recordset and clean up
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Exit Function
End Function
Function RunSQL(strSP , params())
On Error resume next
' Create the ADO objects
Dim cmd
Set cmd = server.createobject("ADODB.Command")
' Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = GetConnectionString()
cmd.CommandText = strSP
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900 ' 15 minutos
collectParams cmd, params
' Execute the query without returning a recordset
cmd.Execute , , adExecuteNoRecords
If err.number > 0 then
BuildErrorMessage()
exit function
end if
' Cleanup
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Exit Function
End Function
Function RunSQLReturnRS(sqlstmt, params())
On Error Resume next
' Create the ADO objects
Dim rs , cmd
Set rs = server.createobject("ADODB.Recordset")
Set cmd = server.createobject("ADODB.Command")
' Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = GetConnectionString()
cmd.CommandText = sqlstmt
cmd.CommandType = adCmdText
cmd.CommandTimeout = 900 ' 15 minutos
collectParams cmd, params
' Execute the query for readonly
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenForwardOnly, adLockReadOnly
If err.number > 0 then
BuildErrorMessage()
exit function
end if
' Disconnect the recordset
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Set rs.ActiveConnection = Nothing
' Return the resultant recordset
Set RunSQLReturnRS = rs
End Function
Function RunSPReturnInteger(strSP , params())
On Error resume next
' Create the ADO objects
Dim cmd
Set cmd = server.createobject("ADODB.Command")
' Init the ADO objects & the stored proc parameters
cmd.ActiveConnection = GetConnectionString()
cmd.CommandText = strSP
cmd.CommandType = adCmdStoredProc
cmd.CommandTimeout = 900 ' 15 minutos
collectParams cmd, params
' Assume the last parameter is outgoing
cmd.Parameters.Append cmd.CreateParameter("#retval", adInteger, adParamOutput, 4)
' Execute without a resulting recordset and pull out the "return value" parameter
cmd.Execute , , adExecuteNoRecords
If err.number > 0 then
BuildErrorMessage()
exit function
end if
RunSPReturnInteger = cmd.Parameters("#retval").Value
' Disconnect the recordset, and clean up
Set cmd.ActiveConnection = Nothing
Set cmd = Nothing
Exit Function
End Function
Private Sub collectParams(cmd , argparams())
Dim params , v
Dim i , l , u
params = argparams
For i = LBound(params) To UBound(params)
l = LBound(params(i))
u = UBound(params(i))
' Check for nulls.
If u - l = 3 Then
If VarType(params(i)(3)) = vbString Then
If params(i)(3) = "" then
v = null
else
v = params(i)(3)
end if
Else
v = params(i)(3)
End If
If params(i)(1) = adLongVarChar Then
Dim p 'As New Parameter
Set p = cmd.CreateParameter(params(i)(0), params(i)(1), adParamInput)
p.Attributes = adParamLong + adParamSigned
If Not IsNull(v) Then
'Seteo para text columns is not null
p.AppendChunk v
p.Size = Len(v)
Else
'Seteo para text columns is null
p.Value = v
p.Size = 10000
End If
cmd.Parameters.Append p
Else
cmd.Parameters.Append cmd.CreateParameter(params(i)(0), params(i)(1), adParamInput, params(i)(2), v)
End If
Else
RaiseError m_modName, "collectParams(...): incorrect # of parameters"
End If
Next
End Sub
%>
I know it is a common error, but I still can't solve it myself.
What I am trying to do is I have a SELECT item called status that allow the user to choose their employment status, I want to simply get the result and update the user_table(access file) status cell.
Any reply will be greatly appreciated!
The Code is below:
<!--#include file="../conn/conn.asp"-->
<%
id=request.QueryString("id")
status=request.Form("status")
sql="select * from user_table where id="&id
set rs=conn.execute(sql)
sql="update user_table set Status='"+status+"' where id="&id
'response.Write sql
conn.execute(sql)
conn.close
response.Write "<script>alert('Change Sucessful!');</script>"
set conn=nothing
response.end()
%>
I think you may be having a problem with conn.execute(sql) as well as response.end()
To fix it, you need to do either:
conn.execute sql
or
Call conn.execute(sql)
But, yeah, you should follow other comments posted as your technique has security issues. You should consider changing it to use parameters:
<!--#include file="../conn/conn.asp"-->
<%
id = request.QueryString("id")
status = request.Form("status")
sql = "select * from user_table where id = #id"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = sql
Set cmd.ActiveConnection = conn
cmd.Prepared = True
cmd.Parameters.Refresh
cmd.Parameters("#id") = id
Set rs = cmd.Execute
Set rs = nothing
Set cmd = nothing
sql = "update user_table set status = #status where id = #id"
Set cmd = CreateObject("ADODB.Command")
cmd.CommandText = sql
Set cmd.ActiveConnection = conn
cmd.Prepared = True
cmd.Parameters.Refresh
cmd.Parameters("#status") = status
cmd.Parameters("#id") = id
Set rs = cmd.Execute
Set rs = nothing
Set cmd = nothing
response.Write "<script>alert('Change Sucessful!');</script>"
Set conn = nothing
response.end
%>
I'm guessing conn.asp leaves conn open? otherwise you need to open it. Also, what shows when you uncomment the response.write sql line?
And, you are definitely opening yourself to hackers. You need to 'clean' anything that comes from a request.form or request.querystring (with at the very least, a replace(..., "'", "''"), or much better, use stored procedures instead of straight sql
I'm trying to create a new email in asp and send it to a mail server using CDO. I believe I need a reference for CDO or Send Email functionality. In the book it says use this:
Set objNewMail = Server.CreateObject("CDONTS.NewMail")
Unfortunately that is now working as it errors out in asp. Now sure how to add the reference, or com object so that it will work through iis using asp. The book I'm referring to is: ASP In a nut shell 2nd addition. "The CDO Object Model" I'm using windows xp or windows server 2003.
use this instead of cdonts
<!--
METADATA
TYPE="typelib"
UUID="CD000000-8B95-11D1-82DB-00C04FB1625D"
NAME="CDO for Windows 2000 Library"
-->
<%
Function SendMail(sFrom, ToA, Subject, Mybody)
Dim iMsg,iConf
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
Dim Flds
Set Flds = iConf.Fields
With Flds
' assume constants are defined within script file
.Item(cdoSendUsingMethod) = cdoSendUsingPort
.Item(cdoSMTPServer) = MAILSERVER
.Item(cdoSMTPConnectionTimeout) = 60
.Item(cdoURLGetLatestVersion) = True
.Update
End With
With iMsg
Set .Configuration = iConf
.To = ToA
.From = sFrom
.Subject = Subject
.TextBody = Mybody
.Send
End With
Set iConf = nothing
Set iMsg = nothing
If Err.Number = 0 Then
SendMail = True
Else
SendMail = Err.Number&":"&Err.Description
End If
On Error Goto 0
set objSendMail = Nothing
End Function
%>