继我之前的Question之后,我设法用help from the Oracle forums回答了问题,我现在又提出了另一个问题,从前一个问题开始(为背景提供)。
我希望直接从我的C#代码查询LDAP,以执行Oracle TNS主机名的LDAP查找,以获取连接字符串。这通常存储在 tnsnames.ora 中,我的组织使用LDAP(通过 ldap.ora )使用Active Directory从LDAP服务器解析主机名。
但是,我在我的C#应用程序中使用ODP.NET, Managed Driver Beta( Oracle.ManagedDataAccess.dll ),该应用程序不支持LDAP,如release notes中所述。 Oracle forum reply我之前提到过。这就是我希望直接从C#查询LDAP的原因。
我找到了使用DirectoryEntry
和DirectorySearcher
执行此操作here的方法,但我不知道将DirectorySearcher
的参数放在哪里。我可以访问 ldap.ora ,其格式如下:
#LDAP.ORA配置
#由Oracle配置工具生成 DEFAULT_ADMIN_CONTEXT =“dc = xx,dc = mycompany,dc = com”
DIRECTORY_SERVERS =(ldap_server1.mycompany.com:389:636,ldap_server2.mycompany.com:389:636,...)DIRECTORY_SERVER_TYPE = OID
但是,如何将其映射到在我的C#代码中设置LDAP查询?
答案 0 :(得分:4)
继我在accepted Answer中的第二条评论之后,这是执行LDAP查找的代码,它改进了我找到的原始版本here。它还处理 ldap.ora 文件中包含多个分隔端口号的服务器列表。
private static string ResolveServiceNameLdap(string serviceName)
{
string tnsAdminPath = Path.Combine(@"C:\Apps\oracle\network\admin", "ldap.ora");
string connectionString = string.Empty;
// ldap.ora can contain many LDAP servers
IEnumerable<string> directoryServers = null;
if (File.Exists(tnsAdminPath))
{
string defaultAdminContext = string.Empty;
using (var sr = File.OpenText(tnsAdminPath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// Ignore commetns
if (line.StartsWith("#"))
{
continue;
}
// Ignore empty lines
if (line == string.Empty)
{
continue;
}
// If line starts with DEFAULT_ADMIN_CONTEXT then get its value
if (line.StartsWith("DEFAULT_ADMIN_CONTEXT"))
{
defaultAdminContext = line.Substring(line.IndexOf('=') + 1).Trim(new[] {'\"', ' '});
}
// If line starts with DIRECTORY_SERVERS then get its value
if (line.StartsWith("DIRECTORY_SERVERS"))
{
string[] serversPorts = line.Substring(line.IndexOf('=') + 1).Trim(new[] {'(', ')', ' '}).Split(',');
directoryServers = serversPorts.SelectMany(x =>
{
// If the server includes multiple port numbers, this needs to be handled
string[] serverPorts = x.Split(':');
if (serverPorts.Count() > 1)
{
return serverPorts.Skip(1).Select(y => string.Format("{0}:{1}", serverPorts.First(), y));
}
return new[] {x};
});
}
}
}
// Iterate through each LDAP server, and try to connect
foreach (string directoryServer in directoryServers)
{
// Try to connect to LDAP server with using default admin contact
try
{
var directoryEntry = new DirectoryEntry("LDAP://" + directoryServer + "/" + defaultAdminContext, null, null, AuthenticationTypes.Anonymous);
var directorySearcher = new DirectorySearcher(directoryEntry, "(&(objectclass=orclNetService)(cn=" + serviceName + "))", new[] { "orclnetdescstring" }, SearchScope.Subtree);
SearchResult searchResult = directorySearcher.FindOne();
var value = searchResult.Properties["orclnetdescstring"][0] as byte[];
if (value != null)
{
connectionString = Encoding.Default.GetString(value);
}
// If the connection was successful, then not necessary to try other LDAP servers
break;
}
catch
{
// If the connection to LDAP server not successful, try to connect to the next LDAP server
continue;
}
}
// If casting was not successful, or not found any TNS value, then result is an error message
if (string.IsNullOrEmpty(connectionString))
{
connectionString = "TNS value not found in LDAP";
}
}
else
{
// If ldap.ora doesn't exist, then return error message
connectionString = "ldap.ora not found";
}
return connectionString;
}
答案 1 :(得分:1)
为了帮助您入门,请尝试:
using System.DirectoryServices;
...
DirectoryEntry de = new DirectoryEntry();
de.Username = "username@mysite.com";
de.Password = "password";
de.Path = "LDAP://DC=mysite,DC=com";
de.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher des = new DirectorySearcher(de);
现在你应该能够使用描述here
的DirectorySearcher(过滤器,findone等)来点击ldap答案 2 :(得分:1)
根据我在Oracle Database Name Resolution with OpenLDAP中找到的内容来判断,代码看起来应该是这样的:
string directoryServer = "ldap_server1.mycompany.com:389";
string defaultAdminContext = "dc=xx,dc=mycompany,dc=com";
string oracleHostEntryPath = string.Format("LDAP://{0}/cn=OracleContext,{1}", directoryServer, defaultAdminContext);
var directoryEntry = new DirectoryEntry(oracleHostEntryPath) {AuthenticationType = AuthenticationTypes.None};
var directorySearcher = new DirectorySearcher(directoryEntry, "(&(objectclass=orclNetService)(cn=ABCDEFG1))", new[] { "orclnetdescstring" }, SearchScope.Subtree);
string oracleNetDescription = Encoding.Default.GetString(des.FindOne().Properties["orclnetdescstring"][0] as byte[]);
答案 3 :(得分:0)
这里有一个基于其他答案的更完整的样本:
using System;
using System.Data;
using System.DirectoryServices;
using System.Text;
using Oracle.ManagedDataAccess.Client;
namespace BAT
{
internal class Program
{
private static void Main(string[] args)
{
string directoryServer = "myServer:389";
string defaultAdminContext = "cn=OracleContext,dc=world";
string serviceName = "MYDB";
string userId = "MYUSER";
string password = "MYPW";
using (IDbConnection connection = GetConnection(directoryServer, defaultAdminContext, serviceName, userId,
password))
{
connection.Open();
connection.Close();
}
}
private static IDbConnection GetConnection(string directoryServer, string defaultAdminContext,
string serviceName, string userId, string password)
{
string descriptor = ConnectionDescriptor(directoryServer, defaultAdminContext, serviceName);
// Connect to Oracle
string connectionString = $"user id={userId};password={password};data source={descriptor}";
OracleConnection con = new OracleConnection(connectionString);
return con;
}
private static string ConnectionDescriptor(string directoryServer, string defaultAdminContext,
string serviceName)
{
string ldapAdress = $"LDAP://{directoryServer}/{defaultAdminContext}";
string query = $"(&(objectclass=orclNetService)(cn={serviceName}))";
string orclnetdescstring = "orclnetdescstring";
DirectoryEntry directoryEntry = new DirectoryEntry(ldapAdress, null, null, AuthenticationTypes.Anonymous);
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry, query, new[] { orclnetdescstring },
SearchScope.Subtree);
SearchResult searchResult = directorySearcher.FindOne();
byte[] value = searchResult.Properties[orclnetdescstring][0] as byte[];
if (value != null)
{
string descriptor = Encoding.Default.GetString(value);
return descriptor;
}
throw new Exception("Error querying LDAP");
}
}
}