Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not familiar with DirectoryServices, but if I got your question right you could use reflections to set the properties of your User object. To set the correct properties you should match names of the properties with data saved in the attributes on the properties of the User's object.</p> <pre><code> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class DirectoryAttributeAttribute : Attribute { public DirectoryAttributeAttribute(string propertyName) { PropertyName = propertyName; } public string PropertyName { get; set; } } public class User { [DirectoryAttributeAttribute("SAMAccountName")] public string AccountName { get; set; } [DirectoryAttributeAttribute("givenName")] public string FirstName { get; set; } } // Finds property info by name. public static PropertyInfo FindProperty(this Type type, string propertyName) { foreach (PropertyInfo propertyInfo in type.GetProperties()) { object[] attributes = propertyInfo.GetCustomAttributes(typeof(DirectoryAttributeAttribute, false)); foreach (DirectoryAttributeAttribute attribute in attributes) { if (attribute.PropertyName == propertyName) { return propertyInfo; } } } return null; } SearchResult searchResult = ...; if (searchResult != null) { User user = new User(); Type userType = typeof (User); foreach (string propertyName in searchResult.Properties.PropertyNames) { // Find property using reflections. PropertyInfo propertyInfo = userType.FindProperty(propertyName); if (propertyInfo != null) // User object have property with DirectoryAttributeAttribute and matching name assigned. { // Set value using reflections. propertyInfo.SetValue(user, searchResult.Properties[propertyName]); } } } </code></pre> <p>If names of the properties you are going to fill can change you can store mapping of properties in Dictionary.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload