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.
Related
I am trying to recursively build a list of all the fields of an object that are of a certain type. Recursion is needed because the object can hold arrays of objects which, in turn, may contain fields of a certain type.
So, if an object has a field of type Wanted, I want that object in the list.
class a
{
Wanted m_var;
};
If an object has an array that contains other objects and these objects contain a field of type Wanted, I'd also like those added to the list.
class b
{
int m_whatever;
a[] m_vararray;
};
I've been trying all sorts of approaches, including Reflection but I am not getting anywhere. All the attempts were some variation of this
private IList<object> ListOfTypeWanted(object fields)
{
IList<object> result = new List<object>();
System.Reflection.MemberInfo info = fields.GetType();
object[] properties = type.GetProperties();
foreach (var p in properties)
{
if (true == p.GetType().IsArray)
{
result.Add(ListOfTypeWanted(p));
}
else
{
Type t = p.GetType();
if (p is WantedType)
{
result.Add(this);
}
}
}
return result;
}
I've also tried Linq statements using Where() but they did not get me any useful results either.
Does anyone know what the best way is to achieve this?
Your question contains many typo and syntax error, but I can advise few:
Make sure you want GetProperties not GetFields. Your example seems like you only have fields, not properties.
Make sure you are providing proper BindingFlags when calling GetProperties. Your example seems like containing private member. In that case BindingFlags.NonPublic | BindingFlags.Instance should be used.
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]`
}
}
}
}
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());
}
}
}
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 am attempting to create a Clipboard stack in C#. Clipboard data is stored in System.Windows.Forms.DataObject objects. I wanted to store each clipboard entry (IDataObject) directly in a Generic list. Due to the way Bitmaps (seem to be) stored I am thinking I need to perform a deep copy first before I add it to the list.
I attempted to use Binary serialization (see below) to create a deep copy but since System.Windows.Forms.DataObject is not marked as serializable the serialization step fails. Any ideas?
public IDataObject GetClipboardData()
{
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, Clipboard.GetDataObject());
memoryStream.Position = 0;
return (IDataObject) binaryFormatter.Deserialize(memoryStream);
}
I wrote the code below for another question and maybe it could come in useful for you in this scenario:
public static class GhettoSerializer
{
// you could make this a factory method if your type
// has a constructor that appeals to you (i.e. default
// parameterless constructor)
public static void Initialize<T>(T instance, IDictionary<string, object> values)
{
var props = typeof(T).GetProperties();
// my approach does nothing to handle rare properties with array indexers
var matches = props.Join(
values,
pi => pi.Name,
kvp => kvp.Key,
(property, kvp) =>
new {
Set = new Action<object,object,object[]>(property.SetValue),
kvp.Value
}
);
foreach (var match in matches)
match.Set(instance, match.Value, null);
}
public static IDictionary<string, object> Serialize<T>(T instance)
{
var props = typeof(T).GetProperties();
var ret = new Dictionary<string, object>();
foreach (var property in props)
{
if (!property.CanWrite || !property.CanRead)
continue;
ret.Add(property.Name, property.GetValue(instance, null));
}
return ret;
}
}
However I don't think this will be the final solution to your problem though it may give you a place to start.
Look up the docks for Serializable and find the stuff about serialization helpers. You can wrap the bitmap in your own serialization code the integrates with the .net framework.
Copy of my answer to: difference between DataContract attribute and Serializable attribute in .net
My answer fits much better here than there, although above question ends with:
"... or maybe a different way of creating a deepclone?"
I once did some inspection to an object structure via Reflection to find all assemblies required for deserialization and serialize them alongside for bootstrapping.
With a bit of work one could build a similar method for deep copying. Basically you need a recursive method that carrys along a Dictionary to detect circular references. Inside the method you inspect all fields about like this:
private void InspectRecursively(object input,
Dictionary<object, bool> processedObjects)
{
if ((input != null) && !processedObjects.ContainsKey(input))
{
processedObjects.Add(input, true);
List<FieldInfo> fields = type.GetFields(BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic );
foreach (FieldInfo field in fields)
{
object nextInput = field.GetValue(input);
if (nextInput is System.Collections.IEnumerable)
{
System.Collections.IEnumerator enumerator = (nextInput as
System.Collections.IEnumerable).GetEnumerator();
while (enumerator.MoveNext())
{
InspectRecursively(enumerator.Current, processedObjects);
}
}
else
{
InspectRecursively(nextInput, processedObjects);
}
}
}
}
To get it working you need to add an output object and something like System.Runtime.Serialization.FormatterServices.GetUninitializedObject(Type type) to create the most shallowest copy (even without copying references) of each field's value. Finally you can set each field with something like field.SetValue(input, output)
However this implementation does not support registered event handlers, which is _un_supported by deserializing, too. Additionally each object in the hierarchy will be broken, if its class' constructor needs to initialize anything but setting all fields. The last point only work with serialization, if the class has a respective implementation, e.g. method marked [OnDeserialized], implements ISerializable,... .