I did some programming for reading the data from Active Directory such as user account or Orgnization info and so on. The code below is like something what I did.
DirectoryEntry entry = new DirectoryEntry(
"LDAP://CN=Users,DC=domain,DC=com",
null,
null,
AuthenticationTypes.Secure
);
DirectorySearcher search = new DirectorySearcher(entry);
using (SearchResultCollection src = search.FindAll())
{
foreach (SearchResult result in src)
{
Console.WriteLine(result.Properties["name"][0] + " : " +
result.Properties["department"][0]);
}
}
The problem is how can I know what properties that target objects have then I can use them to filter the data before get it all.
Any ideas?
If you have a DirectoryEntry, you can inspect its .SchemaEntry:
DirectoryEntry entry = new DirectoryEntry("LDAP://......");
DirectoryEntry schema = entry.SchemaEntry;
This should - if you have the necessary permissions - give you access to the properties defined in the schema - things like MandatoryProperties or OptionalProperties:
foreach (var prop in schema.Properties.PropertyNames)
{
string propName = prop.ToString();
var propValue = schema.Properties[propName].Value;
}
Does that help you get started??
You might also want to have a look at BeaverTail - my C# open-source LDAP browser.
(source: mvps.org)
It will allow you to inspect any LDAP node and see all its properties.
Related
I've read this excellent SO post on how to get access to the appsettings.json file in a .Net 6 console app.
However, in my json file I have several arrays:
"logFilePaths": [
"\\\\server1\\c$\\folderA\\Logs\\file1.log",
"\\\\server2\\c$\\folderZ\\Logs\\file1A1.log",
"\\\\server3\\c$\\folderY\\Logs\\file122.log",
"\\\\server4\\c$\\folderABC\\Logs\\fileAB67.log"
],
And I get the results if I do something like this:
var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true);
var config = builder.Build();
string logFile1 = config["logFilePaths:0"];
string logFile2 = config["logFilePaths:1"];
string logFile3 = config["logFilePaths:2"];
But I don't want to have to code what is effectively an array into separate lines of code, as shown.
I want to do this:
string[] logFiles = config["logFilePaths"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
But it gives me an error on config["logFilePaths"] saying it's null.
Why would that be null?
To access the logFilePaths as an array, you want to use the Get<T> extension method:
string[] logFilePaths = config.GetSection("logFilePaths").Get<string[]>();
One option is to install Microsoft.Extensions.Configuration.Binder nuget and use Bind (do not forget to setup CopyToOutputDirectory for appsettings.json):
var list = new List<string>();
config.Bind("logFilePaths", list);
Another - via GetSection (using the same nuget to bind a collection):
var list = config.GetSection("logFilePaths").Get<List<string>>();
I need to get a list of SQL server instances present on a computer, get a list of databases in each instance, and then determine how much space each database is taking up.
I can easily grab the instance names from the registry, but I don't have access to query the tables to get the names of the databases. Is there another way of doing this, maybe though WMI?
After some digging around, I finally found the WMI Class that will get my the info I need. On a server where I have 3 instances of SQL Server, I found my data in the following classes
Win32_PerfFormattedData_MSSQLINST2_MSSQLINST2Databases
Win32_PerfFormattedData_MSSQLINST3_MSSQLINST3Databases
Win32_PerfFormattedData_MSSQLSERVER_SQLServerDatabases
My instances are MSSQLINST2, MSSQLINST3 and MSSQLSERVER. I couldn't figure out the naming scheme, so I had to look though all the classes to find out the information I needed. Anyway, here's the code that's working. Maybe someone will find it useful.
ManagementObjectSearcher sqlInstancesSearcher = new ManagementObjectSearcher(
new ManagementScope(#"Root\Microsoft\SqlServer\ComputerManagement10"),
new WqlObjectQuery("select * from SqlServiceAdvancedProperty where propertyindex = 12"),
null);
foreach (ManagementObject instance in sqlInstancesSearcher.Get())
{
string instanceName = instance["ServiceName"].ToString().Replace("$", String.Empty);
Console.WriteLine("INSTANCE: " + instanceName);
ManagementObjectSearcher classNameSearcher = new ManagementObjectSearcher(
new ManagementScope(#"root\cimv2"),
new WqlObjectQuery("select * from meta_class where __CLASS Like 'Win32_PerfFormattedData_" + instanceName + "%Databases%'"),
null);
foreach (ManagementClass wmiClass in classNameSearcher.Get())
{
string className = wmiClass["__CLASS"].ToString();
string query = "select * from " + className;
ManagementObjectSearcher databaseSearcher = new ManagementObjectSearcher(
new ManagementScope(#"root\cimv2"),
new WqlObjectQuery(query),
null);
foreach (ManagementObject database in databaseSearcher.Get())
{
Console.WriteLine(" " + database["Name"]);
Console.WriteLine(" Data Files : " + database["DataFilesSizeKB"]);
Console.WriteLine(" Log Files : " + database["LogFilesSizeKB"]);
Console.WriteLine(" Log Files Used : " + database["LogFilesSizeKB"]);
}
}
}
I'm trying to write an LDAP query which will discover if a user is a member of a group which matches a wildcard query and I'm trying to use the LDAP_MATCHING_RULE_IN_CHAIN OID to do this. I'm basically following example 2 on this page:
http://support.microsoft.com/kb/914828
I've found that this method works well within a domain i.e. if user1 is in group1 and group1 is in group2 then I can write a query matching "*2" and the LDAP query will find the nested relationship and match the user against the group.
However, now I've been asked to support relationships between domains in the same forest. So now I've got:
user1 is a member of group1 in domain 1
group1 in domain 1 is a member of group2 in domain 2
And I want to be able to match user1 against group2.... I can't work out how to make LDAP_MATCHING_RULE_IN_CHAIN do this:
I've tried setting the base of the query to the following:
Domain 1, but this just returns groups in domain 1
The parent domain of domain 1 and domain 2, but this returns no results.
The GC, found by querying "rootDSE" property but this just returns groups inside the domain 1 (which is the GC server)
Anyone know how I can make this work?
As far as I understand, one way of doing that is :
From the RootDSE, look for the configuration NamingContext.
In the configuration NamingContext looking for objects of class crossRef with an attribute nETBIOSName existing.
From these entries use the algorithm you are discribing by using dnsRoot and nCName attributs. A working forest DNS allows you to join a domain controler of dnsRoot. nCName allows to search from the root.
Be careful to do this as a member of the enterpreise administrators group.
Here is an example of the code.
/* Retreiving RootDSE
*/
string ldapBase = "LDAP://WM2008R2ENT:389/";
string sFromWhere = ldapBase + "rootDSE";
DirectoryEntry root = new DirectoryEntry(sFromWhere, "dom\\jpb", "PWD");
string configurationNamingContext = root.Properties["configurationNamingContext"][0].ToString();
/* Retreiving the root of all the domains
*/
sFromWhere = ldapBase + configurationNamingContext;
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", "PWD");
DirectorySearcher dsLookForDomain = new DirectorySearcher(deBase);
dsLookForDomain.Filter = "(&(objectClass=crossRef)(nETBIOSName=*))";
dsLookForDomain.SearchScope = SearchScope.Subtree;
dsLookForDomain.PropertiesToLoad.Add("nCName");
dsLookForDomain.PropertiesToLoad.Add("dnsRoot");
SearchResultCollection srcDomains = dsLookForDomain.FindAll();
foreach (SearchResult aSRDomain in srcDomains)
{
/* For each root look for the groups containing my user
*/
string nCName = aSRDomain.Properties["nCName"][0].ToString();
string dnsRoot = aSRDomain.Properties["dnsRoot"][0].ToString();
/* To find all the groups that "user1" is a member of :
* Set the base to the groups container DN; for example root DN (dc=dom,dc=fr)
* Set the scope to subtree
* Use the following filter :
* (member:1.2.840.113556.1.4.1941:=cn=user1,cn=users,DC=x)
*/
/* Connection to Active Directory
*/
sFromWhere = "LDAP://" + dnsRoot + "/" + nCName;
deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", "PWD");
DirectorySearcher dsLookFor = new DirectorySearcher(deBase);
// you cancomplete the filter here (&(member:1.2.840.113556.1.4.1941:=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)(cn=*2)
dsLookFor.Filter = "(member:1.2.840.113556.1.4.1941:=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)";
dsLookFor.SearchScope = SearchScope.Subtree;
dsLookFor.PropertiesToLoad.Add("cn");
SearchResultCollection srcGroups = dsLookFor.FindAll();
foreach (SearchResult srcGroup in srcGroups)
{
Console.WriteLine("{0}", srcGroup.Path);
}
}
This is just a proof of concept, you have to complete with :
using using(){} form for disposing DirectoryEntry objects
Exception management
Edited (2011-10-18 13:25)
Your comment about the way you solve the problem can be found in a method given in System.DirectoryServices.AccountManagement Namespace. It's a kind of recursive solution. This time, I test with a user belonging to group1 (in an other domain) which belongs to group2 (in a third domain) and it seems to work.
/* Retreiving a principal context
*/
Console.WriteLine("Retreiving a principal context");
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "PWD");
/* Look for all the groups a user belongs to
*/
UserPrincipal aUser = UserPrincipal.FindByIdentity(domainContext, "user1");
PrincipalSearchResult<Principal> a = aUser.GetAuthorizationGroups();
foreach (GroupPrincipal gTmp in a)
{
Console.WriteLine(gTmp.Name);
}
I'm trying to find out the unboundid AttributeSyntax type for a specific attribute name and it's simply not working.
Here's the example test code that I'm using to achieve this:
#Test
public void testLDAPSchema() {
try {
LDAPConnection connection = new LDAPConnection();
connection.connect("hessmain", 389);
connection.bind("CN=Administrator,CN=Users,DC=FISHBOWL,DC=NET", "password");
Schema s = connection.getSchema();
System.out.println(s.toString());
AttributeTypeDefinition atd = s.getAttributeType("directReports");
Set<AttributeTypeDefinition> oat = s.getOperationalAttributeTypes();
Set<AttributeSyntaxDefinition> l = s.getAttributeSyntaxes();
AttributeSyntaxDefinition asd1 = s.getAttributeSyntax(atd.getOID());
AttributeSyntaxDefinition asd2 = s.getAttributeSyntax(atd.getSyntaxOID());
AttributeSyntaxDefinition asd3 = s.getAttributeSyntax(atd.getBaseSyntaxOID());
connection.close();
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
From the above code, all the sets are empty. This also means that no matter which OID I pass to the schema getAttributeSyntax method that I will simply get a null return.
Is there any reason why I can't get the attribute syntaxes from an Active Directory server schema?
Thanks
I don't think that this is specific to the UnboundID LDAP SDK for Java. I'm not sure that Active Directory exposes this information over LDAP. When I perform a general LDAP search to retrieve schema information, I can see the attributeTypes and objectClasses attributes, but ldapSyntaxes isn't returned (and in fact ldapSyntaxes doesn't appear in the list of attribute types).
Similarly, none of the attribute type definitions includes a USAGE element, which is what is used to indicate that the attribute type is operational (e.g., "USAGE directoryOperation").
It may well be that Active Directory simply doesn't report this information at all. It could be that it provides some other non-standard way to get this information (e.g., a control or extended operation, or some other entry that can be retrieved), but if there is then I don't know about it.
I've got an asp application running but i want to search the Active Directory.
i am using vb (visual web developer 2008)
how do i search the active directory for a given user?
ie: user enters login name in text box, clicks submit. active directory is searched on-click for this user. when found user information is displayed .
Thanks
What version of the .NET framework can you use? Searching and looking up stuff in AD has become extremely easy in .NET 3.5 - see this great MSDN article by Ethan Wilanski and Joe Kaplan on using the security principals API for that.
If you're not on .NET 3.5 yet, you'll have to use the DirectorySearcher class and set up the search filters as you need. Getting the LDAP filter right is probably the biggest obstacle.
Robbie Allen also has two great intro article on System.DirectoryServices programming:
- Part 1
- Part 2
There are some really good resources at http://www.directoryprogramming.net (Joe Kaplan's site - he's a Microsoft Active Directory MVP), and Richard Mueller has some great reference excel sheets on what properties are available for each of the ADSI providers, and what they mean, and how their LDAP name is - see http://www.rlmueller.net.
Marc
EDIT: Ok- here's the .NET 2.0 / 3.0 approach:
// set the search root - the AD container to search from
DirectoryEntry searchRoot = new DirectoryEntry("LDAP://dc=yourdomain,dc=com");
// create directory searcher
DirectorySearcher ds = new DirectorySearcher(searchRoot);
ds.SearchScope = SearchScope.Subtree;
// set the properties to load in the search results
// the fewer you load, the better your performance
ds.PropertiesToLoad.Add("cn");
ds.PropertiesToLoad.Add("sn");
ds.PropertiesToLoad.Add("givenName");
ds.PropertiesToLoad.Add("mail");
// set the filter - here I'm using objectCategory since this attribute is
// single-valued and indexed --> much better than objectClass in performance
// the "anr" is the "ambiguous name resolution" property which basically
// searches for all normally interesting name properties
ds.Filter = "(&(objectCategory=person)(anr=user-name-here))";
// get the result collection
SearchResultCollection src = ds.FindAll();
// iterate over the results
foreach (SearchResult sr in src)
{
// do whatever you need to do with the search result
// I'm extracting the properties I specified in the PropertiesToLoad
// mind you - a property might not be set in AD and thus would
// be NULL here (e.g. not included in the Properties collection)
// also, all result properties are really multi-valued, so you need
// to do this trickery to get the first of the values returned
string surname = string.Empty;
if (sr.Properties.Contains("sn"))
{
surname = sr.Properties["sn"][0].ToString();
}
string givenName = string.Empty;
if (sr.Properties.Contains("givenName"))
{
givenName = sr.Properties["givenName"][0].ToString();
}
string email = string.Empty;
if (sr.Properties.Contains("mail"))
{
email = sr.Properties["mail"][0].ToString();
}
Console.WriteLine("Name: {0} {1} / Mail: {2}", givenName, surname, email);
}
Hope this helps!
Marc