473,549 Members | 2,723 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieving Custom Attributes from a property using StackTrace

Hi all,
I am trying to get custom attributes from a property. I can do this if I
pass in the name of the property i.e. "Name" to the reflection methods, but
if I pass in set_Name which is what the set piece of the Name property gets
compiled to, which I am getting from the stack trace, then the attributes are
not returned.

For example, Class Person has a property called "Name" which has a custom
attribute decorating it. Inside the set brace in the property I want to
retrieve the custom attributes from the Property and do some processing (in
my real world code the attributes are to be used for validating input, i.e.
user length, max min values etc). I can do this as long as I pass the name
of the property i.e. "Name" to the GetMember method of the Type class.
However, if I try to get it using the name the Set property gets compile to,
set_Name which comes from the StackTrace no custom attributes are returned.

I could pass the name of the property to the method, but this seems to be
something that would be a source of bugs, if I change the property name and
forget to change the string value I am passing to the attribute processing
method.

Here is an example of the code (I appologise for the formatting in this
window):

using System;
using System.Collecti ons.Generic;
using System.Text;

using System.Reflecti on;
using System.Diagnost ics;

namespace ConsoleApplicat ion5
{
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.Name = "Frank";
}
}

class CustomTestAttri bute : Attribute
{
}

class Person
{
[CustomTest]
public string Name
{
get
{
return "Bob";
}
set
{
//THIS WORKS
ProcessAttribut es("Name");

//THIS DOES NOT WORK, when passing set_Name
StackTrace stackTrace = new StackTrace();
ProcessAttribut es(stackTrace.G etFrame(0).GetM ethod().Name);
}
}

private void ProcessAttribut es(string memberName)
{
//get the member that called this method
MemberInfo[] members = this.GetType(). GetMember(
memberName, BindingFlags.Pu blic | BindingFlags.In stance);

//Get the attributes
object[] attributes = members[0].GetCustomAttri butes(false);

}
}
}
Thanks in advance
Mark.
Feb 10 '06 #1
3 3175

I'm no reflections expert, but this sounded interesting so I thought I
would poke around at it.

In my tinkering, I found that if you put the attributes at the "set"
level, you will get them in your ProcessAttribut es method:
public string Name
{
get { return "Bob"; }

[CustomTest]
set
{
...
}

}
So, somehow to get the attributes of the Name property, you need to
somehow get out of the set section and up one level into the Name
property. But, I cannot find a link between the set_Name method and its
"parent property".

--Brian
Feb 10 '06 #2
Mark,

You are going to have to parse off the set_ or the get_ part of the
method name and then get the PropertyInfo instance for the property. The
method doesn't have the attributes assigned to it, just the property.
Properties are always backed by methods (which is why there is a property to
get the method info for the method backing the property), but not the other
way.

What you could do is once you get the property, you can call the
GetGetMethod or GetSetMethod on the property that you retrieved. If it
matches the method that you started with, then you know it is the same.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Mark R. Dawson" <Ma*********@di scussions.micro soft.com> wrote in message
news:39******** *************** ***********@mic rosoft.com...
Hi all,
I am trying to get custom attributes from a property. I can do this if I
pass in the name of the property i.e. "Name" to the reflection methods,
but
if I pass in set_Name which is what the set piece of the Name property
gets
compiled to, which I am getting from the stack trace, then the attributes
are
not returned.

For example, Class Person has a property called "Name" which has a custom
attribute decorating it. Inside the set brace in the property I want to
retrieve the custom attributes from the Property and do some processing
(in
my real world code the attributes are to be used for validating input,
i.e.
user length, max min values etc). I can do this as long as I pass the
name
of the property i.e. "Name" to the GetMember method of the Type class.
However, if I try to get it using the name the Set property gets compile
to,
set_Name which comes from the StackTrace no custom attributes are
returned.

I could pass the name of the property to the method, but this seems to be
something that would be a source of bugs, if I change the property name
and
forget to change the string value I am passing to the attribute processing
method.

Here is an example of the code (I appologise for the formatting in this
window):

using System;
using System.Collecti ons.Generic;
using System.Text;

using System.Reflecti on;
using System.Diagnost ics;

namespace ConsoleApplicat ion5
{
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.Name = "Frank";
}
}

class CustomTestAttri bute : Attribute
{
}

class Person
{
[CustomTest]
public string Name
{
get
{
return "Bob";
}
set
{
//THIS WORKS
ProcessAttribut es("Name");

//THIS DOES NOT WORK, when passing set_Name
StackTrace stackTrace = new StackTrace();
ProcessAttribut es(stackTrace.G etFrame(0).GetM ethod().Name);
}
}

private void ProcessAttribut es(string memberName)
{
//get the member that called this method
MemberInfo[] members = this.GetType(). GetMember(
memberName, BindingFlags.Pu blic | BindingFlags.In stance);

//Get the attributes
object[] attributes = members[0].GetCustomAttri butes(false);

}
}
}
Thanks in advance
Mark.

Feb 10 '06 #3
Hi Brian,
thanks for looking into this. Maybe you are onto something with moving
the attributes inside the set, I am going to look more into this to see if I
can find out if it can be used.

Thanks
Mark.
"Brian P" wrote:

I'm no reflections expert, but this sounded interesting so I thought I
would poke around at it.

In my tinkering, I found that if you put the attributes at the "set"
level, you will get them in your ProcessAttribut es method:
public string Name
{
get { return "Bob"; }

[CustomTest]
set
{
...
}

}
So, somehow to get the attributes of the Name property, you need to
somehow get out of the set section and up one level into the Name
property. But, I cannot find a link between the set_Name method and its
"parent property".

--Brian

Feb 10 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5483
by: Chris Newby | last post by:
I am trying to implment some business level user authorization in my current ..net 1.1 app. In C#, I would like to do something like: public void MethodRequiringAuthorization() { ... some code that requires authorization } But then have this code changed at compile time to something like:
2
1976
by: Rob | last post by:
What VB run-time methods are available to retrieve information (such as AssemblyCopyright, AssemblyProduct, AssemblyVersion, etc.) from the AssemblyInfo.vb file for the current executable? Thank you in advance for any help.
2
3174
by: Jay Walker | last post by:
I created a custom DataGridColumn based on Marcie Robillard's MSDN Article: Creating Custom Columns for the ASP.NET Datagrid http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/creatingcustomcolumns.asp The problem I am having is that the data in the custom datagridcolumn is not saved to viewstate and after...
3
1491
by: Gigi | last post by:
I'm trying to add a custom property to each row of a table. So I created an HtmlTable called tblClass, I created a new class myRow inherited from HtmlTableRow, to which I added a new member myRow public class myRow : System.Web.UI.HtmlControls.HtmlTableRow private string _myCustomProp public myRow() : base() _myCustomProp="" public...
0
1030
by: Sanjay Pais | last post by:
This is an extension of an earlier post I have created a custom text box and compiled it and dropped it into my toolbox. However when I change the value of my custom property in design mode and switch between design mode to page source and back to design mode i am unable to retrieve the property value I set. Also the property setting in the...
1
1695
by: Sanjay Pais | last post by:
I built a custom control for all the basic web.ui.controls like textbox, label, checkbox etc etc. I added my custom attribute called ApplySecurity to the html in the page. However, when I cycle through the controls on the page using this code, I cant seem to be able to access the Attribute collection. However, if I were to add the tag to a...
6
1571
by: Steve Amey | last post by:
Hi all I want to be able to throw a custom error up the call stack. I have looked around and it seems as though it's possible, but I can't get it to work :o( Below is some sample code. ------------------------------------------------------------ Public Class MainForm Public Sub Show Form Try
5
1863
by: =?Utf-8?B?cGFnYXRlcw==?= | last post by:
Hello All, I am sure that I am just overlooking something, but here's something I can't quite get right... I want to be able to get the value of a parameter of an unknown custom attribute at runtime. All of the examples I have seen use casting of known custom attributes to get these values. Thanks,
3
1779
by: Michel Vanderbeke | last post by:
Hello, While logging the errors in my program, I want to know in which class, function or procedure they occured. Is it possible to know the name of the class, function and / or procedure in which the error was produced? Is it also possible to know at which line number of the program the error occured? Many thanks and greetings,
0
7450
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7809
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6043
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5088
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1941
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1059
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.