How to connect to LDAP store with VB6 - vb6

I’ve got a problem with Visual Basic (6) in combination with LDAP. When I try to connect to an LDAP store, I always get errors like ‘Bad Pathname’ or ‘Table does not exist’ (depending on what the code looks like).
This is the part of the code I wrote to connect:
path = "LDAP://xx.xxx.xxx.xxx:xxx/"
Logging.WriteToLogFile "Test1", logINFO
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "USER_ID"
conn.Properties("Password") = "PASSWORD"
conn.Properties("Encrypt Password") = True
conn.Properties("ADSI Flag") = 34
Logging.WriteToLogFile "Test2", logINFO
conn.Open "Active Directory Provider"
Logging.WriteToLogFile "Test3", logINFO
Set rs = conn.Execute("<" & path & "ou=Some,ou=Kindof,o=Searchbase>;(objectclass=*);name;subtree")
Logging.WriteToLogFile "Test4", logINFO
The logfile shows “Test1” , “Test2”, “Test3” and then “Table does not exist”, so it’s the line “Set rs = conn.Execute(…)” where things go wrong (pretty obvious…).
In my code, I try to connect in a secure way. I found out it has nothing to do with SSL/certificates though, because it’s also not possible to establish an anonymous unsecured connection. Funny thing is: I wrote a small test app in .NET in five minutes. With that app I was able to connect (anonymously) and read results from the LDAP store, no problems at all.
Does anyone have any experience with the combination LDAP and VB6 and maybe know what could be the problem? I googled and saw some example code snippets, but unfortunately none of them worked (same error messages as result). Thanks in advance!

I'm not sure how much help this will be, but I use this code to access Active Directory objects.
Set oinfo = New ADSystemInfo
sDomain = Split(oinfo.DomainDNSName, ".")
'-- Get Datasets from the Active Directory
'-- Connect to Active Directory in logged in domain
con.Open "Provider=ADsDSOObject;Encrypt Password=False;Integrated Security=SSPI;Data Source=ADSDSOObject;Mode=Read;Bind Flags=0;ADSI Flag=-2147483648"
'-- Query all serviceConnectionPoints in the Active Directory
'-- that contain the keyword "urn://tavis.net/TM/Database"
'-- and return the full path to the object
Set rst = con.Execute("<LDAP://DC=" & sDomain(0) & ",DC=" & sDomain(1) & ">;(&(objectCategory=serviceConnectionPoint)(keywords=urn://tavis.net/TM/Database));Name, AdsPath;subTree")

2 things:
The Open() method call takes additional parameters, server/username/password
The LDAP query you passed to Execute() should be:
"<" & path & "ou=Some/ou=Kindof/o=Searchbase>;(objectclass=*);name;subtree"

Related

Getting network details from Active Directory in VB script?

There are needs when we want to populate user details from Active Directory. Sharing my code to access user details from AD.
Introduction
People often ask for querying active directory by passing network account name or email. There are many articles already available on this, and one might get confused. Here is simple working code to access user detail from active directory database-
Please note in order to access AD, you have to specify valid network account credentials in connection.
function GetADDetails(userId)
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.provider ="ADsDSOObject"
objConn.Properties("User ID") = "domain\userId" 'specify domain and
network account
objConn.Properties("Password") = "password" 'specify network password
objConn.Properties("Encrypt Password") = True
objConn.open "Active Directory Provider"
Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objConn
strTarget="GC://abc.com" 'your domain name
objCom.CommandText ="select sn, givenName, sAMAccountName, name,mail,
telephoneNumber FROM '"+strTarget+"' where sAMAccountname='"+userId+"'"
Set objRS = objCom.Execute
If Not (objRS.EOF Or objRS.BOF) Then
GetADDetails=objRS.GetRows
Else
GetUserData = Null
End If
'Close objects and remove from memory
objRS.Close
objConn.Close
Set objRS = Nothing
Set objConn = Nothing
Set objCom = Nothing
end function

Unspecified error while executing sql query vba on Oracle database

I want to import data from Oracle database to Excel using VBA. I've tried several options I found in here or in the official manual but none of them seem to work for me - I always get the same unspecified runtime error on line with
rs.Open strSQL1, con
or
Set rs = con.Execute(strSQL1)
depending on which one of these two methods I use obviously. Here is the whole code:
Sub data_distribution()
'Setting up the database connection
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim strSQL1, strInput, strCon As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=XXX)(PORT=XXX))" & _
"(CONNECT_DATA=(SERVICE_NAME=XXX))); uid=XXX; pwd=XXX;"
'--- Open the above connection string.
con.ConnectionString = strCon
con.Open
'con.Open strCon
'--- Now connection is open and you can use queries to execute them.
'--- It will be open till you close the connection
'Definition of parameter
strInput = InputBox("Insert car_id")
strSQL1 = "select * from car where car_id = " & strInput & ""
'Executing the query
'rs.activeconnection = con
'rs.Open strSQL1, con
Set rs = con.Execute(strSQL1)
rs.Open strSQL1, con
Worksheets("Data").Range("A2").CopyFromRecordset rs
'Closing connection
rs.Close
con.Close
Set con = Nothing
Set rs = Nothing
I was thinking it might be an issue of connecting to the database but if I import/query data manual, it works just fine. For example using this manual
http://blog.mclaughlinsoftware.com/microsoft-excel/how-to-query-oracle-from-excel-2007/
I had to download and configure ODAC for Windows from Oracle site to make it work. I use tsnames.ora to set the path. Wasn't sure if I configured it right but it works so I guess there isn't a problem with the connection in vba either, or is it? (The variables are, of course, set to real values, not "XXX")
The query itself is correct and returns valid results from the database. Libraries necessary to use ADOBD are linked as well. (Microsoft ActiveX Data Objects 2.0 Library)
There is an existing question with the same error but it's unresolved:
Unspecified run time error while executing vba script
I'm guessing it's station/interface specific (I use Excel 2010, SQL developer).
Even though it's been some time I asked the question, here, it's still unresolved so I will answer myself.
The problem was in the car table where one of the attributes was type CLOB (CHARACTER LARGE OBJECT) with lenght over 2000 characters. Excel was unable to cope with that type and the query caused the unspecified error. If I listed all attributes but this one, it all went well.

Access Connection String From File Generated by Server.Execute

I have a file header.asp that has an server side include head.asp. Inside head.asp my connection to my database is created and is accessible from the header.asp file and pages that use the header.asp file as an server side include (in this case my core.asp file). Inside core.asp I have the following:
if request.querystring("page") = "" then
response.write("<p>No data to load</p>")
else
page = request.querystring("page")
set fso = createobject("scripting.filesystemobject")
FileName = "../Pages/" & page & ".asp"
if fso.FileExists (server.mappath(FileName)) then
Server.Execute(FileName)
else
response.write("<p>Could not validate page. Try again.</p>")
end if
end if
This executes just fine and the proper page renders inside the core.asp file. My issue, is that the connection string (from head.asp) is not available to the file being called from Server.Execute. Thus, I cannot run database queries, etc. on this page unless I were to instantiate the object anew. Is there any way to use the object created?
If I have not explained this properly, I will expound as I am able given my intermediate experience level.
As a follow up to answer #1, if I've followed the logic correctly, I'm attempting to create the connection object at the application level (global.asa):
Sub Application_OnStart()
dim oConn, connectstr
set oConn = Server.CreateObject("ADODB.Connection")
connectstr = "Driver={MySQL ODBC 3.51 Driver};SERVER=theServer; DATABASE=theDatabase; UID=theUserID; PWD=thePassword"
oConn.ConnectionTimeout = 5
oConn.Open connectstr
Application("con") = oConn
end Sub
</script>
Attempting to access the object like so from my page that includes the global.asa as an IIS:
qryAdmin = "select * from table"
set rsAdmin = Application("con").execute(qryAdmin)
The results are the same. I receive the "Object required" error. Any glaring errors that could be causing this?
Assign this object to a session variable and you can access it from any page you like...
Session("MyConnectionObj")= CONN
CONN is your instantiated connection object on the page where you instantiate your connection originally. And in your executed file just call
set NewCONN=Session("MyConnectionObj")
RS.Open strSql ,NewCONN,1,1
where strSql is your SQL, RS is your recordset etc... Obviously if you calling the stored procedure, it will look slightly different but you get the point.
Edited to show that object have to be declared and set before one using it. As I see at least one "expert" did not know that.
Edited base on comments from Window Frog:
did you try it like that:
<%
if request.querystring("page") = "" then
response.write("<p>No data to load</p>")
else
page = request.querystring("page")
set fso = createobject("scripting.filesystemobject")
FileName = "../Pages/" & page & ".asp"
if fso.FileExists (server.mappath(FileName)) then%>
<!--#include file="<%=FileName %>" -->
<% else
response.write("<p>Could not validate page. Try again.</p>")
end if
end if
%>

ADS user details - subdomain - from vbs file

I managed to get ADS users without specifying authentication details from my ADS domain(ex,mydomain.com). I used ADODB.Connection and ADODB.Command.
I also have sub-domains like test.mydomain.com. How to get user details from sub-domain, by specifying authentication details of a user belonging to test.mydomain.com .
You can query records from trusted domains by using their LDAP name as the search base. However, since the DC of the parent domain doesn't contain the information about objects in the child domain it will generate a referral. The ADODB.Command object won't automatically chase that referral, because the respective named property "Chase referrals" defaults to 0x00 (ADS_CHASE_REFERRALS_NEVER). You have to set the property to one of the following two values
ADS_CHASE_REFERRALS_SUBORDINATE (0x20)
ADS_CHASE_REFERRALS_ALWAYS (0x60)
to make your query follow the referral. Example:
base = "<LDAP://dc=test,dc=example,dc=org>"
filter = "(&(objectCategory=computer)(name=foo*))"
attr = "name,description"
scope = "subtree"
Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Open "Active Directory Provider"
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = conn
cmd.CommandText = base & ";" & filter & ";" & attr & ";" & scope
cmd.Properties("Chase referrals") = &h60 ' <-- here
Set rs = cmd.Execute
I wrote a wrapper class (ADQuery) to encapsulate the boilerplate code for Active Directory queries (because I got fed up with writing it over and over again). With that you could simplify the above to something like this:
Set qry = New ADQuery
qry.SearchBase = "dc=test,dc=example,dc=org"
qry.Filter = "(&(objectCategory=computer)(name=foo*))"
qry.Attributes = Array("name", "description")
Set rs = qry.Execute
Either way you may still need to run the script on a DC, though.

Classic ASP (VBScript), 2008 R2, error using AD to authenticate

I have moved a web site from Win2003 x32 to Win2008R2 x64. It works fine on the old server. The web site uses active directory to authenticate. I get this error on 2008: -2147023584 : A specified logon session does not exist. It may already have been terminated. I have tried switching to classic mode, etc. with no change. It does execute VBScript code (otherwise I wouldn't get the error).
Here is the code:
Function AuthenticateUser(UserName, Password)
On Error Resume Next
Dim oADsNamespace, oADsObject
Dim strADsNamespace, strADsPath
strADsPath = "WinNT://ibcschools.edu"
strADsNamespace = left(strADsPath, instr(strADsPath, ":"))
Set oADsObject = GetObject(strADsPath)
Set oADsNamespace = GetObject(strADsNamespace)
Set oADsObject = oADsNamespace.OpenDSObject(strADsPath, UserName, Password, 0)
Response.Write(Err.Number & " : " & Err.Description & "<br />")
If Err.Number = 0 Then
Set oADsNamespace = Nothing
Set oADsObject = Nothing
Set strADsNamespace = Nothing
Set strADsPath = Nothing
AuthenticateUser = True
Else
Set oADsNamespace = Nothing
Set oADsObject = Nothing
Set strADsNamespace = Nothing
Set strADsPath = Nothing
AuthenticateUser = False
End If
End Function
Any help would be appreciated. Thanks.
Your problem seems to be related to using WinNT provider with OpenDSObject.
Things you could try:
Replace WinNT with LDAP provider.
Try running your standalone VBS file
under IIS/ApplicationPool user privileges.
Okay, so I got it working. Before it worked without the domain name, but now requires it. I think it has something to do with the app pool logging in on the old server versus this one. I am going to work on it a little more. I don't want to change all the sites.

Resources