Interacting with .NET Framework Elements
❘
129
print ThisRef
# Access a specific assembly and display more information about it.
ThisRef = clr.References[2]
print ‘\nFull Name of System.Xml:’
print ThisRef.FullName
# Display the referenced assemblies.
print ‘\nReferenced Assemblies:’
for Reference in ThisRef.GetReferencedAssemblies():
print Reference.ToString()
# Display the assembly attributes.
print ‘\nAttributes:’
for AnAttribute in ThisRef.GetCustomAttributes(type(ThisRef)):
print AnAttribute.ToString()
# Pause after the debug session.
raw_input(‘Press any key to continue...’)
The code begins by importing
sys
and adding the .NET Framework 2.0 path to
sys.path
. Adding
just the path you need tends to reduce the risk of importing the wrong assembly. Even so, you want
to verify that you’re using the right assembly, especially when the code is running on another system.
The next step is to import
clr
. This module provides the features required to interact with the
assemblies. The next few lines of code import
System
and
System.Xml
so that you can see a
number of assemblies in IronPython. Notice that the
System.Xml
import requires use of the
clr.AddReference()
method.
At this point, the example obtains the list of loaded assemblies from the
clr.References
property
and displays them onscreen using a
for
loop. Figure 7-11 shows the list of assemblies for this example.
Notice that the first assembly is
mscorlib
, which always loads.
You can drill down into an assembly as far as you want. The example continues by working with
the
System.Xml
assembly. As a first step, the code displays the full name of the assembly. Using
string manipulation, you can obtain the assembly name, version, culture, and public key token.
When creating an installation program, you often need to know the list of referenced
assemblies. The next portion of application code shows how to perform this task using the
ThisRef
.GetReferencedAssemblies()
method. The output includes the same four pieces of information as
the assembly information, so you know precisely which assemblies to include with your application.
Some developers also want to know about attributes assigned to an assembly. The
ThisRef
.GetCustomAttributes(type(ThisRef))
method call obtains this information. You must provide
the type of the assembly you want to interact with. Notice that the example uses the Python
type()
function, rather than a .NET equivalent. In some situations, you mix .NET and Python code to
obtain a desired result. The code shows how to use a loop to obtain the list of attributes. Most
assemblies include a wealth of attributes (some inherited). A developer might need to know some of
these attributes, such as
System.Security.Permissions.SecurityPermissionAttribute
(which
provides security information about the assembly), to create a functional application.
548592c07.indd 129
2/25/10 9:44:29 AM
www.finebook.ir
Do'stlaringiz bilan baham: |