Documente Academic
Documente Profesional
Documente Cultură
Reflection
Facultatea de Informatica Iasi Universitatea Al I. Cuza Iasi
21.01.2007
Daca safemode = false, atunci se incarca versiunea de CLR cea mai recenta ce este
compatibila cu versiunea aplicatiei noastre.
Ioan Asiminoaei
21.01.2007
Ioan Asiminoaei
21.01.2007
Public Properties
BaseDirectory
CurrentDomain
DynamicDirectory
Evidence
FriendlyName
Public Methods
AppendPrivatePath
ClearPrivatePath
ClearShadowCopyPath
CreateComInstanceFrom
CreateDomain
Ioan Asiminoaei
21.01.2007
Compact Framework.
GetLifetimeService (inherited Retrieves the current lifetime service object that
controls the lifetime policy for this instance.
from MarshalByRefObject)
Gets the Type of the current instance.
GetType (inherited from
Object)
Supported by the .NET
Compact Framework.
SetShadowCopyFiles
SetShadowCopyPath
InitializeLifetimeService
IsFinalizingForUnload
Load
SetAppDomainPolicy
SetCachePath
SetData
SetDynamicBase
SetPrincipalPolicy
Ioan Asiminoaei
21.01.2007
SetThreadPrincipal
ToString
Supported by the .NET
Compact Framework.
Unload
Public Events
AssemblyLoad
AssemblyResolve
DomainUnload
ProcessExit
ResourceResolve
TypeResolve
UnhandledException
Protected Methods
Framework.
destructor syntax.
MemberwiseClone (inherited Creates a shallow copy of the current Object.
from Object)
Supported by the .NET Compact
Framework.
AppDomain.AssemblyLoad Event
[C#]
public virtual event AssemblyLoadEventHandler AssemblyLoad;
Event Data
Functia ce trateaza evenimentul primeste un argument de tip AssemblyLoadEventArgs
ce contine informatii despre acest eveniment.
Proprietatea AssemblyLoadEventArgs furnizeaza informatii specifice pentru acest
eveniment.
Property
Ioan Asiminoaei
Description
21.01.2007
Remarks
The AssemblyLoadEventHandler delegate for this event indicates what assembly was
loaded.
To register an event handler for this event, you must have the permissions described
in the Permissions section. If you do not have the appropriate permissions, a
SecurityException occurs.
For more information about handling events, see Consuming Events.
Example
[Visual Basic, C#, C++] For this code example to run, you must provide the fully
qualified assembly name.
[C#]
using System;
using System.Reflection;
class Test {
public static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyLoad += new
AssemblyLoadEventHandler(MyAssemblyLoadEventHandler);
PrintLoadedAssemblies(currentDomain);
// Lists mscorlib and this assembly
// You must supply a valid fully qualified assembly name here.
currentDomain.CreateInstance("System.Windows.Forms, Version,
Culture, PublicKeyToken", "System.Windows.Forms.TextBox");
// Loads System, System.Drawing, System.Windows.Forms
PrintLoadedAssemblies(currentDomain);
// Lists all five assemblies
}
static void PrintLoadedAssemblies(AppDomain domain)
{
Console.WriteLine("LOADED ASSEMBLIES:");
foreach (Assembly a in domain.GetAssemblies())
{
Console.WriteLine(a.FullName);
}
Console.WriteLine();
}
static void MyAssemblyLoadEventHandler(object sender,
AssemblyLoadEventArgs args)
{
Console.WriteLine("ASSEMBLY LOADED: " +
args.LoadedAssembly.FullName);
Console.WriteLine();
}
}
Ioan Asiminoaei
21.01.2007
AppDomain.CreateInstanceAndUnwrap Method
Creates a new instance of a specified type.
Overload List
Creates a new instance of the specified type. Parameters specify the assembly where
the type is defined, and the name of the type.
[C#] public object CreateInstanceAndUnwrap(string, string);
Creates a new instance of the specified type. Parameters specify the assembly where
the type is defined, the name of the type, and an array of activation attributes.
[C#] public object CreateInstanceAndUnwrap(string, string, object[]);
Creates a new instance of the specified type. Parameters specify the name of the
type, and how it is found and created.
[C#] public object CreateInstanceAndUnwrap(string, string, bool, BindingFlags,
Binder, object[], CultureInfo, object[], Evidence);
[C#]
public object CreateInstanceAndUnwrap(
string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes,
Evidence securityAttributes
);
Parametri
assemblyName = nume assembly.
typeName = numele tipului cerut (calificat complet).
ignoreCase = valoare booleana; specifica daca se executa cautare case-sensitive sau
nu.
bindingAttr = o combinatie de flaguri ce afecteaza cautarea constructorului pentru
typeName.
binder = un obiect ce permite legarea, verificarea tipurilor argumentelor, invocarea
membrilor si regasirea obiectelor MemberInfo folosind reflection. Daca binder este
null, atunci se foloseste legarea implicita.
args = argumentele ce trebuiesc pasate constructorului. Daca se doreste apelarea
constructorului implicit, args trebuie sa fie null.
culture = obiect folosit in verificarea tipurilor.
activationAttributes = un tablou de atribute ce pot participa in procesul de invocare.
securityAttributes = atribute de securitate pentru typeName.
Valoarea returnata reprezinta o instanta a obiectului specificat de typeName.
Exceptions
Exception Type
ArgumentNullException
Ioan Asiminoaei
Condition
assemblyName or typeName is a null
SecurityException
AppDomainUnloadedException
21.01.2007
Exemplu
[C#]
using System;
using System.Reflection;
class Test {
static void Main() {
InstantiateINT32(false);
InstantiateINT32(true);
}
// Failed!
// OK!
Exemplu pentru CreateDomain (vezi MS). Importante sunt etapele de creare, care
urmaresc prototipul metodei CreateDomain ce va fi folosita.
Ioan Asiminoaei
21.01.2007
Public Properties
ApplicationBase
ApplicationName
CachePath
ConfigurationFile
DisallowBindingRedirects
DisallowCodeDownload
DisallowPublisherPolicy
DynamicBase
LicenseFile
LoaderOptimization
PrivateBinPath
PrivateBinPathProbe
Ioan Asiminoaei
21.01.2007
to locate an application.
Gets or sets the names of the directories containing
assemblies to be shadow copied.
Gets or sets a string that indicates whether shadow
copying is turned on or off.
ShadowCopyDirectories
ShadowCopyFiles
Clasa Evidence
Defineste multimea de informatii ce constituie intrare pentru deciziile politicii de
securitate. Clasa nu poate fi mostenita.
Obiectele de orice tip ce sunt recunoscute de politica de securitate reprezinta
evidence.
Politica de securitate este compusa din grupuri de cod; un assembly particular
(unitatea de baza pentru acordarea drepturilor de securitate) este un membru al unui
cod de grup daca satisface conditiile membrilor grupului de cod.
Evidence este multimea intrarilor pentru aceasta politica de securitate folosita
pentru a determina carui grup de cod ii apartine un anumit assembly.
Clasa Evidence este o colectie (vezi ICollection) ce pastreaza multimea obiectelor ce
reprezinta evidence.
Aceasta clasa tine doua multimi ce corespund sursei evidence : host evidence si
assembly evidence.
Cand se evalueaza permisiunile unui cod se folosesc aceste doua multimi.
Host evidence is provided by the host, and can only be provided by hosts
that have been granted the ControlEvidence permission. Typically, this is evidence
of the origin of the code and digital signatures on the assembly. Evidence about
origin typically includes Url, Site, and Zone evidence. Signatures refer to software
publisher (AuthentiCode X.509v3 signature) and strong name identities. Both
kinds of digital signature-based identity are built into the assembly, but must be
validated and passed to policy by the host; when loaded, the security system
verifies the signature. The system then creates the appropriate evidence and
passes it to policy only if the corresponding signature is valid.
Public Constructors
Evidence Constructor
Supported by the .NET Compact
Framework.
Public Properties
Count
IsReadOnly
IsSynchronized
Locked
Ioan Asiminoaei
10
21.01.2007
locked.
Gets the synchronization root.
Public Methods
AddAssembly
AddHost
CopyTo
Equals (inherited from Object)
GetEnumerator
GetType (inherited from Object) Gets the Type of the current instance.
Supported by the .NET Compact
Framework.
Merges the specified evidence set into the current
evidence set.
ToString (inherited from Object) Returns a String that represents the current
Object.
Supported by the .NET Compact
Merge
Framework.
Protected Methods
Ioan Asiminoaei
11
21.01.2007
Ioan Asiminoaei
12
21.01.2007
Evenimente AppDomain
Evenimentele pe care le putem trata sunt:
AssemblyLoad apare cand CLR incarca un assembly intr-un domeniu. Functia ce trateaza
evenimentul primeste un obiect System.Reflection.Assembly ce identifica assembly
incarcat.
DomainUnload - apare inainte ca AppDomain sa fie descarcat. Evenimentul nu apare
cand procesul ce contine AppDomain este terminat.
ProcessExit - apare inainte ca procesul sa se termine. Evenimentul este lansat numai
pentru AppDomain implicit.
UnhandledException - emis cand apare o exceptie intr-un AppDomain.
AssemblyResolve apare cand CLR nu poate localiza un assembly cerut de un domeniu.
Functia ce trateaza evenimentul primeste un string ce identifica numele assembly lipsa.
ResourceResolve acelasi lucru ca la AssemblyResolve, numai ca este vorba de o resursa.
TypeResolve Acelasi lucru ca mai sus, numai ca este vorba de un tip de data.
Din nou despre Reflection
Metadata este constituita dintr-o multime de tabele. Cand construim un assembly sau un
modul, compilatorul creaza o serie de tabele: tabela de definitie a tipurilor, tabela de
definitie a campurilor, tabela de definitie a metodelor, etc.
Spatiul de nume System.Reflection din FCL contine mai multe tipuri ce permit sa scriem
cod ce obtine informatii din aceste tabele. Tipurile din acest spatiu de nume ofera un
model obiect peste metadata continuta in assembly sau modul.
Cu ajutorul acestor tipuri putem enumera toate tipurile dintr-o tabela de definitie a
tipurilor. Pentru fiiecare tip putem obtine tipul de baza, ce interfete implementeaza.
De asemenea putem obtine campurile, metodele, proprietatile, atributele si evenimentele
unui tip.
Metoda reflection este cel mai des folosita cu clasele de biblioteci pentru a construi
ierarhia corecta a definitiei tipurilor.
Aceasta metoda poate fi folosita pentru a incarca un assembly in mod explict, apoi sa
construiasca un obiect de un anumit tip (tip gazduit de acest assembly) si apoi sa apeleze
metodele pe acest obiect (ceva asemanator cu LoadLibrary si GetProcAddress din Win32
API) se realizeaza legarea intarziata .
Obtinerea tipurilor unui assembly (reflection method)
Exemplu
using System;
using System.Reflection;
class App
{
static void Main()
{
Assembly assem = Assembly.GetExecutingAssembly();
Reflector.ReflectOnAssembly(assem);
}
}
public class Reflector
{
Ioan Asiminoaei
13
21.01.2007
Rezultatul este:
Assembly: p7_reflection, Version=1.0.1783.28359, Culture=neutral, PublicKeyToken
=null
Module: p7_reflection.exe
Type: App
Method: Int32 GetHashCode()
Method: Boolean Equals(System.Object)
Method: System.String ToString()
Method: System.Type GetType()
Constructor: Void .ctor()
Type: Reflector
Method: Int32 GetHashCode()
Method: Boolean Equals(System.Object)
Ioan Asiminoaei
14
21.01.2007
Ioan Asiminoaei
15
21.01.2007
16
21.01.2007
System;
System.Text;
System.Reflection;
System.Collections;
App
static void Main()
{
// Incarcam in mod explicit assembly pe care
// vrem sa aplicam reflection
Ioan Asiminoaei
17
21.01.2007
Initializare contoare
totalTypes = numar total tipuri
totalExceptionType = numar total tipuri exceptii
exceptionTree = lista cu tipuri de exceptii
Ioan Asiminoaei
18
21.01.2007
h,
1,
h.Length
}
}
// Sortam tipurile Exception in ordinea ierarhiei lor.
exceptionTree.Sort();
// Afisam arborescenta Exception.
foreach (String s in exceptionTree)
{
// Pentru acest tip Exception,
// separam tipul de baza sa.
String[] x = s.Split(-);
// Indentam pe baza numarului de tipuri de baza.
Console.WriteLine(
new String( , 3 * x.Length) + x[x.Length - 1]);
}
// Afisam starea finala a tipului considerat.
Console.WriteLine("\n> Of {0} types, {1} are " +
"derived from System.Exception.",
totalTypes, totalExceptionTypes);
Console.ReadLine();
}
static void LoadAssemblies()
{
String[] assemblies = {
"System, PublicKeyToken={0}",
"System.Data, PublicKeyToken={0}",
"System.Design, PublicKeyToken={1}",
"System.DirectoryServices, PublicKeyToken={1}",
"System.Drawing, PublicKeyToken={1}",
"System.Drawing.Design, PublicKeyToken={1}",
"System.EnterpriseServices, PublicKeyToken={1}",
"System.Management, PublicKeyToken={1}",
"System.Messaging, PublicKeyToken={1}",
"System.Runtime.Remoting, PublicKeyToken={0}",
"System.Security, PublicKeyToken={1}",
"System.ServiceProcess, PublicKeyToken={1}",
"System.Web, PublicKeyToken={1}",
"System.Web.RegularExpressions, PublicKeyToken={1}",
"System.Web.Services, PublicKeyToken={1}",
"System.Windows.Forms, PublicKeyToken={0}",
"System.Xml, PublicKeyToken={0}",
};
String EcmaPublicKeyToken = "b77a5c561934e089";
String MSPublicKeyToken = "b03f5f7f11d50a3a";
// Obtinem versiunea assembly ce contine System.Object.
// Vom presupune aceeasi versiune
// pentru toate celelate assemblies.
Ioan Asiminoaei
19
21.01.2007
Version version =
typeof(System.Object).Assembly.GetName().Version;
// Incarcam explicit assembly pe care vrem sa
// aplicam reflection
foreach (String a in assemblies)
{
String AssemblyIdentity =
String.Format(a, EcmaPublicKeyToken,
MSPublicKeyToken) +
", Culture=neutral, Version=" + version;
Assembly.Load(AssemblyIdentity);
}
}
}
Rezultatul este:
System.ApplicationException
System.Reflection.InvalidFilterCriteriaException
System.Reflection.TargetException
System.Reflection.TargetInvocationException
System.Reflection.TargetParameterCountException
System.IO.IsolatedStorage.IsolatedStorageException
System.Runtime.Remoting.MetadataServices.SUDSGeneratorException
System.Runtime.Remoting.MetadataServices.SUDSParserException
System.SystemException
System.AppDomainUnloadedException
System.ArgumentException
System.ArgumentNullException
.............................................
Of 7281 types, 135 are derived from System.Exception.
Explicatie asupra codului:
String[] assemblies = {
"System, PublicKeyToken={0}",
"System.Data, PublicKeyToken={0}",
"System.Design, PublicKeyToken={1}",
"System.DirectoryServices, PublicKeyToken={1}",
"System.Drawing, PublicKeyToken={1}",
"System.Drawing.Design, PublicKeyToken={1}",
"System.EnterpriseServices, PublicKeyToken={1}",
...
Ideea construirii acestui string, se gaseste in algoritmul folosit pentru construirea identitatii
unui assembly
foreach (String a in assemblies)
{
String AssemblyIdentity =
String.Format(a, EcmaPublicKeyToken,
MSPublicKeyToken) +
", Culture=neutral, Version=" + version;
...
20
21.01.2007
Rezultatul este:
mark<br>
smith<br>
123 csharp drive<br>
toronto<br>
canada<br>
Descarcarea explicita a unui assembly: descarcarea unui AppDomain
CLR nu suporta abilitatea de a descarca un assembly. In loc de aceasta trebuie sa
descarcam un AppDomain ce are ca efect descarcarea tuturor assemblies din cadrul
acestuia.
Descarcarea unui AppDomain se face apeland metoda Unload, ce are drept parametru o
refrerinta la un AppDomain.
Important : Assembly care sunt incarcati intr-un AppDomain neutral nu pot fi descarcati
niciodata. Un AppDomain neutral este descarcat cand procesul se termina.
Exemplu de creare a unui AppDomain, transfer de date prin referinta in afara AppDomain.
using
using
using
class
{
System;
System.Reflection;
System.Threading;
App
static void Main()
Ioan Asiminoaei
21
21.01.2007
{
// Creaza un AppDomain nou.
AppDomain ad =
AppDomain.CreateDomain("MyNewAppDomain", null, null);
// Creaza un obiect MarshalByRef in noul AppDomain
MarshalByRefType mbrt = (MarshalByRefType)
ad.CreateInstanceAndUnwrap(
Assembly.GetCallingAssembly().FullName,
"MarshalByRefType");
// Apeleaza o metoda pe acest obiect.
// Proxy redirecteaza apelul catre alt AppDomain
mbrt.SomeMethod(Thread.GetDomain().FriendlyName);
// Am terminat cu acest AppDomain.
// Il descarcam si implicit toate assemblies
// pe care le contine.
AppDomain.Unload(ad);
on
object
in
other
}
Console.ReadLine();
}
}
// Un tip derivat din MarshalByRefObject.
class MarshalByRefType : MarshalByRefObject
{
// Aceasta metoda de instanta poate fi apelata via proxy.
public void SomeMethod(String sourceAppDomain)
{
// Afisam numele AppDomain apelat si al AppDomain curent.
// Firul aplicatiei a facut tranzitia intre AppDomain.
Ioan Asiminoaei
22
21.01.2007
Console.WriteLine(
"Code from the {0} AppDomain\n" +
"called into the {1} AppDomain.",
sourceAppDomain, Thread.GetDomain().FriendlyName);
}
}
Iesirea este:
Code from the 'p7_appdomain.exe' AppDomain
called into the 'MyNewAppDomain' AppDomain.
Fail to call SomeMethod on object in other AppDomain.
This should happen.
System.Collections Namespace
The System.Collections namespace contains interfaces and classes that define
various collections of objects, such as lists, queues, bit arrays, hashtables and
dictionaries.
Namespace hierarchy
Classes
Class
Description
ArrayList
Implements the IList interface using an
array whose size is dynamically increased
as required.
BitArray
Manages a compact array of bit values,
which are represented as Booleans, where
true indicates that the bit is on (1) and
false indicates the bit is off (0).
CaseInsensitiveComparer
Compares two objects for equivalence,
ignoring the case of strings.
CaseInsensitiveHashCodeProvider
Supplies a hash code for an object, using a
hashing algorithm that ignores the case of
strings.
CollectionBase
Provides the abstract (MustInherit in
Visual Basic) base class for a strongly
typed collection.
Comparer
Compares two objects for equivalence,
where string comparisons are casesensitive.
DictionaryBase
Provides the abstract (MustInherit in
Visual Basic) base class for a strongly
typed collection of key-and-value pairs.
Hashtable
Represents a collection of key-and-value
pairs that are organized based on the hash
code of the key.
Queue
Represents a first-in, first-out collection of
objects.
ReadOnlyCollectionBase
Provides the abstract (MustInherit in
Visual Basic) base class for a strongly
typed read-only collection.
SortedList
Represents a collection of key-and-value
pairs that are sorted by the keys and are
accessible by key and by index.
Ioan Asiminoaei
23
21.01.2007
Interfaces
Interface
ICollection
IComparer
IDictionary
IDictionaryEnumerator
IEnumerable
IEnumerator
IHashCodeProvider
IList
Description
Defines size, enumerators and
synchronization methods for all collections.
Exposes a method that compares two
objects.
Represents a collection of key-and-value
pairs.
Enumerates the elements of a dictionary.
Exposes the enumerator, which supports a
simple iteration over a collection.
Supports a simple iteration over a
collection.
Supplies a hash code for an object, using a
custom hash function.
Represents a collection of objects that can
be individually accessed by index.
Structures
Structure
DictionaryEntry
Ioan Asiminoaei
Description
Defines a dictionary key-and-value pair
that can be set or retrieved.
24