Recently we were working with LINQ to SharePoint Web Part for anonymous users and faced an issue with elevated permissions.
Web Part has query through LINQ to a custom list for which currently logged in user (logged in user is anonymous user) does not have access so Web Part runs with elevated privilege but it was not working.
Reason: LINQ seems to build some “context” even before the Web Part runs with Elevated Privileges so that it throws an exception says that list “yourlistname” is not available/found.
Code with Problem:
Findings: It was an interesting issue, after researching I found that it was because of a constructor which call in the class SPServerDataConnection class within the Microsoft.SharePoint.Linq.dll
Lawbreaker: Microsoft.SharePoint.Linq.Provider.SPServerDataConnection class
Background Process: When we create a new instance of SharePoint Linq DataContext it actually executes a constructor of SPServerDataConnection class where some funny things happening in behind. If we are executing the code with SPContext then it will be using the SPSite and SPWeb instances under the current context and because of that we were getting an exception.
The issues was how to find internal code of SPServerDataConnection, so i used Reflector and got that as below:
Solution: After reviewing SPServerDataConnection code we found that we can tweak this functionality by creating a new HttpContext and use it under elevated permission to execute our code. After our usage set the actual SPContext back.
Sample Web Part code given below
NOTE: Make sure that you are setting the actual SPContext back after your operation.
Hope this will help!!!