Programmatically getting the NameSpaces and Generic Factory to Load the Control

Posted: June 16, 2006 in Uncategorized
This particular Post is more then a year older and today while looking for my Old post i found that it was saved but not published.Thus Publishing  it:-
 
If you are into .Net Programming quite Often you ll get a scenario where by you need to invoke a control or a Class or a method of a particular class type in Runtime .That is During the design or compiletime you are not aware which controls or methods needed to be executed.Further you might also be facing a scenariowhere if you need to Generate same or Different Set of class or Assmebly (EXE or dll doesn’t matter)dynamically .
 
Normally from a developer’s stand point you ll Execute the same using Reflection.Rememebr Reflection gives you the black magic to even alter or execute a Private member too.Further Codegen feature of relflection.emit or codedom can help you in dynamically craeting an assembly or executing or invoking a type in the dynamic or static assembly.Although be aware of the CAS level security while dealing with a dynamic generated assembly particularly under what trust that assembly will run and what would be the trust level you can provide and finally the consequences of using in memory dlls.
 
Howvere this post is not about dynamic generation too [may be some other time].Here by i ll simply show the generic factory pattern you can use to invoke a assembly[dll or exe doesn’t matter again].
 
I am aware of the fact that you might aware of the factory pattern and bit of CodeDom And reflection.However this post is mere a refresher for a new approach and an answer to a common but well hidden question.
My friend asked me  while he was trying with generic factory that how he can get the namespace name…QUITE straight fwd right but believe me it took me 5 minutes and just when i was looking for seraching the reflection and reflector etc;;got it:-
 
Here is the Lione to get the Namespace:-
string nmspace=Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.Namespace;
 
 
Coming to the FActory method .This is How you can use it to Laod dynamic Controls into ur UI:-
 
using System;
using System.Reflection;
using System.Security;
namespace WindowsApplication2
{
 /// <summary>
 /// Summary description for GenericFactory.
 /// </summary>
 public class GenericFactory
 {
  public GenericFactory()
  {
   //
   // TODO: Add constructor logic here
   //
  }
  public static object CreateObj( string asmName, string typeName, object[] constArgs )
  {
    // Instance to hold assembly
   Assembly  asm   = null;
   // Instance to Type Information
   Type   typeInfo = null;
   // Load the Assembly.
   try
   {
    // current executing assembly, which should be ur assembly
    // If the name of the assembly is not given then take the current executing assembly.
    if ( ( asmName != "" ) || ( asmName != string.Empty ) )
     // Load the assembly
     asm  = Assembly.LoadFrom( asmName );
    else
     asm  = Assembly.GetExecutingAssembly();
   }
   catch( SecurityException e )
   {
    // To do: Exception Handling
    throw e;
   }
   catch( Exception e )
   {
    // To do: Exception Handling Mechs
    throw e;
   }
   // Load type information
   try
   {
    //  use type name to get type from asm; note we WANT case specificity
    typeInfo = asm.GetType( typeName.Trim(), true, false );
    
    if ( constArgs != null )
     // Create the object dynamically with args
     return Activator.CreateInstance( typeInfo, constArgs );
    else
     // Create the object dynamically.
     return Activator.CreateInstance( typeInfo );
   }
   catch( Exception e )
   {
    // To do: Exception Handling Mechs
    throw e;
   }
  }
 
 }
}
 
private void Form2_Load(object sender, System.EventArgs e)
  {
      object[] objarr={"shreeman"};
      object obj=GenericFactory.CreateObj("","WindowsApplication2.UserControl1",objarr);
      this.panel1.Controls.Add((UserControl)obj);
      
  
  }
  private UserControl getnextcontrol(string classname)
  {
   string nmspace=Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.Namespace;
   string typename=nmspace+"."+classname;
   object[] objarr={"shreeman"};
   object obj=GenericFactory.CreateObj("",typename,objarr);
   return((UserControl)obj);
   
  }
  string getnextcontrolname(string currctrlname)
  {
   switch ( currctrlname)
   {
 
//this is for demo purposes only and you need to change ur code accordingly
    case "UserControl1" :
     return "UserControl2";
    case "UserControl2" :
     return "UserControl3";
    case "UserControl3" :
     return "UserControl1";
    default :
     return null;
   }
  }
  private void button1_Click(object sender, System.EventArgs e)
  {
   UserControl uc=new UserControl ();
   uc=(UserControl)this.panel1.Controls[0];
   uc=getnextcontrol( getnextcontrolname(this.panel1.Controls[0].Name));
   this.panel1.Controls.Add(uc);
   this.panel1.Controls.SetChildIndex(uc,0);
 
  }
 
 
//What if i want to Run an exe using Reflection.Remembervthat .Net unit is Assembly be it dll or Exe reflection doesn’t mind
//   object obj=GenericFactory.CreateObj("WindowsApplication2.exe","WindowsApplication2.Form1",null);
//   //this.panel1.Controls.Add((UserControl)obj);
//   ((Form)obj).Show();
 
Hope that I shade few more lights into the older topic.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s