in

ASPXWizard.net

.net and Ajax Community

Mina Labib

Run time (Dynamic) attributes in C#

In the current project I was concerned to build generic user control, accept generic collection and paint collection elements details in HTML table and allow editing functionality for specific columns. The challenge is to detect the editable properties in the collection elements in the run time without knowing the collection or columns types.

My idea was to decorate desired properties with custom Attributes to specify the layout behavior; Attributes can be accessed and obtained using Reflection in the run time, the idea seems working fine.

So, what are attributes in c#?

"Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). Once associated with a program entity, the attribute can be queried at run time and used in any number of way" - MSDN.

Also attributes are classes that inherits System.Attribute as below

[AttributeUsage(AttributeTargets.Property)]

public class UIAttributes : Attribute

{

private bool isReadOnly = false;

public bool IsReadOnly

{

get { return isReadOnly; }

}

public UIAttributes(bool isReadOnly)

{

this.IsReadOnly = isReadOnly;

}

}

Then decorate class property with the custom attribute:

public class ProductViewData

{

public string Name { get; set; }

[UIAttributes(true)] //ProdcutID property is decorated to be read only.

public int ProductID { get; set; }

public double Price { get; set; }

}

Then by using reflection we can detect which property has the custom attribute and paint attribute according to that.

public void DetectProperties(object o)

{

PropertyInfo[] propInfo = o.GetType().GetProperties();

foreach(PropertyInfo prop in propInfo)

{

foreach(Attribute att in prop.GetCustomAttributes(true))

{

if((att is UIAttributes) && (((UIAttributes)att).IsReadOnly) )

{

//Do somthing.

}

}

}

}

But let's say the same property should be editable in a view and non-editable in other view, then property behavior should be changed at run time to toggle between the editable/read-only mode, and custom attributes does now allow to be changed at runtime.

So, after some readings there was no easy way to do that, but there was a great class in System.ComponentModel namespace called TypeDescriptor which allow dynamically assigning and querying metadata on instance on runtime, it seems like it is our solution.

The only drawback is the long way to implement it, so first I built Interface representing any type need to follow my custom attribute:

Interface:

public interface IUIAttributes

{

bool IsReadOnly(string PName);

bool IsReadOnly();

}

Custom Attribute:

[AttributeUsage(AttributeTargets.Property)]

public class UIAttributes : Attribute

{

private bool isReadOnly = false;

public bool IsReadOnly

{

get { return isReadOnly; }

set { isReadOnly = value; }

}

public UIAttributes()

{

}

public UIAttributes(bool isReadOnly)

{

this.IsReadOnly = isReadOnly;

}

}

Any Class implements the interface:

public class ProductViewData : IUIAttributes

{

public string Name { get; set; }

public int ProductID { get; set; }

public double Price { get; set; }

#region IUIAttributes Members

bool IUIAttributes.IsReadOnly(string PName)

{

if (PName.Equals("ProductID"))

return true;

else

return false;

}

bool IUIAttributes.IsReadOnly()

{

return false;

}

#endregion

}

Now I have to write a CustomTypeDescriptor and Provider, this descriptor will create instances of my custom attribute UIAttribute and associate them to types that implement the Interface:

public sealed class CustomTypeDescriptionProvider : TypeDescriptionProvider where T : IUIAttributes

{

///

/// Constructor

///

public CustomTypeDescriptionProvider(TypeDescriptionProvider parent)

: base(parent)

{

}

///

/// Create and return a custom type descriptor and chains it with the original

/// custom type descriptor

///

public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)

{

return new UIAttributeCustomTypeDescriptor(base.GetTypeDescriptor(objectType, instance));

}

}

public sealed class UIAttributeCustomTypeDescriptor : CustomTypeDescriptor where T : IUIAttributes

{

///

/// Constructor

///

public UIAttributeCustomTypeDescriptor(ICustomTypeDescriptor parent)

: base(parent)

{

}

public override AttributeCollection GetAttributes()

{

Type UIType = typeof(T).GetInterface(typeof(IUIAttributes).Name);

if (UIType != null)

{

IUIAttributes UIInstance = GetPropertyOwner(base.GetProperties().Cast<PropertyDescriptor>().First()) as IUIAttributes;

bool instanceLevelRoles = UIInstance.IsReadOnly();

List<Attribute> attributes = new List<Attribute>(base.GetAttributes().Cast<Attribute>());

UIAttributes UIAttrib = new UIAttributes(instanceLevelRoles);

TypeDescriptor.AddAttributes(UIInstance, UIAttrib);

attributes.Add(UIAttrib);

return new AttributeCollection(attributes.ToArray());

}

return base.GetAttributes();

}

///

/// This method add a new property to the original collection

///

public override PropertyDescriptorCollection GetProperties()

{

// Enumerate the original set of properties and create our new set with it

PropertyDescriptorCollection originalProperties = base.GetProperties();

List<PropertyDescriptor> newProperties = new List<PropertyDescriptor>();

Type UIType = typeof(T).GetInterface("IUIAttributes");

if (UIType != null)

{

foreach (PropertyDescriptor pd in originalProperties)

{

IUIAttributes UIInstance = GetPropertyOwner(pd) as IUIAttributes;

bool propertyIsReadOnly = UIInstance.IsReadOnly(pd.Name);

UIAttributes UIAttrib = new UIAttributes(propertyIsReadOnly);

// Create a new property and add it to the collection

PropertyDescriptor newProperty = TypeDescriptor.CreateProperty(typeof(T), pd.Name, pd.PropertyType, UIAttrib);

newProperties.Add(newProperty);

}

// Finally return the list

return new PropertyDescriptorCollection(newProperties.ToArray(), true);

}

return base.GetProperties();

}

}

I have overridden GetAttributes in which I query the underlying instance to get read-only mode of the instance. Similarly, I have also overridden GetProperties which will in turn query the instance to get read-only mode of the specified property name.

We are now ready to associate the UIAttribute with our class instances.

ProductViewData pvd = new ProductViewData();

pvd.ProductID = 1;

pvd.Name = "Product1";

pvd.Price = 99.99;

TypeDescriptor.AddProvider(new CustomTypeDescriptionProvider<ProductViewData>(TypeDescriptor.GetProvider(typeof(ProductViewData))),pvd);

And then by Reflection we can get properties attributes and check its layout behavior without knowing instance type, in next piece of code ‘Model’ is the instance name and ‘Name’ is the property name.

public bool IsPropReadOnly(string Name)

{

bool readonlyatt = false;

UIAttributes uiatt = TypeDescriptor.GetAttributes(Model).Cast<Attribute>().SingleOrDefault(a => a.GetType().Name == typeof(UIAttributes).Name) as UIAttributes;

if ((uiatt != null) && uiatt.IsReadOnly)

return uiatt.IsReadOnly;

PropertyInfo propInfo = Model.GetType().GetProperty(Name);

//(propInfo =>

{

PropertyDescriptor propDescriptor = TypeDescriptor.GetProperties(Model).Cast<PropertyDescriptor>().SingleOrDefault(p => propInfo.Name == p.Name);

if (propDescriptor != null)

{

UIAttributes attrib = propDescriptor.Attributes.Cast<Attribute>().SingleOrDefault(p => p.GetType().Name == typeof(UIAttributes).Name) as UIAttributes;

if (attrib != null)

{

readonlyatt = attrib.IsReadOnly;

}

}

}

//);

return readonlyatt;

}

Thanks for this Post it helps a lot.

Comments

 

Generic editable GridView – ASP.NET MVC « Mina Labib's Blog said:

Pingback from  Generic editable GridView &#8211; ASP.NET MVC &laquo; Mina Labib&#039;s Blog

November 6, 2009 5:09 PM
 

???????????? ???????????????????? ???????????? » ?????????? ???????? » ???????????? Adidas «Dynamic Pulse. ?????????????????? ????????, 100 ???? said:

Pingback from  ???????????? ???????????????????? ????????????  &raquo; ?????????? ????????  &raquo; ???????????? Adidas &laquo;Dynamic Pulse. ?????????????????? ????????, 100 ????

February 27, 2010 3:17 AM
 

???????????? ???????????????????? ???????????? » ?????????? ???????? » Adidas «Dynamic Pulse. ???????????? ?????????? ????????????, 100 ???? ????????????. said:

Pingback from  ???????????? ???????????????????? ????????????  &raquo; ?????????? ????????  &raquo; Adidas &laquo;Dynamic Pulse. ???????????? ?????????? ????????????, 100 ???? ????????????.

March 3, 2010 9:23 AM
 

???????????? ???????????????????? ???????????? » ?????????? ???????? » Adidas «Dynamic Pulse. ?????????????????? ????????, 50 ???? ????????????. said:

Pingback from  ???????????? ???????????????????? ????????????  &raquo; ?????????? ????????  &raquo; Adidas &laquo;Dynamic Pulse. ?????????????????? ????????, 50 ???? ????????????.

March 4, 2010 4:08 AM
 

Wagovan Replacement Catalytic Converter Honda Prelude, Wagovan Discount Middle said:

Pingback from  Wagovan Replacement Catalytic Converter Honda Prelude, Wagovan Discount Middle

May 20, 2010 10:12 AM
 

C55 Amg Used Rent 2010 Mercedes Benz, Mercedes C55 Parts said:

Pingback from  C55 Amg Used Rent 2010 Mercedes Benz, Mercedes C55 Parts

May 20, 2010 10:13 AM
 

Unscrambler Motorcycle, Rocky Mountain Radar Laser Scrambler said:

Pingback from  Unscrambler Motorcycle, Rocky Mountain Radar Laser Scrambler

May 20, 2010 1:59 PM
 

Fairmont Auction Silent 00pm, Ford Fairmont Used Salvage Yard said:

Pingback from  Fairmont Auction Silent 00pm, Ford Fairmont Used Salvage Yard

May 20, 2010 4:18 PM
 

Mercury Monarch Cheap Ford Granada, Granada Aftermarket Options Crown Victoria said:

Pingback from  Mercury Monarch Cheap Ford Granada, Granada Aftermarket Options Crown Victoria

May 20, 2010 6:58 PM
 

Cj6a Cheap Becoming Warbird, Cj6a Accessories 5a Cars said:

Pingback from  Cj6a Cheap Becoming Warbird, Cj6a Accessories 5a Cars

May 20, 2010 8:26 PM
 

Headlight Aftermarket Oem Volvo C70, Chevrolet El Camino Aftermarket Ball Joints said:

Pingback from  Headlight Aftermarket Oem Volvo C70, Chevrolet El Camino Aftermarket Ball Joints

May 20, 2010 11:30 PM
 

B3000 Cooling System Replacement, B3000 Sell Hammond B 3000 Organ said:

Pingback from  B3000 Cooling System Replacement, B3000 Sell Hammond B 3000 Organ

May 21, 2010 2:24 AM
 

V1500 Zip Used Truck Parts, Auto Gmc V1500 Suburban Radiator Yukon Denali said:

Pingback from  V1500 Zip Used Truck Parts, Auto Gmc V1500 Suburban Radiator Yukon Denali

May 21, 2010 3:47 AM
 

Ford Granada Part Mercury Zephyr, Lamp Granada Spares said:

Pingback from  Ford Granada Part Mercury Zephyr, Lamp Granada Spares

May 21, 2010 2:07 PM
 

1998 Ram 3500 For Sale Used Car Dodge Avenger, Dodge Avenger Xenon said:

Pingback from  1998 Ram 3500 For Sale Used Car Dodge Avenger, Dodge Avenger Xenon

May 22, 2010 4:17 AM
 

Cheap 325i E36, Bmw 325 E36 Engine Specs said:

Pingback from  Cheap 325i E36, Bmw 325 E36 Engine Specs

May 22, 2010 6:54 AM
 

323 Parts Tail Light Protege Mazda Mx5, Download Mx5 said:

Pingback from  323 Parts Tail Light Protege Mazda Mx5, Download Mx5

May 22, 2010 7:27 AM
 

1966 Camaro Muscle Cars For Sale, Camaro Used Parts said:

Pingback from  1966 Camaro Muscle Cars For Sale, Camaro Used Parts

May 22, 2010 12:50 PM
 

Havana 1500 Sale Envoy Xuv, Replacement Bulb 2000 Gmc Envoy said:

Pingback from  Havana 1500 Sale Envoy Xuv, Replacement Bulb 2000 Gmc Envoy

May 22, 2010 2:40 PM
 

Wagon Century 21, 1993 Buick Century Parts Catalytic Converter - 78.an74.com said:

Pingback from  Wagon Century 21, 1993 Buick Century Parts Catalytic Converter - 78.an74.com

May 22, 2010 10:28 PM
 

164 Lyrics, Gh164 Pd Hose Reel Powder Coat Finish - 85.unlockiphone30.net said:

Pingback from  164 Lyrics, Gh164 Pd Hose Reel Powder Coat Finish - 85.unlockiphone30.net

May 23, 2010 5:17 AM
 

T1000 Discount Available, T1000 Free Shipping Available - 148.myipgirl.com said:

Pingback from  T1000 Discount Available, T1000 Free Shipping Available - 148.myipgirl.com

May 24, 2010 4:24 AM
 

Mercedes Benz C240 Radiator Oxygen Sensor C55 Amg, C55 Replacement C32 Amg - 343.unlockiphone30.net said:

Pingback from  Mercedes Benz C240 Radiator Oxygen Sensor C55 Amg, C55 Replacement C32 Amg - 343.unlockiphone30.net

May 24, 2010 6:25 AM
 

Jimmy Rent A Car Truck, Jimmy Equipment Driving - 164.jordanbrandallamerican.com said:

Pingback from  Jimmy Rent A Car Truck, Jimmy Equipment Driving - 164.jordanbrandallamerican.com

May 24, 2010 6:53 AM
 

Sale Used Saturn Relay 2 Tilt Steering Keyless Entry, Water Sensor Relay - 259.tvshowzone.com said:

Pingback from  Sale Used Saturn Relay 2 Tilt Steering Keyless Entry, Water Sensor Relay - 259.tvshowzone.com

May 24, 2010 10:00 AM
 

1998 Mitsubishi Montero Sport Recall, Mitsubishi Tredia Radiator Montero Sport - 359.defutbolazo.com said:

Pingback from  1998 Mitsubishi Montero Sport Recall, Mitsubishi Tredia Radiator Montero Sport - 359.defutbolazo.com

May 24, 2010 3:34 PM
 

Bdp S350 Usb, Es350 Headlight Bulb Ge Lighting - 124.computeronlinebingo.com said:

Pingback from  Bdp S350 Usb, Es350 Headlight Bulb Ge Lighting - 124.computeronlinebingo.com

May 24, 2010 5:38 PM
 

Pb300 Diagram Body Kits, Pb300 Require Exhaust Manifold - 4.luna-atra.net said:

Pingback from  Pb300 Diagram Body Kits, Pb300 Require Exhaust Manifold - 4.luna-atra.net

May 24, 2010 6:12 PM
 

Es250 Racing, Sc400 Headlight Es250 Lexus Ls400 Parts - 267.computeronlinebingo.com said:

Pingback from  Es250 Racing, Sc400 Headlight Es250 Lexus Ls400 Parts - 267.computeronlinebingo.com

May 25, 2010 1:31 AM
 

Used Times Gmc K3500, K45 K3500 Pickup Review - 212.dlmreza.net said:

Pingback from  Used Times Gmc K3500, K45 K3500 Pickup Review - 212.dlmreza.net

May 25, 2010 10:58 AM
 

G Taillight Ford Probe, Probe Sale Classified Listings Shelby Gt500 Ford Zx2 - 248.computeronlinebingo.com said:

Pingback from  G Taillight Ford Probe, Probe Sale Classified Listings Shelby Gt500 Ford Zx2 - 248.computeronlinebingo.com

May 25, 2010 12:26 PM
 

Discount Mercedes Benz E63 Amg Look, Amg For Sale Used Mercedes Benz E63 - 291.jeepsunlimted.com said:

Pingback from  Discount Mercedes Benz E63 Amg Look, Amg For Sale Used Mercedes Benz E63 - 291.jeepsunlimted.com

May 25, 2010 3:50 PM
 

Suzuki Grand Vitara 2009 Km77, 1978 Parts Grand Wagoneers Full Size Jeeps - 285.computeronlinebingo.com said:

Pingback from  Suzuki Grand Vitara 2009 Km77, 1978 Parts Grand Wagoneers Full Size Jeeps - 285.computeronlinebingo.com

May 25, 2010 4:36 PM
 

2001 - 2006 @ 2005 F250 Passenger Side Mirror, Ford F250 Parts Chair Covers F350 - 159.eumreborn.com said:

Pingback from  2001 - 2006 @ 2005 F250 Passenger Side Mirror, Ford F250 Parts Chair Covers F350 - 159.eumreborn.com

May 30, 2010 11:33 PM
 

1996 - 1985 @ 4runner Used Car Classifieds Toyota Fj Cruiser, Toyota 4runner Discount Code - 386.ja3ra.com said:

Pingback from  1996 - 1985 @ 4runner Used Car Classifieds Toyota Fj Cruiser, Toyota 4runner Discount Code - 386.ja3ra.com

May 31, 2010 12:27 AM
 

1981 - 2003 @ Se300 Crown Molding, Ml63 Part Cls55 E300 Cl65 Amg - 297.an74.com said:

Pingback from  1981 - 2003 @ Se300 Crown Molding, Ml63 Part Cls55 E300 Cl65 Amg - 297.an74.com

May 31, 2010 12:37 AM
 

1996 - 1988 @ 350sl One Replacement, Aftermarket Mercedes Benz 350sl - 77.renters.ws said:

Pingback from  1996 - 1988 @ 350sl One Replacement, Aftermarket Mercedes Benz 350sl - 77.renters.ws

May 31, 2010 12:38 AM
 

1984 - 2003 @ P15 P1500 Van Diagram P35, P1500 Used Supplies Blu Ray Player - 329.mfbattle.com said:

Pingback from  1984 - 2003 @ P15 P1500 Van Diagram P35, P1500 Used Supplies Blu Ray Player - 329.mfbattle.com

May 31, 2010 11:31 AM
 

1990 - 2007 @ 300sel Rating Cd Changer, Heater Mercedes 300sel - 84.dlmreza.net said:

Pingback from  1990 - 2007 @ 300sel Rating Cd Changer, Heater Mercedes 300sel - 84.dlmreza.net

May 31, 2010 12:23 PM
 

1997 - 2003 @ S65 Amg Oem S600, W221 S600 V12 Biturbo - 170.mfbattle.com said:

Pingback from  1997 - 2003 @ S65 Amg Oem S600, W221 S600 V12 Biturbo - 170.mfbattle.com

May 31, 2010 1:17 PM
 

Web site of the state - University web - Fayetteville state university web site said:

Pingback from  Web site of the state - University web - Fayetteville state university web site

August 26, 2010 4:38 AM

Leave a Comment

(required)  
(optional)
(required)  
Add
ASPXWizard.net some rights reserved 2005-2007
Powered by Community Server (Non-Commercial Edition), by Telligent Systems