I need to write a method which takes any object and returns an equivalent object but by applying html-encode on all public writable string properties/fields if the object is a reference type. If the object is a string it should obviously return html-encode of the string passed. If it’s an enumerable type it should enumerate the type and apply the same logic as above on each of the items in the list.
Does this even sound possible ? I’ve been toying with some code (using ObjectDumper.cs as the starting point) but haven’t been able to get far.
The idea is that i can then apply this as an aspect to all my service methods, such that the returning object fields are safe to be bound with html ui, which is being worked on by several people who sometimes forget triggering the encode on the client side.
Yes, but the quick and dirty way is to use reflection, which will cause a massive (30-100x) performance hit versus regular property invocation. This may or may not matter to you.
If you go the reflection route, you could:
PropertyInfoto see that the property is a string or enumerable stringPropertyInfoobject:GetGetMethod()GetSetMethod()For
IEnumerable, you would need to do a little extra work, i.e get the collection with a late bound call and then enumerate it. Depending on your types, you may also need to ignore certain properties, modify fields, etc.If I had to do this (and I question whether or not this is the correct way to address the problem), I would scan the object’s interface with reflection once, and create dynamic getters/setters for each property and cache them in a Dictionary based on type. Subsequent requests to process an object would then use those cached methods and achieve performance similar to normal get/set invocation.
Enumerations will be a little more trouble to handle but very doable if you are familiar with IL generation and/or expression trees.
I think code should be designed to make developer’s lives easier, but how can you account for what people forget? I have nothing against bulletproof code, but who knows what else will be forgotten. Just a thought.