Verify ADO.NET Code Access Using Security Permissions
For partial-trust scenarios, you can identify particular methods in your code as requiring a particular code access security privilege by specifying the required SqlClientPermissionAttribute property. If that privilege is not allowed for your code, an exception will be thrown before your code is run.
Note Because the .NET Framework Data Provider for OLE DB and the .NET Framework Data Provider for ODBC are not enabled for partial-trust scenarios, the test for a particular privilege may succeed, but the code will fail with a SecurityException when it executes.
For example, the following code shows a method that is identified as requiring a particular connection string. If that connection string is not allowed, an exception will be thrown and the method will not be executed.
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Security
Imports System.Security.Permissions
Public Class Sample
<SqlClientPermissionAttribute(SecurityAction.Demand, ConnectionString := " Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")> _
Private Shared Sub OpenConn()
Dim testConn As SqlConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")
testConn.Open()
Console.WriteLine("The calling method has been granted sufficient permission to access the database.")
testConn.Close()
End Sub
Public Shared Sub Main()
Try
OpenConn()
Catch e As SecurityException
Console.WriteLine("The calling method has not been granted sufficient permission to access the database.")
End Try
End Sub
End Class
[C#]
using System;
using System.Data;
using System.Data.SqlClient;
using System.Security;
using System.Security.Permissions;
public class Sample
{
[SqlClientPermissionAttribute(SecurityAction.Demand, ConnectionString = " Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")]
private static void OpenConn()
{
SqlConnection testConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;");
testConn.Open();
Console.WriteLine("The calling method has been granted sufficient permission to access the database.");
testConn.Close();
}
public static void Main()
{
try
{
OpenConn();
}
catch (SecurityException)
{
Console.WriteLine("The calling method has not been granted sufficient permission to access the database.");
}
}
}