In an impersonation scenario related to Sharepoint I need to execute some code in a separate process (the process will run in the context of a certain user). I do not want to launch a separate application, basically I want to do a "run as" on just a method.
"Execute code in a separate process" = "launch a separate application" though.
I mean, you could launch a single process and then make requests to it to run the particular method... but it's not clear whether that's what you want.
I haven't tried this myself but this seems to do the trick.
If you are fine with the impersonated method blocking until it finishes it should work. So your code would be something like:
...
WrapperImpersonationContext context = new WrapperImpersonationContext(domain, username, password);
context.Enter();
Results res = MyImpersonatedMethod(data);
context.Leave();
...
Hope this helps.
The Process.Start method has an overload to start the process provided you have the appropriate user, password and domain.
What you want to do is create a ProcessStartInfo object and specify the proper UserName and Password when starting the process. So you can do something like this:
Dim psiNewProcess As New ProcessStartInfo("Notepad.exe")
psiNewProcess.UserName = "MyUserName"
psiNewProcess.Password = "MyPassword"
Process.Start(psiNewProcess)
Oh, Process is in the System.Diagnostics namespace if it isn't already imported for your project.
EDIT: Quick sidenote, the password field is actually a SecureString type object, so MSDN suggests filling the value in this way:
Dim instance As ProcessStartInfo
Dim value As SecureString
value = instance.Password
instance.Password = value