In the previous sections we understood that before the code
executes it can ask the runtime for the permission to execute. The permission
for an assembly is given by placing attributes. Placing attributes and asking
permissions is known as declarative syntax. (It should be noted that it is not
mandatory for the code to ask for the permission.)
Let us understand this with the help of an example. If we
have an application that reads and writes to the local hard disk then the application
must have FileIOPermission. If the
code does not request FileIOPermission and the local security settings do not
allow your application to have this permission, a security exception is raised
when the application attempts to write to the disk. There are 2 things that
need to be understood here.
·
The local system security does not allow the application to do
anything on the disk.
·
The Application does not request for the FileIOPermission.
On a different scenario, if the application requests
FileIOPermission and the local security settings does not permit the application
to have FileIOPermission, the application will generate the exception. But in
this case, we can programmer can ensure that user will not loose any data.
Different Types of permissions
We have different types of permission sets. Let us see some
of them in detail.
1.
Minimum permissions (RequestMinimum) - Permissions for the code have to
run.
2.
Optional permissions (RequestOptional) - Permissions for the code that
can be bypassed to run without them.
3.
Refused permissions (RequestRefuse) - Permissions that you want to
ensure will never be granted to your code, even if security policy allows them
to be granted.
Listing 1 shown below is the code written in C# that
explains the request for permission from an assembly using attributes.
Listing 1
[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]