vendredi 9 juin 2017

c# Set property of customattribute

I have created a custom class named AttributeConfiguration with the following attributes.

public class AttributeConfiguration : Attribute
{
        public string DisplayName { get; set; }
        public string SchemaNameCRM { get; set; }
        public string SchemaNameERP { get; set; }
        public bool Required { get; set; }
        public bool IsChild { get; set; }
}

I have some other class that decorates its properties with my custom class AttributeConfiguration.

public class Client
{
    public Client()
    {
          //Here I want to set all properties of my custom attribute 
          //AttributeConfiguration that decorates my attribute CODE
    }

    [AttributeConfiguration()]
    public string Code { get; set; }
}

I need to set the properties of the custom class AttributeConfiguration which is decorating my attribute code in the constructor of my Client entity.

This is what I've tried so far.

//PROPERTY OF MY CLASS
 var property = this.GetType().GetProperty("Code");

//MY CUSTOM ATTRIBUTE CONFIGURATOIN
AttributeConfiguration propertyConfigurationBeforeChange = property.GetCustomAttributes(false)
.Where(c => c.GetType() == typeof(AttributeConfiguration)).FirstOrDefault() as AttributeConfiguration;

 //GET SchemaNameERP from my Custom AttributeConfiguration instance
 PropertyInfo propertySchemaNameERP = propertyConfigurationBeforeChange.GetType().GetProperty("SchemaNameERP");
//CHANGING DEFAULT VALUE = Default Value is "ValueNotApplied"
propertySchemaNameERP.SetValue(propertyConfigurationBeforeChange, "NEW VALUE", null);

//SchemaNameERP property of my custom class instance propertyConfigurationBeforeChange has changed to my NEW VALUE 

  ///GETTING VALUE OF MY CUSTOM ATTRIBUTE CONFIGURATOIN FOR THE SECOND TIME AND IT HASN'T CHANGED THE DEFAULT VALUE
  attributeConfiguration propertyConfigurationAfterChange = property.GetCustomAttributes(false)
   .Where(c => c.GetType() == typeof(AttributeConfiguration)).FirstOrDefault() as AttributeConfiguration;

In this example I am trying to change the value only of the property SchemaNameERO, however I am able only to change the value of the atrribute of the instance I have created (propertyConfigurationBeforeChange variable), but not in the actual instance which "is within" the property Code.

I am stuck with that whole day.

I appreciate any help.





Aucun commentaire:

Enregistrer un commentaire