473,322 Members | 1,781 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,322 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 1452
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: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.