I'm trying to find several properties that aren't used anywhere in our AD environment. I don't care what the property name is as long as it isn't used.
I was attempting to do this in C# mainly so that I can explore those classes while I solved this problem, but can't seem to find a way to list all of the properties for an object. The DirectoryEntry.Properties returns a collection of set properties only (as far as I can tell).
So is it possible to view all the active (available) properties for an object or are you only able to view the ones that are currently set with a value somewhere?
EDIT: Current code...
using (var directoryObject = new DirectoryEntry("LDAP://CN=GroupCN,OU=groups,DC=domain,DC=com", "uid", "pass", AuthenticationTypes.ReadonlyServer)) {
foreach (var prop in directoryObject.Properties.PropertyNames) {
Console.WriteLine(prop.ToString() + " | " + directoryObject.Properties[prop.ToString()].Value.ToString());
}
}
Edit: Ok. So I missed the bit about all possible properties. So I will address that.
Since the DirectoryEntry object is an implementation of IDictionary, there really is no way to know what properties can be set. IDictionary will allow you to add as many custom properties as you would like to the object. The documentation for System.DirectoryServices.Property collection is here: http://msdn.microsoft.com/en-us/library/system.directoryservices.propertycollection(v=vs.100).aspx
The below will enumerate all the current properties of the results of an LDAP search. You could adapt this to find all the properties that are currently used on the objects returned in the search result.
foreach (SearchResult item in searchResultCollection)
{
foreach (string propKey in item.Properties.PropertyNames)
{
foreach (object property in item.Properties[propKey])
{
Console.WriteLine("{0} : {1}", propKey, property.ToString());
}
}
}
Related
NOTE #1: This is in Unity, so I mention a scene, if you don't know what that is, don't worry about it, it doesn't apply too much to this question.
NOTE #2: I have looked at multiple other stack overflow posts on this subject, but they were very confusing to me, and I don't have enough reputation yet to comment, so I couldn't ask for clarification on how to use the code solutions given.
I have two custom attributes that I made, AutoSave and AutoLoad, and I want to get a List of all of their data, like the name of the field, the data that the field stores, no matter the type, and the stuff that the attribute call is given, for AutoSave: a string for the file path, a string for the scene name, a enum for the save type (which stores whether or not it will save during the beginning, the end, or when a method is called with the name of this field) and an enum for the settings (which stores whether it will write over what is currently there, or add to what is there (which is a work in progress)). And for AutoLoad: a string for the file path, a string for the scene name, and a enum for the load type (which is the exact same as the AutoSave attribute).
The code that I saw that I would like to use to sort and store is this:
Type type = typeof(AutoLoad);
foreach (PropertyInfo prop in type.GetProperties())
{
var props = from p in this.GetType().GetProperties()
let attr = p.GetCustomAttributes(typeof(AutoLoad), true)
where attr.Length == 1
select new { Property = p, Attribute = attr.First() as AutoLoad };
}
I am not sure if this is right, and I dont know how to implement, sort and store this data. If I am reading this properly, this is LINQ querying, which I am not familiar with. And I am brand new to Attributes, so if I am missing something, please let me know, and an explanation of how this code works would be nice as well.
I would store these in 6 Dictionary<string, List<WhateverTypeICanStoreTheseAs>>, the string being the scene name, the List being a list of every of this data that has that particular scene name attached. 3 dictionaries for saving, 3 for loading, each one having 1 dictionary for the beginning, 1 for the custom times, and 1 for the end. If there is a better way to store this data, please let me know!
If anyone is familiar with attributes, thanks for the help!
EDIT:
Here is my current implementation of the above code, it returns nothing when calling ToString, and returns 1 when checking outer count, and returns 0 when checking inner count.:
public static List<List<AutoSType>> GetAllOfAttribute()
{
Type type = typeof(AutoSave);
List<List<AutoSType>> objs = new List<List<AutoSType>>();
foreach (PropertyInfo prop in type.GetProperties())
{
var props = from p in prop.GetType().GetProperties()
let attr = p.GetCustomAttributes(typeof(AutoSave), true)
where attr.Length == 1
select new AutoSType { Property = p, Attribute = attr.First() as AutoSave };
objs.Add(props.ToList());
}
return objs;
}
Using the method:
List<List<AutoSType>> autoSObjs = AutoSave.GetAllOfAttribute();
Debug.Log(autoSObjs.Count);
if(autoSObjs.Count > 0)
{
Debug.Log(autoSObjs[0].Count);
}
foreach(List<AutoSType> a in autoSObjs)
{
foreach(AutoSType b in a)
{
string temp = b.Attribute.ToString();
Debug.Log(temp);
}
}
ToString override:
public override string ToString()
{
return $"{filePath}, {sceneName}, {saveType.ToString()}, {saveSettings.ToString()}";
}
Using the attribute:
[AutoSave("", "Main", AutoSave.SaveType.Beginning, AutoSave.SaveSettings.AddTo)]
public int endDate;
[AutoSave("", "Main", AutoSave.SaveType.Beginning, AutoSave.SaveSettings.AddTo)]
public string startDay;
It sounds like you're trying to find all instances of AutoSave and do something based upon that. But look at your code.
If we translate your GetAllOfAttribute to psuedo-code we get
Get the type definition for AutoSave
Initialize a list to save our List<List<AutoSType>>
Iterate all of the properties on AutoSave (wait, why?)
For each property on autoSave, get the properties on the PropertyInfo class, but only if that property on PropertyInfo has an [AutoSave] on it (Pretty sure we just went WAY off the rails here)
Instead you want to
Get all types in your assembly
For those types, filter those to the ones that contain a property with [AutoSave] on it, then operate on that type/property.
Also, as with just about anything using reflection this is going to be resource-intensive so ensure you only run it once, or once per scene. You can possibly add a class-level attribute that it can key off of to avoid iterating properties on classes you don't want looked at like creating an [AutoSaveEnabled] you can attach to the class.
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if (type.GetCustomAttribute<AutoSaveEnabled>(true) != null)
{
foreach (PropertyInfo prop in type.GetProperties())
{
AutoSave attr = prop.GetCustomAttribute<AutoSave>(true);
if (attr != null)
{
// I found the attribute!!!
// At this point, type is the class I'm looking at, prop is the decorated property, and attr is the instance of `[AutoSave]`
}
}
}
}
When you deal with JSON, it's really easy to make C# models. You either Paste special in Visual Studio, or you use one of the many available tools online.
ElasticSearch responses obviously are JSON, meaning, if you can get the responding JSON, you're good to go. However, if you just have a connection-string and simply want to "map" all the ElasticSearch objects into your C# code - how do you do it?
My question:
Is there a way to see all fields/data in an ElasticSearch instance, and then easily get the JSON, so you can get strongly typed models?
You can query elasticsearch for mappings. Mapping will contain all information you need to build model in C# (but you will still have to build it by hand I think). Example using database from your previous question:
var settings = new ConnectionSettings(new Uri("http://distribution.virk.dk/cvr-permanent"));
var client = new ElasticClient(settings);
// get mappings for all indexes and types
var mappings = client.GetMapping<JObject>(c => c.AllIndices().AllTypes());
foreach (var indexMapping in mappings.Indices) {
Console.WriteLine($"Index {indexMapping.Key.Name}"); // index name
foreach (var typeMapping in indexMapping.Value.Mappings) {
Console.WriteLine($"Type {typeMapping.Key.Name}"); // type name
foreach (var property in typeMapping.Value.Properties) {
// property name and type. There might be more useful info, check other properties of `typeMapping`
Console.WriteLine(property.Key.Name + ": " + property.Value.Type);
// some properties are themselves objects, so you need to go deeper
var subProperties = (property.Value as ObjectProperty)?.Properties;
if (subProperties != null) {
// here you can build recursive function to get also sub-properties
}
}
}
}
I have a reference to a user object, the Properties collection of this object will only contain properties that have values set but I need to check if a property (by name) exists for this object - I guess this would come from the schema.
I have looked at deUser.SchemaEntry, but I can't find any useful property info from this object.
Any ideas?
DirectoryEntry deUser = new DirectoryEntry(path);
foreach (var prop in deUser.Properties)
{
//if user.Properties["company"] is not set on this user then
//it will not be available here although 'company' is
//a property defined for the user class
}
//How do I get to the list of all available properties using
//deUserSchema as below
DirectoryEntry deUserSchema = deUser.SchemaEntry();
The problem turned out to be easier to solve than it appeared. In each object (DirectoryEntry) in AD there are dynamic properties named allowedAttributes and allowedAttributesEffective.
On standard retrieval by de.Attributes [], returns null. You must first force the rebuild of the object cache (de.RefreshCache) with these parameters.
My code:
public static List<string> AllAvailableProperties(this DirectoryEntry de)
{
de.RefreshCache(new string[] { "allowedAttributes" });
return de.Properties["allowedAttributes"].AsStringList();
}
If we want a list of attributes for a class, we should take any object (existing) of this class.
To list all properties try this :
foreach (var name in deUser.Properties.PropertyNames)
{
Console.WriteLine(name);
}
According to MSDN you can use DirectoryEntry.SchemaEntry to retrieve all attributes.
An entry's schema determines a list of its mandatory and optional property names.
You can use this property to find out what properties and methods are available on the associated object.
String myADSPath = "LDAP://onecity/CN=Users,DC=onecity,DC=corp,DC=fabrikam,DC=com";
// Creates an Instance of DirectoryEntry.
DirectoryEntry myDirectoryEntry=new DirectoryEntry(myADSPath, UserName, SecurelyStoredPassword);
// Gets the SchemaEntry of the ADS object.
DirectoryEntry mySchemaEntry = myDirectoryEntry.SchemaEntry;
if (string.Compare(mySchemaEntry.Name,"container") == 0)
{
foreach(DirectoryEntry myChildDirectoryEntry in myDirectoryEntry.Children)
{
//...do what you need
}
}
I have a custom entity in a relational database that I have mapped to the CLR via a domain model. So by using the following statement, I can pull in an entity from my database into memory via a LINQ query on the domain model, like so;
var inspection = (from i in dbContext.New_testinspectionExtensionBases
where i.New_testinspectionId == currentInspection
select i).First();
There are properties/fields on this entity that I need access to, I need to be able to determine the property/field name as well as it's value. I want to loop through these items in memory, and write out their names and values to the console.
I tried using this approach, but couldn't figure out how to correct the syntax (Nor am I sure that GetProperties is the correct method to use, GetFields wasn't returning anything for some reason so I assumed this was the way to go) but it doesn't really matter since all i need is read access to the value;
var inspectionReportFields = inspection.GetType().GetProperties();
// I called this inspectionReportfields because the entity properties correspond to
// form/report fields I'm generating from this data.
foreach (var reportField in inspectionReportFields)
{
var value = reportField.GetValue();
Console.WriteLine(reportField.Name);
Console.WriteLine(value);
}
Is there an easier way to get the property/field value when utilizing a domain model like EF or openaccess? If not, am I going about it the right way? And lastly, if so, how do I fix the syntax in the value variable declaration?
Here are some sample fields/properties from the code generated by the domain model, for reference;
private int? _new_systemGauges;
public virtual int? New_systemGauges
{
get
{
return this._new_systemGauges;
}
set
{
this._new_systemGauges = value;
}
}
private int? _new_systemAlarm ;
public virtual int? New_systemAlarm
{
get
{
return this._new_systemAlarm;
}
set
{
this._new_systemAlarm = value;
}
}
I assume that you're trying to define a general-purpose way to "dump" an object without knowing anything about its structure. If so, then you are going about things the correct way. You use reflection (GetType() and the associated Type class methods) to inspect the object and return its information.
The reason GetFields() didn't return anything is that you likely did not supply the right binding flags. In particular, if you call the overload that doesn't take any parameters, you only get back public fields; if you want private fields you need to ask for them specifically.
In your case, GetFields(BindingFlags.NonPublic) would give you back the _new_systemGauges and _new_systemAlarm fields, while GetProperties() would give you back the New_systemAlarm and New_systemAlarm properties.
The other key element you missed is that the data you are getting back is the type metadata; it defines the structure of the class, and not any particular instance. If you want to know what the value of a property for a specific instance is, you need to ask for that:
foreach (var prop in obj.GetType().GetProperties())
{
Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj, null));
}
One you have one of the PropertyInfo elements from the type's metadata, you can ask for that property value on any instance of that type. It doesn't have to be the same instance that you originally used. For example:
var objs = somelist.Where(x => x.Id == 1);
foreach (var prop in objs.First().GetType().GetProperties())
{
int x = 0;
foreach (var obj in objs)
{
if (prop.PropertyType.Name.Equals("Int32"))
{
int val = (int)prop.GetValue(obj, null);
Console.WriteLine("Obj #{0}: {1} = 0x{2:x8}", x++, prop.Name, val);
}
else if (prop.PropertyType.Name.Equals("Decimal"))
{
int val = (decimal)prop.GetValue(obj, null);
Console.WriteLine("Obj #{0}: {1} = {2:c2}", x++, prop.Name, val);
}
else
{
Console.WriteLine("Obj #{0}: {1} = '{2}'", x++, prop.Name, prop.GetValue(obj, null));
}
}
}
Technically you should check the result of GetIndexParameters to see if a property is indexed or not; the null parameter to GetValue is actually an array of index values.
To convert the value you get back you can either use typecasts, or if you want to be a bit more flexible, use the Convert class's methods. The difference is, for example, if you have a short property, GetValue() will return a boxed short, which you cannot then typecast as an int; you have to unbox it to a short first. Using Convert.ToInt32() will perform all of the needed steps to get an int value out of any property that is convertible to an integer.
Converting between reference types is easier since you can just use is and as for that; those work just like you'd expect with "reflected" property values.
GetProperties indeed is the correct method.
To get rid of the compiler error, change your code to this:
var value = reportField.GetValue(inspection, null);
You need to pass the instance from which you want to obtain the value, as a PropertyInfo object is not bound to any specific class instance.
Please consider following the standard .NET naming rules.
This would lead to the following:
NewSystemAlarm instead of New_systemAlarm
newSystemAlarm or _newSystemAlarm instead of _new_systemAlarm
NewTestInspectionExtensionBases instead of New_testinspectionExtensionBases
NewTestInspectionId instead of New_testinspectionId
If you are using OpenAccess you always have the complete information about your model classes at your disposal. The information there is retrieved from your mapping which means that you needn't reflect over your classes (no overhead).
Just browse trough context.Metadata.PersistentTypes for all of your classes mapping information.
I have List (Of Report). Report has 90 properties. I dont want write them each and every propertiy to get values for properties. Is there any waht to get propeties values from the List
Ex:
Dim mReports as new List(Of Reports)
mReport = GetReports()
For each mReport as Report In mReports
'Here I want get all properties values without writing property names
next
You can use reflection:
static readonly PropertyInfo[] properties = typeof(Reports).GetProperties();
foreach(var property in properties) {
property.GetValue(someInstance);
}
However, it will be slow.
In general, a class with 90 proeprties is poor design.
Consider using a Dictionary or rethinking your design.
PropertyInfo[] props =
obj.GetType().GetProperties(BindingFlags.Public |BindingFlags.Static);
foreach (PropertyInfo p in props)
{
Console.WriteLine(p.Name);
}
Sounds like a good fit for reflection or meta-programming (depending on the performance required).
var props=typeof(Report).GetProperties();
foreach(var row in list)
foreach(var prop in props)
Console.WriteLine("{0}={1}",
prop.Name,
prop.GetValue(row));
I don't speak VB.NET fluently, but you can easily translate something like this to VB.NET.
var properties = typeof(Report).GetProperties();
foreach(var mReport in mReports) {
foreach(var property in properties) {
object value = property.GetValue(mReport, null);
Console.WriteLine(value.ToString());
}
}
This is called reflection. You can read about its uses in .NET on MSDN. I used Type.GetProperties to get the list of properties, and PropertyInfo.GetValue to read the values. You might need to add various BindingFlags or check properties like PropertyInfo.CanRead to get exactly the properties that you want. Additionally, if you have any indexed properties, you will have to adjust the second parameter to GetValue accordingly.