list all properties with [XmlAttribute] of given class - c#

For example I have a simple class
class SomeCfg
{
[XmlAttribute("ArchivePath")]
public string ArchivePath { get; set; }
}
As it can be seen given class have one property with XmlAttribute. But when program execution comes to that code
var t = typeof (SomeCfg);
var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(XmlAttribute)));
Runtime throws exception
System.ArgumentException: Type passed in must be derived from System.Attribute or System.Attribute itself.
Of course when I saw type hierarchy I realized it's true (I will not go into why this does not inherits from that class).
My question is how to list these properties (creating a class that inherits from XmlAttribute and System.Attribute is not an option in that case).
According to question tag .Net version is 4.0.

Is it possible that you used System.Xml.XmlAttribute instead of System.Xml.Serialization.XmlAttributeAttribute?
System.Xml.XmlAttribute is used to represent an attribute from the xml document.
System.Xml.Serialization.XmlAttributeAttribute specifies that the XmlSerializer must serialize the class member as an XML attribute.

You can get Properties containing XMLAttribute from following code..
var props = t.GetProperties()
.Where(prop =>
prop.GetCustomAttributes(typeof(XmlAttributeAttribute), false).Any(PropType => PropType.GetType() == typeof(XmlElementAttribute) ||
PropType.GetType() == typeof(XmlAttributeAttribute)));
if you don't want to use full LINQ then this post is also helpful for you.
Serialize all properties in a class as attributes instead of elements

Related

Simplify Attribute decorator on methods when referencing multiple libraries [duplicate]

On a control I am using multiple attribute properties:
[Browsable(false)]
[Bindable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Obsolete("", true)]
public new Boolean AllowDrop;
I am using those properties on a lot of the other control properties as well.
I am wondering if there is a way to reduce the amount of code to write each time.
It would be nice if I could combine multiple attributes like this:
[Hidden(true)]
public new Boolean AllowDrop;
Where the Hidden Property would include all the attributes above. So there is only 1 single line of code.
Maybe there is also a way to combine the attributes in a macro or something?
I am aware that there are other ways of hiding properties but I chose the way of using attributes.
Thanks
It depends to the framework which is using the attribute.
Combining attributes can be meaningful in order to the context which uses and interprets attributes. For example for those contexts which use .Net Type Description mechanisms you can customize the type description which .Net returns to consumers.
It's possible to provide custom metadata for types using the standard .Net mechanism for that purpose, registering a custom type descriptor for your object.
The idea will work this way, you create a custom type descriptor for your type. In the custom type descriptor, you return custom property descriptors for the properties of your type and in the property descriptor, you return a custom set of attributes for the property.
The approach requires more code, but it's really interesting and shares some good idea about how to provide custom metadata for your types:
IMetedataAttribute Interface
The usage is providing an standard way to create MetaDataAttributes. Each attribute which implements this interface will be used as metadata and instead of the attribute, those one which it returns in Process method will be used:
public interface IMetadatAttribute
{
Attribute[] Process();
}
Sample MetadataAttribute
It's a sample metadata attribute which returns some attribute instead when processing the attribute:
public class MySampleMetadataAttribute : Attribute, IMetadatAttribute
{
public Attribute[] Process()
{
var attributes = new Attribute[]{
new BrowsableAttribute(false),
new EditorBrowsableAttribute(EditorBrowsableState.Never),
new BindableAttribute(false),
new DesignerSerializationVisibilityAttribute(
DesignerSerializationVisibility.Hidden),
new ObsoleteAttribute("", true)
};
return attributes;
}
}
Property Descriptor
This class will be used by the custom type descriptor to provide a custom list of attributes for the property:
public class MyPropertyDescriptor : PropertyDescriptor
{
PropertyDescriptor original;
public MyPropertyDescriptor(PropertyDescriptor originalProperty)
: base(originalProperty) { original = originalProperty;}
public override AttributeCollection Attributes
{
get
{
var attributes = base.Attributes.Cast<Attribute>();
var result = new List<Attribute>();
foreach (var item in attributes)
{
if(item is IMetadatAttribute)
{
var attrs = ((IMetadatAttribute)item).Process();
if(attrs !=null )
{
foreach (var a in attrs)
result.Add(a);
}
}
else
result.Add(item);
}
return new AttributeCollection(result.ToArray());
}
}
// Implement other properties and methods simply using return original
// The implementation is trivial like this one:
// public override Type ComponentType
// {
// get { return original.ComponentType; }
// }
}
Type Descriptor
This is the type descriptor which provides a custom description for your type. In this example it uses custom property descriptors to provide custom attributes set for the properties of your class:
public class MyTypeDescriptor : CustomTypeDescriptor
{
ICustomTypeDescriptor original;
public MyTypeDescriptor(ICustomTypeDescriptor originalDescriptor)
: base(originalDescriptor)
{
original = originalDescriptor;
}
public override PropertyDescriptorCollection GetProperties()
{
return this.GetProperties(new Attribute[] { });
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
var properties = base.GetProperties(attributes).Cast<PropertyDescriptor>()
.Select(p => new MyPropertyDescriptor(p))
.ToArray();
return new PropertyDescriptorCollection(properties);
}
}
Typedescriptor Provider
This class will be used in the attribute above your type to introduce the custom type descriptor which we created as the metadata engine for the type:
public class MyTypeDescriptionProvider : TypeDescriptionProvider
{
public MyTypeDescriptionProvider()
: base(TypeDescriptor.GetProvider(typeof(object))) { }
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType,
object instance)
{
ICustomTypeDescriptor baseDescriptor = base.GetTypeDescriptor(objectType, instance);
return new MyTypeDescriptor(baseDescriptor);
}
}
Sample Class
Here is my sample class which its Name property is decorated using MySampleMetadataAttribute and the class itself is registered to use our custom type descriptor provider:
[TypeDescriptionProvider(typeof(MyTypeDescriptionProvider))]
public class MySampleClass
{
public int Id { get; set; }
[MySampleMetadataAttribue]
[DisplayName("My Name")]
public string Name { get; set; }
}
To see the result it's enough to create an instance of the class and see the result in PropertyGrid:
var o = new MySampleClass();
this.propertyGrid1.SelectedObject = o;
Some notes on answer
Probably it's not as simple as you expected for such task. But it's working.
It's a lengthy answer, but contains a complete working example of how you can apply type descriptors to your types to provide custom metadata.
The approach will not work for engines which use reflection instead of type description. But it's completely working with for example PropertyGrid control which works with type description.
The best way for me to do this, is by using Metalama (modern rewrite of PostSharp for new .NET releases).
It is absolutely the best framework for doing AOP in .NET from the same guys that did PostSharp. It is still in preview, but Metalama 1.0 will be released in a week or 2, and in next year, it will probably get most of features found in PostSharp... And it has a nice community on Slack and the authors of this Metalama framework are super supportive, they helped me with each question I had, and I had a lot of them already :D
And so this library is perfect for creating custom aspects, but could easily be used for this merging of attributes :) It will be even better then the approach above, because once you see transformed file (using Metalama Diff Preview - you gotta install Metalama extension to VS), then you will actually see all those original attributes there, in a transformed file :)
And so this is how easily I will merge 3 attributes into 1 with Metalama:
Metalama easy merging of attributes 1
(This would be for aspect attributes created by Metalama)
Or, for other attributes (from other libraries), that don't need to do the aspect work, it would by like this: (And this is probably what you want to use, not the first example...):

XmlSerialization and interfaces

I know that you can't serialize/deserialize using an interface but I'm confused by behaviour I'm seeing.
When I deserialize and cast back to the interface, some properties are null. But if I cast back to the concrete type the same property has a value?
So, given this XML (shortened for brevity):
<Page>
<ComponentPresentations>
<ComponentPresentation>
<Component>
<Categories>
<Category>
<Id>tcm:35-540-512</Id>
Deserializing with
var serializer = new XmlSerializer(typeof(Page));
page = (IPage)serializer.Deserialize(reader);
page.ComponentPresentations[0].Component.Categories <-- is null
But if I cast back to the type,
var serializer = new XmlSerializer(typeof(Page));
page = (Page)serializer.Deserialize(reader);
page.ComponentPresentations[0].Component.Categories <-- is not null!
The Page type exposes the interface Categories property and a non-interface property - I assume to get around the serializing interface problem.
public List<Category> Categories { get; set; }
[XmlIgnore]
IList<ICategory> IComponent.Categories
{
get { return Categories as IList<ICategory>; }
}
Is this because the interface property doesn't expose a setter?
No. The problem is Contravariance not being supported by List<T> and IList<T>. Here is a good reference.
Have a look at this simple code:
public interface IMyInterface
{
}
public class MyImplementation : IMyInterface
{
}
List<MyImplementation> myImplementations = new List<MyImplementation>();
Console.WriteLine(myImplementations as IList<IMyInterface> == null); // OUTPUT: true!!
So as you can see, Categories as IList<ICategory> will always be null. While Categories as IList<Category> will be OK.
Nothing to do with serialisation.

C# reflection avoid propertie

Im using reflection to acess a class tha represents a table in DB.However,reflection read all properties of that class,and im wondering if there're some atributte in c# we can use to avoid read that propertie.
i.e:
[AvoidThisPropertie]
public string Identity
{
get;
set;
}
PropertyInfo [] properties = MyType.GetProperties(
BindingFlags.Instance | BindingFlags.Public);
IList<PropertyInfo> crawlableProperties = properties.Where(
p => p.GetCustomAttributes(
typeof(AvoidThisProperty), true)
.Count() == 0);
You'd also have to create the AvoidThisProperty
[AttributeUsage(AttributeTargets.Property)]
public class AvoidThisPropertyAttribute : Attribute
{
// Doesn't need a body
}
You still have access to all the properties, but the LINQ statement would generate a list of the desired properties.
If you could avoid full accessibility, reflection would have no sense

Access parent class from custom attribute

Is it possible to access a parent class from within an attribute.
For example I would like to create a DropDownListAttribute which can be applied to a property of a viewmodel class in MVC and then create a drop down list from an editor template. I am following a similar line as Kazi Manzur Rashid here.
He adds the collection of categories into viewdata and retrieves them using the key supplied to the attribute.
I would like to do something like the below,
public ExampleDropDownViewModel {
public IEnumerable<SelectListItem> Categories {get;set;}
[DropDownList("Categories")]
public int CategoryID { get;set; }
}
The attribute takes the name of the property containing the collection to bind to. I can't figure out how to access a property on the parent class of the attribute. Does anyone know how to do this?
Thanks
You can't access a parent type from an attribute. Attributes are metadata that is applied to a type, but you can't look back and try and identify the type, unless you did something like:
[MyCustomAttribute(typeof(MyClass))]
public class MyClass {
///
}
With the reflection solution above, you are not actually achieving the action of getting a type from an attribute, you are doing the reverse, you are getting attributes from a type. At this point, you already have the type.
You can do that using reflection. Do the following in your main class:
Type type = typeof(ExampleDropDownViewModel));
// Get properties of your data class
PropertyInfo[] propertyInfo = type.GetProperties( );
foreach( PropertyInfo prop in propertyInfo )
{
// Fetch custom attributes applied to a property
object[] attributes = prop.GetCustomAttributes(true);
foreach (Attribute attribute in attributes) {
// we are only interested in DropDownList Attributes..
if (attribute is DropDownListAttribute) {
DropDownListAttribute dropdownAttrib = (DropDownListAttribute)attribute;
Console.WriteLine("table set in attribute: " + dropdownAttrib.myTable);
}
}
}

C# setting property values through reflection with attributes

I am trying to build an object through an attribute on a classes property that specifies a column in a supplied data row that is the value of the property, as below:
[StoredDataValue("guid")]
public string Guid { get; protected set; }
[StoredDataValue("PrograGuid")]
public string ProgramGuid { get; protected set; }
In a Build() method on a base object, I am getting the attribute values set on these properties as
MemberInfo info = GetType();
object[] properties = info.GetCustomAttributes(true);
However, at this point I am realising the limitation in my knowledge.
For a start, I don't appear to be getting back the correct attributes.
And how do I set these properties through reflection, now that I have the attributes? Am I doing / thinking something fundamentally incorrect?
There are a couple of separate issues here
typeof(MyClass).GetCustomAttributes(bool) (or GetType().GetCustomAttributes(bool)) returns the attributes on the class itself, not the attributes on members. You will have to invoke typeof(MyClass).GetProperties() to get a list of properties in the class, and then check each of them.
Once you got the property, I think you should use Attribute.GetCustomAttribute() instead of MemberInfo.GetGustomAttributes() since you exactly know what attribute you are looking for.
Here's a little code snippet to help you start:
PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach(PropertyInfo property in properties)
{
StoredDataValueAttribute attribute =
Attribute.GetCustomAttribute(property, typeof(StoredDataValueAttribute)) as StoredDataValueAttribute;
if (attribute != null) // This property has a StoredDataValueAttribute
{
property.SetValue(instanceOfMyClass, attribute.DataValue, null); // null means no indexes
}
}
EDIT: Don't forget that Type.GetProperties() only returns public properties by default. You will have to use Type.GetProperties(BindingFlags) to get other sorts of properties as well.

Categories

Resources