views:

469

answers:

3

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.

A: 

"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.

Jon Skeet
Could you point to where can find more info on this subject, maybe an example. This is what I want to do.
iulianchira
Basically you'd need to start a new process (once) and communicate over a named pipe (or whatever). If you're using a recent version of .NET, WCF may be the best option - so pick up a WCF book or tutorial.
Jon Skeet
+2  A: 

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.

Gunnar Steinn
A: 

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
Dillie-O
I do not want to launch a new application. Is it possible to use ProcessStartInfo to run a piece of code from the application in which I create the new process?
iulianchira
No, it's not possible to use ProcessStartInfo to do that.
skst