Accessing Databases via Custom Code
Another good question in response to my Custom Code in Report Services article.
I am trying to access a database through a custom assembly and I already have the following in the rssrvpolicy.config file , but I still get the #Error. [snip] Do I need an associated permission set? And what would that be if I do, I dont know?
The answer that yes you do need an associated permission set. If you're using the System.Data.SqlClient to connection to a SQL Server database then you will need the SqlClientPermission. This would look like:
<PermissionSet
class="NamedPermissionSet"
version="1"
Name="MyDatabasePermissionSet"
Description="A special permission set that grants sql access.">
<IPermission
class="SqlClientPermission"
version="1"
Unrestricted="true"
/>
<IPermission
class="SecurityPermission"
version="1"
Flags="Execution, Assertion"
/>
</PermissionSet>
So where did I get this information from? I already knew that the SqlClientPermission was what I needed from some previous projects and I was able to determine what the IPermission section should look like based on Lamont's post. However, this brings up something that I've been unable to figure out: how do you figure out what should be in the IPermission section?
Maybe I'm just missing it but I read through a few CAS articles and I've searched through the documentation and yet somehow this remains a total mystery to me. Is this documented somewhere? Can you point me to it?
The question (from above) continues:
And do I need to do step 3 and 4 of your article for my custom assembly if I am only accessing a database from my function.
And If I do, what would step 3 and 4 be?
Yes you do need to do steps 3 and 4. Step 4 would be exactly the same. In step 3 you would need to assert the SqlClientPermission on your method as follows:
[VB]
<SqlClientPermission(SecurityAction.Assert)> _
Public Shared Function Foo() as String
...
[C#]
[SqlClientPermission(SecurityAction.Assert)]
public static string Foo()
...
I'm going to go back and read up some more on CAS. It is something every .Net developer should understand.
Update:
For some reason when I was testing this I was getting a security exception even though I was asserting SqlClientPermission on the method call. I found I had to actually assert the permission in my code before it would work. The code I used is posted below. I would really like to understand this better but I'm actually heading out of town for a few days with my wife for our 1st wedding anniversary.
[VB]
Dim perm as SqlClientPermission new SqlClientPermission(PermissionState.Unrestricted)
perm.Assert()
'' SQL CODE HERE
CodeAccessPermission.RevertAssert()
[C#]
SqlClientPermission perm = new SqlClientPermission(PermissionState.Unrestricted);
perm.Assert();
// SQL CODE HERE
CodeAccessPermission.RevertAssert();