Monday, October 31, 2011

Running another .net executable without Process.Start

Whenever we get a requirement like this first answer will be Process.Start which is the common way to start another application from one application. It creates different process ,its region and execute independently.
static void StartProcess()
{
    Process proc = new Process();
    proc.StartInfo = new ProcessStartInfo() {FileName=@"Path\Executable file.exe" };
    proc.Start();
}

This is the correct solution if the application is not a .net executable.You can also see new process in the task manager. But here we need to load an application which is in .net itself. So are there any other method to load a new application in the current process itself?

It is YES since AppDomain is a unique feature in.Net. AppDomain is an another separation in the process for isolated execution.This separation is managed by the .Net runtime, not by the windows OS which manages Process and its allocation. Everybody must have heard about AppDomain and will be in confusion with Application and Process.  For more details about AppDomain please refer the articles below

http://codebetter.com/raymondlewallen/2005/04/04/what-is-an-application-domain-an-explanation-for-net-beginners/
http://msdn.microsoft.com/en-us/library/2bh4z9hs(v=vs.71).aspx

Once you are confortable with AppDomain read the below which explains how to create new AppDomain of the other application and start it.

Executing an Assembly present other application using Appdomain

Creating the appdomain is very easy as follows
//Creating the setup object
AppDomainSetup setup = new AppDomainSetup();

setup.ApplicationBase = @"D:\Joy\POCs\DesktopUIApp";
//Set the probing path if needed
//setup.PrivateBinPath = "Some path which resides inside ApplicationBase";

//Create the domain
AppDomain domain = AppDomain.CreateDomain("NewApp", AppDomain.CurrentDomain.Evidence, setup);
Now we have the appdomain. If you are a .net developer with knowledge in reflection you can think about so many techniques to start the other application as follows

1) Create assembly using the AppDomain.Load method and get the Main() method’s MethodInfo and invoke it.
2) Create type of App of target application using the AppDomain.CreateInstanceAndUnwrap () and executes it.

But almost all these techniques will fail because it cannot create another application inside this appdomain since it has one.ie multiple Applications are not allowed in same app domain.So the API which works is as follows.
AppDomain domain = AppDomain.CreateDomain("NewApp", AppDomain.CurrentDomain.Evidence, setup);
domain.ExecuteAssembly(@"D:\Joy\POCs\DesktopUIApp\DesktopUI.exe");
            

This executes the specified assembly in the new appdomain. Only thing you need to know is the name of the assembly to be started.This is not useful when you don’t know what type of files to be opened such as downloading files from server and opening it.

No comments: