Tuesday, August 25, 2020

C# - How to make question into active directory (AD, LDAP)

This example shows all Petr names contained in defined AD:
/* -- question */
DirectoryEntry de = new DirectoryEntry("LDAP://OU=Comp Users,DC=EU,DC=company,DC=local");

/* -- define searcher */

DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectCategory=User)(objectClass=person)(givenname=*petr*))";
ds.Sort = new SortOption( "name", SortDirection.Ascending );
      
/* -- enumerate results */

SearchResultCollection results = ds.FindAll();
    
foreach ( SearchResult sr in results )
{
  string output = "";
  if ( sr.Properties["name"].Count > 0 ) 
  	output+= sr.Properties["name"][0].ToString();
  if ( sr.Properties["mail"].Count > 0 ) 
  	output+= " - " + sr.Properties["mail"][0].ToString();
  if ( sr.Properties["givenname"].Count > 0 ) 
  	output+= " - " + sr.Properties["givenname"][0].ToString();
  if ( sr.Properties["sn"].Count > 0 ) 
  	output+= " - " + sr.Properties["sn"][0].ToString();
  if ( sr.Properties["userPrincipalName"].Count > 0 ) 
  	output+= " - " + sr.Properties["userPrincipalName"][0].ToString();
  if ( sr.Properties["distinguishedName"].Count > 0 ) 
  	output+= " - " + sr.Properties["distinguishedName"][0].ToString();
        
  Console.WriteLine( output );
}
Output:
Bednaro, Petr - Petr.Bednar@company.com - Petr - Bednaro - bednarop@EU.company.local - 
CN=Bednaro\, Petr,OU=Czech Republic,OU=MKPE,OU=Comp Users,DC=EU,DC=company,DC=local

Cepka, Petr - Petr.Cepka@company.com - Petr - Cepka - cepkap@EU.company.local - 
CN=Cepka\, Petr,OU=Czech Republic,OU=BEIC,OU=Comp Users,DC=EU,DC=company,DC=local

Hartigo, Petr - Petr.Hartigo@company.com - Petr - Hartigo - hartigop@EU.company.local - 
CN=Hartigo\, Petr,OU=Czech Republic,OU=MKPE,OU=Comp Users,DC=EU,DC=company,DC=local
For DirectoryEntry is possible use Domain class:
DirectoryEntry de = domain.GetDirectoryEntry();      
If you want filter only for company BEIC, extent the filter in LDAP string:
DirectoryEntry de = new DirectoryEntry("LDAP://OU=BEIC,OU=Comp Users,DC=EU,DC=company,DC=local");

WIN OS - How to get important info about machine

systeminfo
Output:
For another information you can use command:
msinfo

Thursday, August 20, 2020

C# - How to get active domain name

Domain domain;
try {
  domain = Domain.GetCurrentDomain();
  Console.WriteLine( domain.Name );
}
catch ( ActiveDirectoryOperationException e ) {
  Console.WriteLine( "No domain" );
  return;
}
Output:
EU.company.local