Archive for June, 2006

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.

LDAP verification

Posted: June 7, 2006 in Uncategorized

Often this is a common requirement to validated the user from the active directory or LDAP.Here by i am showing you a simple routine which will take the user alias for the domain and retrieve the userinfo:-

Fisrt of all you need to import the directory class:-

using

System.DirectoryServices; 

Keep this Routine in a Class let say DirectoryServiceHelper:-

 

public static void GetUserInfo(string alias,out string fullname,out string firstname,out string lastname)

            {

                 

                  string delimStr            =  @”\”;

                  char [] delimiter          =  delimStr.ToCharArray();

                  string[] domain;

 

                  //To get the domain name

                  try

                  {

                        domain=alias.Split(delimiter,2);

                        string LookUpDirectory     =”LDAP://” +domain[0];

                 

                        DirectoryEntry entry       = new DirectoryEntry(LookUpDirectory);

                        DirectorySearcher dSearch  = new DirectorySearcher(entry);

 

                        //Filter by alias name

                        dSearch.Filter             = “(mailnickname= ” + domain[1] + “)”;

                        fullname                   = “”;

                        firstname                  = “”;

                        lastname                   = “”;

 

                        foreach(SearchResult sResultSet in dSearch.FindAll())

                        {

 

                              if(sResultSet.Properties.Contains(“cn”))

                              {

                                    //assign fullname

                                    fullname          = sResultSet.Properties[“cn”][0].ToString() ;

                                                     

                              }

 

                       

                              if(sResultSet.Properties.Contains(“givenName”))

                              {

                                    //assign firstname

                                    firstname          = sResultSet.Properties[“givenName”][0].ToString() ;

                                                     

                              }

                 

                              if(sResultSet.Properties.Contains(“sn”))

                              {

                                    //Assign lastname

                                    lastname          = sResultSet.Properties[“sn”][0].ToString() ;

                                                     

                              }

                    

                        }

   

                  }

                  catch ( Exception ex )

                  {

                        throw ex;

                  }

            }

 

and in ur Main Routne or Startup Routine validet the user:-

 

public void AuthenticateUser()

{

 

string  alias;

string  firstName;

string  lastName;

string  name;

WindowsIdentity windowIdentity =  WindowsIdentity.GetCurrent();

aliaswindowIdentity.Name;

try

{

DirectorySvcHelper userAuthetnicate  =  new DirectorySvcHelper();

DirectorySvcHelper.GetUserInfo( alias, out name, out  firstName, out  lastName );

}

catch( Exception ex )

{

throw ex;

}