Question

We are trying to access the active directory services using C# on SharePoint webpart. There was COM exception when executing: SearchResultCollection resultCol = search.FindAll();

I got the solution from the answer of atconway here.

And accordingly I have surrounded my code with:

using (HostingEnvironment.Impersonate()){
//code
}

It works well now, but is it good practice to deploy this on production server? If not, then how else could we bypass the exception?

Do I try to use: SPSecurity.RunWithElevatedPrivileges instead? This article mentioned the both are equivalent..

Was it helpful?

Solution

As the article you link to explains, SPSecurity.RunWithElevatedPrivileges is considered the best practice if your code is being executed within a SharePoint server-side context. Since it is part of SharePoint's server API, it can only function on a server within a SharePoint Farm. If your web application is running on IIS on a non-SharePoint environment, HostingEnvironment.Impersonate() is the correct method.

Note that both methods allow the code within the encompassing block to run under the context of the current App Pool Identity, instead of context of the current calling user, the only question is whether your code is part of a stand-alone ASP.NET application or part of a SharePoint hosted solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top