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.

Monday, October 24, 2011

Fusion log viewer fuslogvw ie Assembly Binding Log Viewer

When you work with .net and your dlls are scattered around GAC, application bin, or reference assemblies its very difficult to check which version of dll is loaded in the application. Without knowing that you cannot ensure that your code changes are in effect. For small projects you can put Console.WriteLine or Messagebox.Show to indicate your code change .But when we talk about bigger applications with hundreds of project and thousands of code files ,it is not practical.Also there are chances that your message box code might get checked into the code repository which gives fun for others.

Another scenario is creating and maintaining AppDomains .There are concepts like ApplicationBasePath, PrivateBinPath for the appdomains which decides from where the runtime should load the assembly or what is the sequence in searching for assembly. If you are versioning your application there are chances for MissingMethodException if the loaded assembly is not compatible with the versions.

All these things says we need to profile/inspect the assembly loading behavior in .net on the fly to make sure the dlls are loaded from correct location and it is the Fusion log viewer which comes with Visual Studio.

Starting the tool
  • Make sure the registry entry HKLM\Software\Microsoft\Fusion\ForceLog is 1
  • Goto visual studio command prompt.
  • Type and enter 'fuslogvw'
  • This will bring you the tool window.Make sure the log path is correct.
  • Now run your assembly.
  • Once the application loads click on the refresh button in the assembly log viewer.
  • You got the details of assemblies loaded with loading history and from which location
This is very useful in my current project to identify assembly loading where we have versioning and play with AppDomains all around.

Tuesday, October 4, 2011

ControlledSingleton pattern

Some months back I had written a post to describe how to get the name of the calling method programmatically. ie to get the call stack entry just below the current method. That post was born in relation with one of our requirement to create controlled singleton pattern which I described in it’s previous post.

Why we need ControlledSingleton pattern?

This is needed when you plan to make a class Singleton after so much code is written using that class and you have technical and managerial limitations to change all the existing code.The normal singleton pattern with private constructor will not be applicable here since it needs full inspection in your code base for compilation as well as usage of reflection. You can easily fix the compilation issues but reflection cannot be caught that much easily.Also if you are serializing the Singleton class to persist its state or pass through WCF, certainly you cannot make it as singleton otherwise the serializer will fail.

If your company management in case of product development or you client in case of projects are really adamant on quality and are ready to give you enough time to refactor code,just go with that and implement the real singleton. Also if you are developing a new project you can decide on which class to be singleton and make that as normal singleton class.Unfortunately I didn’t had this luxury which lead me to the ControlledSingleton pattern.

What is ControlledSingleton

According to me it’s same as normal singleton but giving permission to some components to create the object of singleton class.The components may be some classes,some methods or some assemblies.That depends on the requirements of the developer who implements the pattern. I am not sure whether there are any other pattern in different name which is same as this.

Implementing ControlledSingleton

This depends upon the environment / programming language you are using.Since I am a .net developer I can see 2 methods to implement the pattern

  1. Validating the caller using call stack
    This can be achieved by inspecting the current call stack and checking whether the caller has the permission to create the object.Please refer my previous posts to get detailed idea.
    http://joymonscode.blogspot.com/2011/02/how-to-get-calling-method-name.html

    Characteristics:-The draw back of this method is we cannot ensure singleton at compile time.Each and every time before inspecting the call stack will cause performance impacts. This is applicable only in managed languages where we have the method name at runtime.
  2. InternalsVisibleTo attribute
    The InternalsVisibleToAttribute defined on assembly tells the system that there are some more assemblies which can see it’s internal members. That means if we make a class Singleton using internal constructor the assemblies which are specified in the InternalsVisibleTo attribute can create the object of the singleton class.

    Characteristics:-The advantage of this is we can ensure at the compile time itself. This idea can also extend to unmanaged languages too since it works at compile time.

About attached sample

The sample contains 3 projects. “ControlledSingleton” project contains the singleton class PersonsContext. The class is made as Singleton using internal constructor which means any class inside that project can create the instance of the singleton class. The InternalsVisibleTo attribute is pointing to the second assembly named “SingletonPermitted”.ie it can create object of PersonContext.The “ControlledSingleton_Demo” is a console application which don’t have permission to create the object of singleton class. It cannot even try to use reflection to create the object.

Download the sample from here.

Recommended changes

The above methods allows so many objects of the singleton class in the system at same time.If you don’t have serialization on your singleton candidate you can think about a ReInitializeSingleton method which is internal to modify/replace the single ton object.

internal ReinitializeSingleton(params)