473,396 Members | 2,003 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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.Messaging
Imports System.Text
Imports System.Runtime.Serialization

<Serializable()> _
Public NotInheritable Class UserPermission
Implements IPermission, ISecurityEncodable, IUnrestrictedPermission,
ISerializable
Private _permission As String = ""
Private _name As String = ""
Private _unrestricted As Boolean = False
Public Function IsUnrestricted() As Boolean Implements
IUnrestrictedPermission.IsUnrestricted
Return _unrestricted
End Function
Public Sub GetObjectData(ByVal info As SerializationInfo, ByVal context
As StreamingContext) Implements ISerializable.GetObjectData
info.AddValue("Permission", _permission)
info.AddValue("User", _name)
info.AddValue("Unrestricted", _unrestricted)
End Sub
Public Sub New(ByVal info As SerializationInfo, ByVal context As
StreamingContext)
_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.Copy
Dim iperm As New UserPermission(PermissionState.None)
iperm._name = Me._name
iperm._permission = Me._permission
iperm._unrestricted = Me._unrestricted
Return iperm
End Function
Public Sub Demand() Implements IPermission.Demand
Try
Dim principal As Security.Principal.IPrincipal =
Threading.Thread.CurrentPrincipal
If principal.IsInRole("UnrestrictedAccess") Then
Exit Sub
End If
If principal.IsInRole(_permission) = False Then
Throw New SecurityException("You do not have rights to
perform the requested function.")
End If
Catch ex As Exception
Throw New SecurityException("You do not have rights to perform
the requested function.")
End Try
End Sub

Public Function IsSubsetOf(ByVal target As IPermission) As Boolean
Implements IPermission.IsSubsetOf
If target Is Nothing Then
Return False
'Return Not Me.IsUnRestricted
End If
Dim passedPerm As UserPermission = target
If passedPerm._permission = Me._permission Then
Return True
Else
Return False
End If
End Function
Public Function Union(ByVal target As IPermission) As IPermission
Implements IPermission.Union
Dim result As New UserPermission(PermissionState.None)
Dim passedPerm As UserPermission = target
result._unrestricted = Me._unrestricted And passedPerm._unrestricted
If Me._name = passedPerm._name Then
result._name = ""
Else
result._name = Me._name
End If
If Me._permission = passedPerm._permission Then
result._permission = ""
Else
result._permission = Me._permission
End If
Return result
End Function
Public Function Intersect(ByVal target As IPermission) As IPermission
Implements IPermission.Intersect
If target Is Nothing Then
Return Nothing
End If
Dim passedPerm As UserPermission = target
End Function
Public Sub FromXml(ByVal e As SecurityElement) Implements
ISecurityEncodable.FromXml
Dim iVal As String

iVal = e.Attribute("User")
_name = iVal
iVal = e.Attribute("Permission")
_permission = iVal
iVal = e.Attribute("Unrestricted")
If iVal <> "" Then
_unrestricted = Convert.ToBoolean(iVal)
End If
End Sub
' Serialize permission object to xml
Public Function ToXml() As SecurityElement Implements
ISecurityEncodable.ToXml
Dim e As New SecurityElement("IPermission")
Dim typ As Type = Me.GetType()
Dim assemblyName As New StringBuilder(typ.Assembly.ToString)
assemblyName.Replace(ControlChars.Quote, "'"c)
e.AddAttribute("class", typ.FullName & ", " & assemblyName.ToString)
e.AddAttribute("version", "1")
e.AddAttribute("Unrestricted", _unrestricted.ToString)
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
NamedPermissionSet("HospitalityMaxPermissionSet", PermissionState.None)
pset.Description = "Permission set containing permissions for
hospitalitymax"
pset.AddPermission(perm)
Return pset.ToXml().ToString()
End Get
End Property
End Class
Imports System.Security
Imports System.Security.Permissions
Imports System.Runtime.Serialization

<AttributeUsage(AttributeTargets.All, inherited:=False,
AllowMultiple:=True), Serializable()> _
Public NotInheritable Class UserPermissionAttribute
Inherits CodeAccessSecurityAttribute
Private _permission As String = "IsAuthenticated"
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(action)
End Sub
Public Overrides Function CreatePermission() As
System.Security.IPermission
Return New UserPermission(MyBase.Unrestricted, _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(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Threading.Thread.CurrentPrincipal = Nothing
Try
Me.SomeCodeToRun()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

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

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim roles() As String = {"CanRunThisCode"}
Dim i As New Security.Principal.GenericIdentity("steve")
Dim p As New Security.Principal.GenericPrincipal(i, roles)
Threading.Thread.CurrentPrincipal = p
Try
Me.SomeCodeToRun()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

Any thoughts?

Jul 21 '05 #1
3 1456
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 FileNotFoundException was
thrown. If there is any misunderstanding, 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 FileNotFoundException was
thrown. If there is any misunderstanding, 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
by: mtv | last post by:
Hi all, I have the following code: ================================ Webservice side: public class MyWS: WebService { private myLib.DataObject curDataObject;
3
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...
3
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...
2
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...
15
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...
4
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...
2
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...
5
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...
1
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...
3
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 ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...
0
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,...

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.