How to use condition checking inside LINQ select new{ } - c#

I want to assign all my User properties from active directory into a List< User > properties by using LINQ.
For that I have tried some code but I am not able to assign Manager attribute on List User Manager property.
Because , assign the Manager attribute value from Active directory we need to search the manager user on active directory and based on the search result we need to assign manager attribute value to List of User.Manager property.
Here is my Code,
public List< User > GetADUsers()
{
DirectorySearcher searcher = new DirectorySearcher(ADEntry);
searcher.Filter = "(&(objectClass=user)objectCategory=person)";
SearchResultCollection resultCol = searcher.FindAll();
return
(from serachresult in resultCol.OfType<SearchResult>()
let result = serachresult.GetDirectoryEntry()
result.Properties["sAMAccountName"].Value != null
select new User
{
GivenName = result.Properties.Contains("givenname") ?
Convert.ToString(result.Properties["givenname"][0]) : "",
SurName = result.Properties.Contains("sn") ?
Convert.ToString(result.Properties["sn"][0]) : "",
Location = result.Properties.Contains("physicalDeliveryOfficeName") ?
Convert.ToString(result.Properties["physicalDeliveryOfficeName"][0]) : "",
Manager= ?// Here I need to assign the manager attribute from active directory
}
).ToList();
}
By using below mentioned code, I am taking the manager attribute from Active Directory by using directory entry object. I want to place this code on above mentioned LINQ query
on Manager property. How can we achieve this inside of LINQ Select clause.
DirectoryEntry DomainRoot = AD.GetDirectoryEntry();
using (DirectorySearcher Search = new DirectorySearcher())
{
Search.SearchRoot = DomainRoot;
Search.Filter = "(&(distinguishedName=" +
Convert.ToString(result.Properties["manager"][0]) + "))";
SearchResult Result = Search.FindOne();
if (Result != null)
{
DirectoryEntry Manager = Result.GetDirectoryEntry();
//This Manager.Name value I have assign above mentioned LINQ
user.Manager = Manager.Name.Substring(3);
Manager.Close();
}
}
Please help me to assign the manager name on the LINQ query Manager property place! Thanks.

Try to move your manager evaluation to a new function that takes 'result' and returns Manager name.
And then call it from your link statement: Manager = GetManagerName(result)
public string GetManagerName(DirectoryEntry dirEntry)
{
DirectoryEntry DomainRoot = AD.GetDirectoryEntry();
using (DirectorySearcher search = new DirectorySearcher())
{
search.SearchRoot = DomainRoot;
search.Filter = "(&(distinguishedName=" + Convert.ToString(dirEntry.Properties["manager"][0]) + "))";
SearchResult result = search.FindOne();
if (result != null)
{
using (DirectoryEntry mgr = result.GetDirectoryEntry())
{
return mgr.Name.Substring(3);
}
}
return string.Empty;
}
}

Related

C# Filter List of Active Directory Users & return Active/Enabled Users

I have a list of Users being returned from AD and I need to filter them to just return the Active users. This is my code, but it's not returning any users. After extensive googling, I'm at a loss as to what's missing;
public static List<Models.ToolUser> ActiveUsers()
{
int unlimitedAccess;
//string userAccountControl;
string listEntry;
string fName;
string lName;
string unlimitedAccessGroup;
//This is getting the List of Users that I need to filter
List<Models.ToolUser> activeUserList = UIDal.GetFullWindowsUserList();
try
{
string filter = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
string[] propertiesToLoad = new string[1] { "name" };
using (DirectoryEntry de = GetDirectoryEntryWithGc())
using (DirectorySearcher searcher = new DirectorySearcher(de, filter, propertiesToLoad))
using (SearchResultCollection results = searcher.FindAll())
{
foreach (SearchResult result in results)
{
unlimitedAccess = 0;
fName = result.Properties["givenName"][0].ToString();
lName = result.Properties["sn"][0].ToString();
listEntry = fName + " " + lName;
var name = result.Properties["sAMAccountName"][0].ToString();
var u = new ToolUser
{
ToolUserId = 0,
DomainAccount = result.Properties["sAMAccountName"][0].ToString(),
FirstName = fName,
LastName = lName,
LoginId = "pc-" + result.Properties["sAMAccountName"][0].ToString(),
UnlimitedAccess = unlimitedAccess > 0,
};
activeUserList.Add(u);
}
}
}
catch
{
}
return activeUserList;
}
Empty catch blocks are the devil. You should at least log the exception before continuing.
In this case, your empty catch block is hiding what's really going on. You're getting an "Index was out of range" exception here:
fName = result.Properties["givenName"][0].ToString();
Because result.Properties["givenName"] is an empty collection (there is no element at index 0). That's happening because of this:
string[] propertiesToLoad = new string[1] { "name" };
You are telling the search to only return the name attribute for the objects found, but then you go on to use givenName, sn and sAMAccountName. You need to tell it to return those attributes if you intend to use them:
string[] propertiesToLoad = new string[3] { "givenName", "sn", "sAMAccountName" };
That said, givenName and sn are not required attributes. If those attributes are empty on any of the accounts found, then they will not appear in the Properties collection at all and you will run into the same exception again. So you should test that those attributes are actually there before trying to use them. For example, this will check and set the variables to an empty string if the attribute doesn't exist:
fName = result.Properties.Contains("givenName") ? result.Properties["givenName"][0].ToString() : "";
lName = result.Properties.Contains("sn") ? result.Properties["sn"][0].ToString() : "";

How to update the property values of an Active Directory user

"I want to update the values ​​of several properties of an Active Directory user at the same time,
I try the following method but it does not pass ..."
public void SetAdInfo(string objectFilter,
Dictionary<string, object> objectName,
string ldapPath)
{
string connectionPrefix = "LDAP://" + ldapPath;
DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(cn=" + objectFilter + ")";
mySearcher.PropertiesToLoad.Add("" + objectName + "");
SearchResult result = mySearcher.FindOne();
if (result != null)
{
DirectoryEntry entryToUpdate = result.GetDirectoryEntry();
foreach (var prop in objectName)
{
entryToUpdate.Properties[prop.Key].Value = prop.Value;
entryToUpdate.CommitChanges();
}
}
entry.Close();
entry.Dispose();
mySearcher.Dispose();
}
This is likely your problem right here:
mySearcher.PropertiesToLoad.Add("" + objectName + "");
The objectName parameter is a Dictionary<string, object>, but you're using it like a string. When you do that, .NET calls the .ToString() method on the object, which will end up being something you don't want, like "System.Collections.Generic.Dictionary`2[System.String,System.Object]".
That's likely what's messing up your search.
But you aren't reading the properties of the search results anyway. You're just calling .GetDirectoryEntry() on each result. So you don't even need to set PropertiesToLoad. So just take that line out.
If you did want to read each property from the search results, you need to add each property individually, so you would need to loop through the Dictionary and add each Key to the PropertiesToLoad:
foreach (var prop in objectName) {
mySearcher.PropertiesToLoad.Add(prop.Key);
}

Get all groups of a User in Sharepoint programmatically in C#

What is the best way to access all groups of a SPUser including the Active Directory groups?
SPUser u = someWeb.EnsureUSer(...);
//Only gives SharePoint groups
SPGroupCollection coll = user.Groups;
//Also gives only SharePoint groups
SPGroupCollection groupsonSite = someSPSite.rootWeb.siteGroups
Is there a way to access all groups a user is in, including AD groups?
If you need all users from current site collection , you can access it from hidden list UserInformationList
The User Information List can be accessed (Only if you’re admin) via the browser by navigating to /_catalogs/users/simple.aspx
Read more here :
https://zimmergren.net/sharepoints-hidden-user-list-user-information-list/
From AD :
DirectoryEntry myLdapConnection = new DirectoryEntry("LDAP://YouDomainName");
DirectorySearcher search = new DirectorySearcher(myLdapConnection) { Filter = ("(objectClass=user)") };
search.CacheResults = true;
SearchResultCollection allResults = search.FindAll();
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("UserID");
resultsTable.Columns.Add("EmailID");
foreach (SearchResult searchResult in allResults)
{
MembershipUser myUser = Membership.GetAllUsers()[searchResult.Properties["sAMAccountName"][0].ToString()];
if (myUser == null)
{
DataRow dr = resultsTable.NewRow();
dr["UserID"] = searchResult.Properties["sAMAccountName"][0].ToString();
if (searchResult.Properties["mail"].Count > 0)
{
dr["EmailID"] = searchResult.Properties["mail"][0].ToString();
}
else
{
dr["EmailID"] = "";
}
resultsTable.Rows.Add(dr);
}
else
{ }
}
http://www.dotnetcodesg.com/Article/UploadFile/2/223/Get%20List%20of%20Active%20Directory%20Users%20in%20ASP.NET%20Csharp.aspx

In Active Directory, how do I find all groups I'm the secretary for?

We use the secretary property of Active Directory, which is a multivalued DN property. I want to efficiently find all the groups for which a given user is a listed secretary. What is the best way to perform this query in C#/.NET?
This code will return a list of sAMAccountNames of groups in context's OU that include distinguishedName as one of the secretaries listed:
var filter = "(&(objectClass=group)(secretary=" + distinguishedName + "))";
PrincipalContext context = new PrincipalContext(...); // place to search from
var up = new GroupPrincipal(context);
var list = new List<string>();
using (var searcher = new PrincipalSearcher(up))
{
var ds = searcher.GetUnderlyingSearcher() as DirectorySearcher;
// if you only want to search in a single OU (as defined by 'context')
ds.SearchScope = SearchScope.OneLevel;
ds.Filter = filter;
ds.PropertiesToLoad.Add("sAMAccountName");
var results = ds.FindAll();
foreach (SearchResult r in results)
{
var name = r.GetDirectoryEntry().Properties["sAMAccountName"].Value as string;
list.Add(name);
}
}

Get Windows sAMAccountName by EmployeeID ActiveDirectory in C#.net

I need to get sAMAccountName by passing EmployeeId to the active directory.
Please help me.
I don't know what is the EmployeeId for you but here is how to access all the users and display some fields :
Domain domain = Domain.GetCurrentDomain();
var searchRoot = domain.GetDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("sAMAccountName");
search.PropertiesToLoad.Add("userPrincipalName");
search.PropertiesToLoad.Add("displayName");
SearchResultCollection results = search.FindAll();
if (results != null)
{
foreach(SearchResult result in results)
{
Console.WriteLine("{0} ({1}) sAMAccountName={2}",
result.Properties["displayName"].OfType<object>().FirstOrDefault(),
result.Properties["userPrincipalName"].OfType<object>().FirstOrDefault(),
result.Properties["sAMAccountName"].OfType<object>().FirstOrDefault());
}
}
To discover all the fields present on your schema you can use AdExplorer.
Try this (with many thanks to VirtualBlackFox)
string employeeId ="someEmployeeId";
Domain domain = Domain.GetCurrentDomain();
var searchRoot = domain.GetDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.PropertiesToLoad.Add("EmployeeID");
search.PropertiesToLoad.Add("sAMAccountName");
search.Filter = String.Format("(&(objectCategory=person)(EmployeeID={0}))", employeeId );
SearchResult searchResult =search.FindOne();
if (searchResult != null)
{
object o = searchResult.Properties["sAMAccountName"].OfType<object>().FirstOrDefault();
if (o != null)
{
string sAMAccountName= o.ToString();
}
}

Categories

Resources