Search code examples
c#linqpad

Running a LINQPad query with SQL impersonation


I am trying to perform a SQL query, in LINQPad, with impersonation but the impersonating user does not have access to the original user's AppData folder, which causes my SqlConnection constructor to throw a TypeInitializationException:

using (var db = new SqlConnection(ConnectionString))
{
    // ...
}

The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.

The InnerException here is a FileNotFoundException on the actual executable for the LINQPad query:

C:\Users\MyUser\AppData\Local\LINQPad\ProcessServer5AnyCPUB\LINQPad.UserQuery.exe

Is there some way for me to configure that folder so that LINQPad will try to run with an executable in a location accessible by all user accounts? I have looked at LINQPad's preferences but I couldn't find any place to specify the folder for the LINQPad.UserQuery.exe


Solution

  • I managed to resolve this after posting a question in the LINQPad user forum (link). The key came from a link suggested by Joe Albahari himself:

    https://social.msdn.microsoft.com/Forums/lync/en-US/90e313c6-bf2f-45ac-a595-a7b6c4aae7e1/windowsidentityimpersonate-throws-catastrophic-failure-exception-from-hresult-0x8000ffff

    I moved the impersonation call so that, instead of wrapping around the SqlConnection and the commands associated with it, it now wraps only around my db.Open() statement. This is because an impersonated SqlConnection constructor tries to read various configs from places it might not have access to.

    I am still debating with myself whether this can cause problems if a pre-opened connection is available from the connection pool but, for the purposes of my application, I don't have that problem.