473,625 Members | 2,690 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Custom Attributes for Classes, Methods, etc

My client uses a SQL Database to store their usernames and passwords, and I
do not believe they have AD...no big deal... I wrote a class to create a
generic identity and generic principal so that I can use the .IsInRole
function for some added security. I would like to do the same by applying an
attribute to a method or class. The code I am including works from what I
can see, but I am experiencing the following... 1) I cannot add the custom
attribues to my main project... .NET does not seem to like it. 2) I cannot
complie my main application unless my custom attribute assembly is in the
GAC. Is this be design or am I doing something completely wrong...

Here are the 2 class files that I use to make the "Security" assembly that
for some reason must be in the GAC

Imports System.Security
Imports System.Security .Permissions
Imports System.Runtime. Remoting.Messag ing
Imports System.Text
Imports System.Runtime. Serialization

<Serializable() > _
Public NotInheritable Class UserPermission
Implements IPermission, ISecurityEncoda ble, IUnrestrictedPe rmission,
ISerializable
Private _permission As String = ""
Private _name As String = ""
Private _unrestricted As Boolean = False
Public Function IsUnrestricted( ) As Boolean Implements
IUnrestrictedPe rmission.IsUnre stricted
Return _unrestricted
End Function
Public Sub GetObjectData(B yVal info As SerializationIn fo, ByVal context
As StreamingContex t) Implements ISerializable.G etObjectData
info.AddValue(" Permission", _permission)
info.AddValue(" User", _name)
info.AddValue(" Unrestricted", _unrestricted)
End Sub
Public Sub New(ByVal info As SerializationIn fo, ByVal context As
StreamingContex t)
_permission = info.GetString( "Permission ")
_name = info.GetString( "User")
_unrestricted = info.GetBoolean ("Unrestricted" )
End Sub
Public Sub New(ByVal perm As PermissionState )
_unrestricted = perm
_permission = ""
_name = ""
End Sub
Public Sub New(ByVal name As String, ByVal permission As String)
_name = name
_permission = permission
End Sub
Public Sub New(ByVal unrestricted As Boolean, Optional ByVal name As
String = "", Optional ByVal permission As String = "")
_unrestricted = unrestricted
_name = name
_permission = permission
End Sub
Public Function Copy() As IPermission Implements IPermission.Cop y
Dim iperm As New UserPermission( PermissionState .None)
iperm._name = Me._name
iperm._permissi on = Me._permission
iperm._unrestri cted = Me._unrestricte d
Return iperm
End Function
Public Sub Demand() Implements IPermission.Dem and
Try
Dim principal As Security.Princi pal.IPrincipal =
Threading.Threa d.CurrentPrinci pal
If principal.IsInR ole("Unrestrict edAccess") Then
Exit Sub
End If
If principal.IsInR ole(_permission ) = False Then
Throw New SecurityExcepti on("You do not have rights to
perform the requested function.")
End If
Catch ex As Exception
Throw New SecurityExcepti on("You do not have rights to perform
the requested function.")
End Try
End Sub

Public Function IsSubsetOf(ByVa l target As IPermission) As Boolean
Implements IPermission.IsS ubsetOf
If target Is Nothing Then
Return False
'Return Not Me.IsUnRestrict ed
End If
Dim passedPerm As UserPermission = target
If passedPerm._per mission = Me._permission Then
Return True
Else
Return False
End If
End Function
Public Function Union(ByVal target As IPermission) As IPermission
Implements IPermission.Uni on
Dim result As New UserPermission( PermissionState .None)
Dim passedPerm As UserPermission = target
result._unrestr icted = Me._unrestricte d And passedPerm._unr estricted
If Me._name = passedPerm._nam e Then
result._name = ""
Else
result._name = Me._name
End If
If Me._permission = passedPerm._per mission Then
result._permiss ion = ""
Else
result._permiss ion = Me._permission
End If
Return result
End Function
Public Function Intersect(ByVal target As IPermission) As IPermission
Implements IPermission.Int ersect
If target Is Nothing Then
Return Nothing
End If
Dim passedPerm As UserPermission = target
End Function
Public Sub FromXml(ByVal e As SecurityElement ) Implements
ISecurityEncoda ble.FromXml
Dim iVal As String

iVal = e.Attribute("Us er")
_name = iVal
iVal = e.Attribute("Pe rmission")
_permission = iVal
iVal = e.Attribute("Un restricted")
If iVal <> "" Then
_unrestricted = Convert.ToBoole an(iVal)
End If
End Sub
' Serialize permission object to xml
Public Function ToXml() As SecurityElement Implements
ISecurityEncoda ble.ToXml
Dim e As New SecurityElement ("IPermissio n")
Dim typ As Type = Me.GetType()
Dim assemblyName As New StringBuilder(t yp.Assembly.ToS tring)
assemblyName.Re place(ControlCh ars.Quote, "'"c)
e.AddAttribute( "class", typ.FullName & ", " & assemblyName.To String)
e.AddAttribute( "version", "1")
e.AddAttribute( "Unrestrict ed", _unrestricted.T oString)
e.AddAttribute( "User", _name)
e.AddAttribute( "Permission ", _permission)
Return e
End Function
Public ReadOnly Property PermissionSet() As String
Get
Dim perm As New UserPermission( PermissionState .None)
Dim pset As New
NamedPermission Set("Hospitalit yMaxPermissionS et", PermissionState .None)
pset.Descriptio n = "Permission set containing permissions for
hospitalitymax"
pset.AddPermiss ion(perm)
Return pset.ToXml().To String()
End Get
End Property
End Class
Imports System.Security
Imports System.Security .Permissions
Imports System.Runtime. Serialization

<AttributeUsage (AttributeTarge ts.All, inherited:=Fals e,
AllowMultiple:= True), Serializable()> _
Public NotInheritable Class UserPermissionA ttribute
Inherits CodeAccessSecur ityAttribute
Private _permission As String = "IsAuthenticate d"
Private _name As String = ""

Public Property Permission() As String
Get
Return _permission
End Get
Set(ByVal Value As String)
_permission = Value
End Set
End Property
Public Property User() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property
Public Sub New(Optional ByVal action As SecurityAction =
SecurityAction. Demand)
MyBase.New(acti on)
End Sub
Public Overrides Function CreatePermissio n() As
System.Security .IPermission
Return New UserPermission( MyBase.Unrestri cted, _name, _permission)
End Function
End Class

So in my main app all I would like to do is similar to the following test...
Once again it seems to work but I have to add it to the GAC on my Devl
machine in order for it to complie. Once built I can deploy without issues.

Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click
Threading.Threa d.CurrentPrinci pal = Nothing
Try
Me.SomeCodeToRu n()
Catch ex As Exception
MsgBox(ex.ToStr ing)
End Try
End Sub

<UserPermission (Permission:="C anRunThisCode") > _
Private Sub SomeCodeToRun()
MsgBox("Code got called")
End Sub

Private Sub Button2_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button2.Click
Dim roles() As String = {"CanRunThisCod e"}
Dim i As New Security.Princi pal.GenericIden tity("steve")
Dim p As New Security.Princi pal.GenericPrin cipal(i, roles)
Threading.Threa d.CurrentPrinci pal = p
Try
Me.SomeCodeToRu n()
Catch ex As Exception
MsgBox(ex.ToStr ing)
End Try
End Sub

Any thoughts?

Jul 21 '05 #1
3 1465
Hi,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that when you're trying to use the user
defined permission attribute in your project, a FileNotFoundExc eption was
thrown. If there is any misunderstandin g, please feel free to let me know.

Based on my research, this issue is by design. The custom permission
attribute cannot be in the same assembly with the calling. Also, it has to
be in the GAC if you're compiling using the VS.NET IDE. HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Jul 21 '05 #2
Just want to confirm that the Assembly must be in the GAC...which you
mentioned to me is by design. Works for me, but I was wondering why it was
designed that way if you can offer any insight to the reasoning behind it

"Kevin Yu [MSFT]" wrote:
Hi,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that when you're trying to use the user
defined permission attribute in your project, a FileNotFoundExc eption was
thrown. If there is any misunderstandin g, please feel free to let me know.

Based on my research, this issue is by design. The custom permission
attribute cannot be in the same assembly with the calling. Also, it has to
be in the GAC if you're compiling using the VS.NET IDE. HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Jul 21 '05 #3
Hi,

Sorry that I cannot offer more information. If we don't put the assembly in
GAC, we can compile successfully in command line. However, in the IDE, the
compilation fails. As far as the document I can see, this behavior is by
design. HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Jul 21 '05 #4

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

Similar topics

5
6907
by: mtv | last post by:
Hi all, I have the following code: ================================ Webservice side: public class MyWS: WebService { private myLib.DataObject curDataObject;
3
1601
by: L.C. Rees | last post by:
Can custom __setattr__ methods and properties be mixed in new style classes? I experimented with a new style class with both a custom __setattr__ method and a property. Attributes controlled by the __setattr__ method work fine. When I attempt to set or get the property it raises the error: "TypeError: _settext() takes exactly two arguments (1 given)". This suggests that the __setattr__ may be conflicting with assignment to the property...
3
3185
by: Mark R. Dawson | last post by:
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...
2
2520
by: prabhupr | last post by:
Hi Folks I was reading this article (http://www.dotnetbips.com/articles/displayarticle.aspx?id=32) on "Custom Attribute", written by Bipin. The only thing I did not understand in this article is the usage of "Custom Attribute" in real life project. Can somebody please help me understand where are these informations really helpful in Development Environment; may be a few example(s) will help me understand.
15
2143
by: Jeff Mason | last post by:
Hi, I'm having a reflection brain fog here, perhaps someone can set me on the right track. I'd like to define a custom attribute to be used in a class hierarchy. What I want to do is to have an attribute which can be applied to a class definition of a class which inherits from a base, mustinherit class. I want to define methods in the base class which will access the contents of the attribute as it is applied to
4
1816
by: davearkley | last post by:
I've recently 'discover' the wonders of custom attributes and reflection. There's one aspect that has stumping me and I've been unable to find samples in the docs or on the web. I have fields in a class which have zero, one or more custom attributes associated with each field. I'd like to get a list of the attributes present for a given field, and then iterate over them to find associated values. Where I've coded for the presence of...
2
8336
by: Paul Hadfield | last post by:
Hi, I'm not having a lot of luck googling for this one, I want to be able to store a custom class in the user settings (DotNet2.0, win app). I don't wish to create public get / set properities for all the things I want to persist just for storing in the user settings file (because that would allow other apps to access / change data they shouldn't be able to). I understand how to browse to the object in VS2005 to add an entry to the...
5
1869
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,
1
2138
by: hardieca | last post by:
Hi! I decorate my unfinished classes and methods with a custom TODO attribute (as in things To Do). Using reflection, I am then able to parse through my classes and output all TODOs to a list I can examine to figure out what is left to be done in my application. The attribute is coded thusly: AttributeUsage((AttributeTargets.Class | AttributeTargets.Method),
3
8882
by: =?Utf-8?B?cmFuZHkxMjAw?= | last post by:
The code below goes through all the methods in the given dll. I'm wondering how I can modify this to only get methods with a specific custom attribute. I'm not seeing any Custom Attributes like when I print out the attributes. Thanks, Randy Assembly a = Assembly.LoadFile(s); Type types = a.GetTypes();
0
8251
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8182
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8688
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7178
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6115
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4188
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2614
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
2
1496
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.