In some cases you may need to use Sharepoint object model outside of the Sharepoint context (i.e. when SPContext.Current is null) and without http context (HttpContext.Current is null), e.g. from console application. If internal methods of the API require not nullable SPContext.Current, you may fake it using the following method (see my another post Override SPContext.Current.Web and Site with sites opened with elevated privileges for explanations why it works like this):
After this SPContext.Current won’t be null, and code which requires it will work. However it brings one problem. If you will try to use User profiles service application with such fake context, you will get NullReferenceException. For example, suppose that we need to enumerate all imported user profiles using the following code:
When you will run it in console application you will get NullReferenceException with the following stack trace:
at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext, Boolean IgnoreUserPrivacy, Boolean backwardCompatible)
at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext)
Let’s check implementation of UserProfileGlobal.IsWindowsAuth() method which causes exception:
As you replace context with fake instance, condition on line 4 will be true and execution will go to the line 6 where it will fail, because context.User is null. In order to fix it you have to specify user when you fake HttpContext. The way how you should do that depends on the authentication type used in your web application: standard or claims based.
For standard windows authentication you should use the following code:
For claims based use the following code:
After that you will be able to use UserProfileManager and work with user profiles in the console application.