Clear all string members from object in C# - c#

I have a class that contains about 500 String members and I'd like to "reset" them all by setting them to String.Empty. Can anybody tell me how to do this using reflection so I can iterate over every String member ?
Thanks

typeof(MyClass).GetProperties()
.Where(p => p.PropertyType == typeof(string))
.ToList()
.ForEach(p => p.SetValue(myObj,string.Empty, null));
EDIT:
If you are dealing with fields and not properties, it's very similar
typeof(MyClass).GetFields()
.Where(f => f.FieldType == typeof(string))
.ToList()
.ForEach(f => f.SetValue(myObj,string.Empty));

foreach (PropertyInfo pi in MyObj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ).ToArray() )
{
if (pi.PropertyType == typeof(string))
{
pi.SetValue(MyObj, string.Empty, null);
}
}
For fields use
foreach (FieldInfo fi in MyObj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic ).ToArray() )
{
if (fi.FieldType == typeof(string))
{
fi.SetValue(MyObj, string.Empty);
}
}

Same code implemented using compiled Expression-Tree:
private static Action<TObject> CreateClearStringProperties<TObject>()
{
var memberAccessExpressions = new List<System.Linq.Expressions.Expression>();
System.Linq.Expressions.ParameterExpression arg = System.Linq.Expressions.Expression.Parameter(typeof(TObject), "x");
foreach (var propertyInfo in typeof(TObject).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy))
{
if (propertyInfo.PropertyType == typeof(string) && propertyInfo.SetMethod != null)
{
var memberAccess = System.Linq.Expressions.Expression.MakeMemberAccess(arg, propertyInfo);
var assignment = System.Linq.Expressions.Expression.Assign(memberAccess, System.Linq.Expressions.Expression.Constant(string.Empty));
memberAccessExpressions.Add(assignment);
}
}
foreach (var fieldInfo in typeof(TObject).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy))
{
if (fieldInfo.FieldType == typeof(string))
{
var memberAccess = System.Linq.Expressions.Expression.MakeMemberAccess(arg, fieldInfo);
var assignment = System.Linq.Expressions.Expression.Assign(memberAccess, System.Linq.Expressions.Expression.Constant(string.Empty));
memberAccessExpressions.Add(assignment);
}
}
if (memberAccessExpressions.Count == 0)
return new Action<TObject>((e) => { });
var allProperties = System.Linq.Enumerable.Aggregate(memberAccessExpressions, System.Linq.Expressions.Expression.Block);
return System.Linq.Expressions.Expression.Lambda<Action<TObject>>(allProperties, arg).Compile();
}
Example of how to use it:
Action<MyClass> clearObject = CreateClearStringProperties<MyClass>();
MyClass obj = new MyClass();
clearObject(obj);
Needed it for some generic pooling logic, where objects put back into the pool should not keep obsolete string-objects alive.

Related

How can I get the Cache Item Priority of an HttpRuntime.Cache object?

Is it possible to get the Cache item priority of an HttpRuntime.Cache object?
If so, what would be the best approach?
You may use this :
public static DateTime GetCachePriority(string strKey)
{
object cacheProvider = HttpRuntime.Cache.GetType().GetProperty("InternalCache", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(HttpRuntime.Cache, null);
object intenralCacheStore = cacheProvider?.GetType().GetField("_cacheInternal", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(cacheProvider);
if(intenralCacheStore != null)
{
Type cacheOption = HttpRuntime.Cache.GetType().Assembly.GetTypes().FirstOrDefault(d => d.Name == "CacheGetOptions");
MethodInfo methodInfo = intenralCacheStore.GetType().GetMethod("DoGet", BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Any,
new[] { typeof(bool), typeof(string), cacheOption }, null);
if(methodInfo != null)
{
dynamic cacheEntry = methodInfo.Invoke(intenralCacheStore, new Object[] { true, strKey, 1 });
PropertyInfo usageBucketProperty = cacheEntry.GetType().GetProperty("UsageBucket", BindingFlags.NonPublic | BindingFlags.Instance);
byte byPriority = (byte) usageBucketProperty.GetValue(cacheEntry, null);
CacheItemPriority prriority = byPriority == byte.MaxValue ? CacheItemPriority.NotRemovable : (CacheItemPriority)byPriority + 1;
strPriority = prriority.ToString();
}
}
}
Thanks.

List all custom data stored in AppDomain

In order to store the state of processes when an error occured, I would like to list all (custom) data stored in AppDomain (by SetData).
The LocalStore property is private and AppDomain class not inheritable.
Is there any way to enumerate those data ?
AppDomain domain = AppDomain.CurrentDomain;
domain.SetData("testKey", "testValue");
FieldInfo[] fieldInfoArr = domain.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo fieldInfo in fieldInfoArr)
{
if (string.Compare(fieldInfo.Name, "_LocalStore", true) != 0)
continue;
Object value = fieldInfo.GetValue(domain);
if (!(value is Dictionary<string,object[]>))
return;
Dictionary<string, object[]> localStore = (Dictionary<string, object[]>)value;
foreach (var item in localStore)
{
Object[] values = (Object[])item.Value;
foreach (var val in values)
{
if (val == null)
continue;
Console.WriteLine(item.Key + " " + val.ToString());
}
}
}
Based on Frank59's answer but a bit more concise:
var appDomain = AppDomain.CurrentDomain;
var flags = BindingFlags.NonPublic | BindingFlags.Instance;
var fieldInfo = appDomain.GetType().GetField("_LocalStore", flags);
if (fieldInfo == null)
return;
var localStore = fieldInfo.GetValue(appDomain) as Dictionary<string, object[]>;
if (localStore == null)
return;
foreach (var key in localStore.Keys)
{
var nonNullValues = localStore[key].Where(v => v != null);
Console.WriteLine(key + ": " + string.Join(", ", nonNullValues));
}
Same solution, but as an F# extension method. May not need the null check.
https://gist.github.com/ctaggart/30555d3faf94b4d0ff98
type AppDomain with
member x.LocalStore
with get() =
let f = x.GetType().GetField("_LocalStore", BindingFlags.NonPublic ||| BindingFlags.Instance)
if f = null then Dictionary<string, obj[]>()
else f.GetValue x :?> Dictionary<string, obj[]>
let printAppDomainObjectCache() =
for KeyValue(k,v) in AppDomain.CurrentDomain.LocalStore do
printfn "%s" k

List all SystemColors

In Windows.Forms, I need to create a program which accepts any color and tries to find the corresponding system colors to it.
I was not able to figure out how to loop through all Colors of the System.Drawing.SystemColors class - it's a class, not an enum or a List.
How can I do this (some kind of reflection?)?
How about
public static Dictionary<string,object> GetStaticPropertyBag(Type t)
{
const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
var map = new Dictionary<string, object>();
foreach (var prop in t.GetProperties(flags))
{
map[prop.Name] = prop.GetValue(null, null);
}
return map;
}
or
foreach (System.Reflection.PropertyInfo prop in typeof(SystemColors).GetProperties())
{
if (prop.PropertyType.FullName == "System.Drawing.Color")
ColorComboBox.Items.Add(prop.Name);
}
And I cooked something up.
var typeToCheckTo = typeof(System.Drawing.Color);
var type = typeof(System.Drawing.SystemColors);
var fields = type.GetProperties(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).Where(p => p.PropertyType.Equals(typeToCheckTo));
foreach (var field in fields)
{
Console.WriteLine(field.Name + field.GetValue(null, null));
}

Same Variable Names - 2 Different Classes - How To Copy Values From One To Another - Reflection - C#

Without using AutoMapper... (because someone in charge of this project will shit bricks when they see dependencies)
I have a class (class A) with however many properties. I have another class (class B) with those same properties (same names and type). Class B could also have other un related variables.
Is there some simple reflection code that can copy values from class A to class B?
The simpler the better.
Type typeB = b.GetType();
foreach (PropertyInfo property in a.GetType().GetProperties())
{
if (!property.CanRead || (property.GetIndexParameters().Length > 0))
continue;
PropertyInfo other = typeB.GetProperty(property.Name);
if ((other != null) && (other.CanWrite))
other.SetValue(b, property.GetValue(a, null), null);
}
This?
static void Copy(object a, object b)
{
foreach (PropertyInfo propA in a.GetType().GetProperties())
{
PropertyInfo propB = b.GetType().GetProperty(propA.Name);
propB.SetValue(b, propA.GetValue(a, null), null);
}
}
If you will use it for more than one object then it may be useful to get mapper:
public static Action<TIn, TOut> GetMapper<TIn, TOut>()
{
var aProperties = typeof(TIn).GetProperties();
var bType = typeof (TOut);
var result = from aProperty in aProperties
let bProperty = bType.GetProperty(aProperty.Name)
where bProperty != null &&
aProperty.CanRead &&
bProperty.CanWrite
select new {
aGetter = aProperty.GetGetMethod(),
bSetter = bProperty.GetSetMethod()
};
return (a, b) =>
{
foreach (var properties in result)
{
var propertyValue = properties.aGetter.Invoke(a, null);
properties.bSetter.Invoke(b, new[] { propertyValue });
}
};
}
I know you asked for reflection code and It's an old post but I have a different suggestion and wanted to share it. It could be more faster than reflection.
You can serialize the input object to json string, then deserialize to output object. All the properties with same name will assign to new object's properties automatically.
var json = JsonConvert.SerializeObject(a);
var b = JsonConvert.DeserializeObject<T>(json);
Try this:-
PropertyInfo[] aProps = typeof(A).GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Default | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
PropertyInfo[] bProps = typeof(B).GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Default | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
foreach (PropertyInfo pi in aProps)
{
PropertyInfo infoObj = bProps.Where(info => info.Name == pi.Name).First();
if (infoObj != null)
{
infoObj.SetValue(second, pi.GetValue(first, null), null);
}
}

Saving a class to a delim file using reflection

I want to write the property names and matching data to a delimited file, I've copied some code from the c# objectdumper help file and it all seems to work OK but I dont understand reflection enough to be confident to use it. What I'm worried about is an incorrect value being placed in the incorrect column, is it possible for this to happen e.g.
Field1,Field2
Val1,Val2
Val1,Val2
Val2,Val1 << Could this ever happen ?
Also what does this piece of code mean?
f != null ? f.GetValue(this) : p.GetValue(this, null)
Code below:
public string returnRec(bool header, string delim)
{
string returnString = "";
bool propWritten = false;
MemberInfo[] members = this.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
foreach (MemberInfo m in members)
{
FieldInfo f = m as FieldInfo;
PropertyInfo p = m as PropertyInfo;
if (f != null || p != null)
{
if (propWritten)
{
returnString += delim;
}
else
{
propWritten = true;
}
if (header)
returnString += m.Name;
else
{
Type t = f != null ? f.FieldType : p.PropertyType;
if (t.IsValueType || t == typeof(string))
{
returnString += f != null ? f.GetValue(this) : p.GetValue(this, null);
}
}
}
}
return returnString;
}
Type t = f != null ? f.FieldType : p.PropertyType;
this is an inline if, asking is f != null then f.FieldType else p.PropertyType
can be written as
Type t;
if (f != null)
t = f.FieldType;
else
t = p.PropertyType;
#astander and #Frederik have essentially answered the questions and concerns that you specifically voiced, but I'd like to suggest doing things in a slightly more efficient manner. Depending on the number of object instances that you wish to write to your file, the method that you've presented may end up being quite inefficient. That's because you're gleaning type and value information via reflection on every iteration, which is unnecessary.
What you're looking for is something that looks up type information once, and then only uses reflection to get the value of properties and fields, e.g. (.NET 3.5),
public static IEnumerable<string> ReturnRecs(IEnumerable items, bool returnHeader, string delimiter)
{
bool haveFoundMembers = false;
bool haveOutputHeader = false;
PropertyInfo[] properties = null;
FieldInfo[] fields = null;
foreach (var item in items)
{
if (!haveFoundMembers)
{
Type type = item.GetType();
properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(pi => pi.PropertyType.IsValueType || pi.PropertyType == typeof (string)).ToArray();
fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance)
.Where(fi => fi.FieldType.IsValueType || fi.FieldType == typeof(string)).ToArray();
haveFoundMembers = true;
}
if (!haveOutputHeader)
{
yield return String.Join(delimiter, properties.Select(pi => pi.Name)
.Concat(fields.Select(pi => pi.Name)).ToArray());
haveOutputHeader = true;
}
yield return String.Join(delimiter,
properties.Select(pi => pi.GetValue(item, null).ToString())
.Concat(fields.Select(fi => fi.GetValue(item).ToString())).ToArray());
}
The above code only ever performs a GetProperties and GetFields once per group of records--also, because of this, there's no need to explicitly sort the properties and fields as was #Frederik's suggestion.
#astander has already given you an answer on the Type t = f != null ? f.FieldType : p.PropertyType; question, so I will leave that one out. Regarding getting the values into the correct columns, I don't know wheter reflection guarantees to list the members of a type in a specific order, but you can guarantee it by sorting the list before using it (using Linq):
MemberInfo[] members = typeof(Item).GetMembers(BindingFlags.Public | BindingFlags.Instance);
IEnumerable<MemberInfo> sortedMembers = members.OrderBy(m => m.Name);
foreach (MemberInfo member in sortedMembers)
{
// write info to file
}
Or if you prefer a non-Linq approach (works with .NET Framework 2.0):
MemberInfo[] members = typeof(Item).GetMembers(BindingFlags.Public | BindingFlags.Instance);
Array.Sort(members, delegate(MemberInfo x, MemberInfo y){
return x.Name.CompareTo(y.Name);
});
foreach (MemberInfo member in members)
{
// write info to file
}
Just to add some thoughts re the accepted answer, in particular for large data volumes:
PropertyInfo etc can be unnecessarily slow; there are ways to avoid this, for example using HyperDescriptor or other dynamic code
rather than building lots of intermediate strings, it may be more efficient to write output directly to a TextWriter
As a tweaked version that adopts these approaches, see below; note that I haven't enabled HyperDescriptor in this example, but that is just:
HyperTypeDescriptionProvider.Add(typeof(YourType));
Anyway...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
static class Program {
static void Main() { // just some test data...
var data = new[] { new { Foo = "abc", Bar = 123 }, new { Foo = "def", Bar = 456 } };
Write(data, Console.Out, true, "|");
}
public static void Write<T>(IEnumerable<T> items, TextWriter output, bool writeHeaders, string delimiter) {
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
foreach (T item in items) {
bool firstCol = true;
if (writeHeaders) {
foreach (PropertyDescriptor prop in properties) {
if (firstCol) {
firstCol = false;
} else {
output.Write(delimiter);
}
output.Write(prop.Name);
}
output.WriteLine();
writeHeaders = false;
firstCol = true;
}
foreach (PropertyDescriptor prop in properties) {
if (firstCol) {
firstCol = false;
} else {
output.Write(delimiter);
}
output.Write(prop.Converter.ConvertToString(prop.GetValue(item)));
}
output.WriteLine();
}
}
}

Categories