Assembly learning experience
Description:
I have recently been prepared to reintegrate the .NET knowledge learned, I am not as good as the hand, so I am prepared for my learning experience, I have already given a reference. J
Everyone is prawn, if there is any mistakes or incomplete places, please don't point out.
Thank you.
This article is divided into two parts:
The first part is some concepts that must be understood;
The second part is a complete example to explain these concepts one by one;
Part 1 Basic Concept
Managed Module
The hosting module is a standard Windows that can be implemented (PE) files that require CLR to perform (PE) files.
Metadata
Simply put, metadata is a collection of data tables, in which some of which are used to describe content defined in the hosting module (such as the defined type and members), and some other for description hosted The content referenced in the module (such as the type being referenced, and their members).
URL: MS-Help: //ms.msdnqtr.2004apr.1033/cpguide/html/cpconmetadataoverview.htm
Assembly list (askMBLY MANIFEST)
The assembly list is a collection of additional metadata tables. These tables describe the files that make up the assembly, the public export type implemented in all files, and some of the resource files or data files related to some assessments.
MS-Help: //ms.msdnqtr.2004apr.1033/cpguide/html/cpconassemblymanifest.htm
1. Concept of assembly (askMBLY):
First: The assembly is one or more hosting modules, as well as logical combinations of some resource files. Because it is a logical combination, the logical representation and physical representation of the assembly can be separated from each other. How to divide the code and resources to different files depending on us. For example, we can put some types or resources that are rarely used in a separate assembly module, and then download them from the Web as needed (for example, when used). If it is not used, they will not be downloaded. This saves disk space and reduces installation time. The assembly allows us to open the deployment of the file, and all the files will be regarded as a separate collection.
Second: Because the CLR is dealing with the disclosure of the assembly, the assembly is also a component multiplexing, and the minimum unit (security policy, version information, etc.) of the security policy and version policy can only be applied to the assembly).
Note: The assembly is a logical combination that contains many files. Most assemblies (such as those created using Visual Studio.net) are generally single file assemblies, that is, only one .exe or .dll file (current .NET's assembly only has these two formats). In this case, the program collection list is directly embedded in the single file program. However, you can also create multi-file assemblies with "Al.exe". You can also create only an assembly that contains only a list.
2. Concept of strong name assembly (strong name assembly)
Because different companies may develop assemblies with the same name, if these assemblies are copied to the same directory, the last installation assembly will replace the previous assembly. This is the reason for the famous Windows "DLL Hell".
Obviously, the simple use of file names is not enough, and the CLR needs to support a mechanism to uniquely identify an assembly. This is the so-called strong name assembly.
A strong named assembly contains four unique logo assemblies: file name (no extension), version number, language culture information (if any), public secret key.
This information is stored in the manifest of the assembly. The list contains metadata of the assembly and embedded in a file in the assembly.
The following string identifies four different assembly files:
"MyType, Version = 1.0.1.0, Culture = neutral, publickeyToken = BF5779AF662FC055"
"MyType, Version = 1.0.1.0, Culture = En-US, PUBLICKEYTOKEN = BF5779AF662FC055"
"Mytype, Version = 1.0.2.0, Culture = NetURL, PUBLICKEYTOKEN = BF5779AF662FC055"
"MyType, Version = 1.0.2.0, Culture = neutral, publickeyToken = DBE4120289F9FD8A"
If a company wants to identify its assembly, it must first get a public key / private key pair, and then associate a common key and assembly. There are no two two companies have the same public key / private key pair, which is this distinction allows us to create an assembly with the same name, version, and language cultural information without causing any conflicts.
The so-called weak naming assembly is called with a strong naming assembly. (It is actually ordinary unnamed assembly). Two program sets are structurally identical. All use the same PE file format, PE header, CLR header, metadata, and manifest. The true difference between the two is that the strong naming assembly has a publisher's public key / private key pair signature, where the public key / private key is unique to identify the publisher of the assembly. With public key / private key pairs, we can uniquely identify the assembly, implement security policies and version control policies, this unique identity assembly capability makes the application when trying to bind a strong named assembly, CLR can Implement some "confirmed security" strategy (such as only trust a company's assembly).
3. How to create a strong naming assembly (Strong name assembly)
Creating a strong named assembly first requires a key generated with a strong named utility (SN.EXE, the Sn.exe, .NET SDK comes with the Sn.exe, .NET SDK.
The following is a brief introduction to some of the usage of sn.exe.
To generate a public key / private key pair:
a) Sn -k mycompany.keys
This name tells Sn.exe to create a file named mycompany.keys. Mycompany.keys file will contain public keys and private keys stored in binary formats.
b) View public key:
First, it is generated into a file containing only public keys:
Sn -p mycompany.keys mycompany.publicKey
Then use the -tp parameters View: sn -tp mycompany.publicKeys
Public Key IS
0024000000000020000200002404800002000000248800525341310004000001000100BB7214723FFC13
901343df4b9c464ebf7ef4312b0ae4d31db04a99673e8163768cc0a2a7062e731dbeb83b869f0509bf8009e90db5c8728e840e782d2cf928dae35c2578ec55f0d11665a30b37f8636c08789976d8
EE9FE9A5C4A0435F0821738E51D6BDD6E6711A5ACB620018658CCE93DF37D7E85F9A0104A58450
53995CE8
Public Key token IS 2DC940D5439468C2
It is easy to create a public key / private key pair, and create a strong naming assembly is easy. Just add the system.reflection.assemblyKeyFileAttribute feature to the source code: [Assembly: askEMBLYKEYFILE ("MyCompany.Keys")]
Explanation: Public key / private key pairs of files can be arbitrary (or not) because it is read in the format of metadata when compiling.
4. Deployment of the assembly
There are two ways to deploy:
a) private way
And the app deployment assembly in the same directory is called a private deployment assembly. Weak naming assembly can only be privately deployed.
b) Global way
The overall deployment method deploys the assembly in some CLRs that have been known. When the CLR search assembly, it will know that these places are looking for. Strong naming assembly can either private deployment or global deployment.
Program set type
Can you perform private deployment?
Can I make a global deployment?
Ordinary assembly
Yes
no
Strong naming assembly
Yes
Yes
5. How to deploy strong name assembly and GAC
a) concept of gac
If an assembly is to be accessed by multiple applications, then he must put in a directory that CLR has been known, and the CLR is probably a reference to the ASSEMBLY, it must automatically find this program in this directory. set. This confident directory is called GAC (GLOBAL Assembly Cache), which is a global assembly cache. It is generally located in the directory below:
: / Windows / askEMBLY / GAC
.
The role of the GAC is to provide the CLR a known identified directory to find the quoted assembly.
b) internal structure of GAC
GAC is a special structured directory that browsing with Windows Explorer you think is just a general directory that contains many assemblies. Actually, not this, check it out on the command, you will actually contain a lot of subdirectories, the name of the subdirectories and the name of the assembly, but they are not actual assemblies, the actual assembly is in the program The collection name corresponds to the directory. For example, enter the GCFWK subdirectory, we will find that there are many subdirectories.
GCFWK.DLL installed to the GAC in the machine has a subdirectory in GCFWK. There is only one directory here that only one version of the GCFWK assembly is installed. The actual assembly saves in each corresponding version directory. The name of the directory is divided into "(discure)".
The language culture information of GCFWK is NetTure, which is expressed as 1.0.0.0_bf5779af662fc055. "
It is indicated that it is:
"GCFWK, VERSION = 1.0.0.0, Culture = neutral, publickeytoken = bf5779af662fc055"
If the language culture information is "ja", it is expressed as "1.0.0.0_ja_bf5779af662fc055"
It is indicated that it is:
"GCFWK, Version = 1.0.0.0, Culture = JA, PUBLICKEYTOKEN = BF5779AF662FC055"?
c) Deploy strong named assembly to GAC
The GAC contains a lot of subdirectories, which are generated by an algorithm. We'd better copy the assembly to the GAC. Instead, we should use tools to do this. Because these tools know the internal structure of the GAC J
In development and testing, the most commonly used tools are Gacutil.exe.
The registration assembly in the GAC is similar to the COM registration, but it is more easier:
1. Add the assembly to the GAC: Gacutil / I Sample.dll (parameter / i is the meaning of installation)
2. Move the program set out of the GAC
Gacutil / u Sample.dll (parameter / U will be removed)
Note: You cannot install a weak naming assembly to the GAC.
If you try to add a weak naming assembly to the GAC, you will receive an error message: "Failure adding assembly to the cache: Attempt to install an assembly without a strong name"
d) Private deployment of strong naming assembly
There are several benefits to install the assembly to the GAC. First, the GAC makes many programs to share the assembly, which reduces the physical memory used in the whole; secondly, we can easily deploy a new version of the assembly to the GAC, and through a publisher policy (almost a kind Redirection method, such as a program that will be retrieved from version 1.0.0.0, by changing its profile, turn the program to reference version 2.0.0.0.0.0.0.0.0.0.0.2.0.0. The new version is used. Finally, the GAC also provides Side-by-side management method for different versions of the assembly. However, the GAC's security policy usually only allows administrator changes, at the same time, the installation assembly in the GAC also destroys the simple copy deployment of the .NET framework.
In addition to deploying a strong naming assembly to the GAC or in a private deployment, we can also deploy a strong named assembly in a certain directory known for a small part of the program. Configure each application's XML configuration file to point to a public directory, so that when running, the CLR will know where to find this strong named assembly. However, this is also possible to trigger the "DLL Hell" problem, because no program can control when this assembly is uninstalled. This is also not encouraged in .NET.
6. Parallel Execution (Side - by - Side)
Here is an example of a strong named assembly:
First, there is an app.exe assembly that binds this version of the Calculus.dll assembly with 2.0.0.0 and an additional version of the AdvMath.dll assembly for 3.0.0.0. The AdvMath.dll assembly also binds an assembly for Calculus.dll with 1.0.0.0. As shown below:
An Application That Requires Different Versions of The Calculus.dll Assembly
The CLR can load the same address space as the same address space as the name, but the path is different, which is called the Side-by-Side execution in .NET, it is the key to solving the "dll hole" problem in Windows. technology.
If the .NET Framework 1.0 and .Net Framework 1.1 can be run on a machine, this is to perform the Side-by-Side execution.
More reference: ms-help: //ms.msdnqtr.2004apr.1033/cpguide/html/cpconside-cy-sideexecutiontop.htm
Http://www.microsoft.com/china/msdn/archives/library/dnnetdep/html/sidexsideNet.asp
7. How CLR is resolved type reference
CLR When parsing a reference type, it can find this type in one of the three places:
· The same file
Access to the type of type in the same file has been determined when compiling, CRL loads the referenced type directly from the file. After the load is complete, the program will continue to run.
· Different files, the same assembly
CLR first ensures that the referenced file is in the FileDef table in the current assembly list. The CLR then finds the referenced files in the directory of the load assembly manifest file. While this file is loaded, the CLR checks its hash value to ensure the integrity of the file, and then find the corresponding type member. After the load is complete, the program will continue to run.
· Different files, different assemblies
When the referenced assembly is in a different assembly file, the CLR will first load the files that contain the list of the referenced assembly. If the file does not contain the type you want, the CLR will load the appropriate file based on this manifold. This will also find the corresponding type of member. After the load is complete, the program will continue to run.
If any errors occur during the parsing type reference, such as files cannot be loaded, the file cannot be loaded, the hash value does not match, etc., the system will throw the corresponding exception.
The following figure demonstrates the type of binding process:
?
Program set type
Can I reference a weak naming assembly?
Can I refer to a strong named assembly?
Ordinary assembly
Yes
Yes
Strong naming assembly
no
Yes
Second part instance
Below is a complete example to explain the concepts mentioned above one by one to deepen understanding.
The entire instance contains 7 files (under the home directory):
The home directory is ... / askEMBLY ---- Source program directory
... / askEMBLY / BIN ---- Directory for compiling results, that is, the application owner directory.
file name
Types of
Description
App.cs
CODE source file
Main program, including program entrance, belonging to Namespace1
Classa.cs
CODE source file
Type A, including a static method, belonging to Namespace1
Classb.cs
CODE source file
Type B, contain a static method, belonging to Namespace2
AskEMBLYINFO.CS
CODE source file
Contains program set signature information, version information, etc.
App.key
Public key / private key pair file
Used to sign the assembly, generate a strong named assembly
App.PublicKey
Only a common key
Only store a total key, view with sn.exe
App.exe.config
XML format profile
App.exe application profile
Source code
App.cs
Namespace name {
PUBLIC CLASS APP {
Static void
Main
(String [] args) {
System.console.writeline (Classa.Showme ());
System.console.writeline (Namespaceb.classb.showme ());
}
}
}
Classa.cs
Namespace Namespacea
{
Public class classa {
Public static string showme () {
Return "this is classa";
}
}
}
Classb.cs
Namespace namespaceb {
Public class classb {
Public static string showme () {
Return "this is classb";
}
}
}
AskEMBLYINFO.CS
// module: askEMBLYINFO.CS
Using system.reflection;
// set companyName, Legalcopyright, And Legaltrademarks
[Assembly: AssemblyCompany]]]]
[Assembly: AssemblyCopyright ("Copyright (C) 2004 @ App Company")]
[Assembly: AssemblyTrademark ("App IS A Test Only Program)]]]]
// set Productname and ProductVersion
[Assembly: AssemblyProduct ("App Product")]]]
[Assembly: AssemblyInformationalvelvelion ("1.0.0.0")]]
// set fileversion and askEMBLYVERSION
[Assembly: assemblyfileversion ("1.0.0.0")]]]]
[Assembly: askMBLYVERSION ("1.0.0.0")]]]]
[Assembly: AssemblyTitle ("App Type assembly"]]]]
[Assembly: AssemblyDescription ("App Aassembly Is A Test Only Assembly"]]
// set culture
[assmbly: assemblyculture ("")]
[assmbly: askEDELAYSIGN (FALSE)]
[assmbly: assemblykeyKeyfile ("app.key")]]
[assmbly: assemblykeykeyname ("")]
App.key and app.publicKey are binary formats stored, and they cannot be viewed directly. The rear example is used.
1. Compile the source code as a managed module (Managed Module)
CSC /OUT :BIN/CLASSA.MODULE / T: Module Classa.cs
Parameters: / OUT: Output path
/ T: Output format. There are four kinds, namely:
LIBRARY ---- DLL assembly
EXE ---- Console executable program (also one of the assembly)
Winexe ---- Windows executable (same is also one of the assembly)
Module ---- Managed Module (part of the assembly)
Description:
The extension of the hosted module can be arbitrary (or not) because it is read in the format of metadata when compiling.
2. Compile the source code as an assembly (askSEMBLY)
l Compile ClassB into a single file assembly
CSC /OUT :BIN/Classb.dll / T: library classb.cs
l Compile App.cs, Classa.Module and Classb.dll into a multi-file assembly
CSC /OUT: BIN /APP.EXE / T: EXE App.cs /addmodule :bin/classa.module /r :bin/classb.dll
Parameters: / addModule: Add the managed module to the program center
/ R: Add reference
Description:
The assembly produced above is because there is no public key / private signature, so generated a set of non-strong naming types.
Generated assembly app.exe only contains only descriptions of the Classa.Module managed module without including metadata of Classa.Module, so app.exe and classa.moudle must be in the same directory. App.EXE is running, if you use a reference to classa.module, you will go to the classa.moudel file, if the classa.moude file does not exist, system.io.filenotFoundException is raised. If App.exe does not use the type in class.module, the classa.module does not have any effect on App.EXE execution (this is one of the benefits of Assembly mentioned above, asmblembly is just one Logical combination).
App.EXE also uses a reference to classb.dll because classb.dll is not a strong named type, so it can only be privately deployed, can be placed together with app.exe, or other sub-listings Under contents. (Change the configuration file later, you can redirect a reference to Classb.dll).
3. Change the application configuration file (app.exe.config), redirect the reference to Classb.dll.
Now app.exe, classa.moudle and classb.dll are in the bin directory, app.exe will find all the types they need at runtime, so running is normal.
If you create a directory in a bin directory, such as Sub, move the classb.dll to the SUB directory, then run app.exe. It also triggers the System.IO.FilenotFoundException error, because the Classb type required when App.exe is running. At this time, you need to change the addition (if not) or change the application profile, the application profile is a configuration file in an XML format, and the tool of the web.config file is similar, which is the behavior of the configured application runtime.
Note: The name of the configuration file must be an application name and add one .config, and must be under the same directory
Details Reference:
MS-help: //ms.msdnqtr.2004apr.1033/cpguide/html/cpConnetApplicationConfigurationsCenarios.htm
App.EXE.CONFIG file content:
XML Version = "1.0" encoding = "UTF-8"?>
>
<
Runtime>
>
When app.exe runs, it will find classb.dll in the Sub directory under the home directory and continue execution.
Description:
When the CLR needs to locate an assembly, it will scan several subdirectors of the application, the following is the order in which the CLR scans a program set: ... / assembly / bin / classb.dll.
... / askEMBLY / BIN / Classb / Classb.dll.
... / askEMBLY / BIN / SUB / CLASSB.DLL.
... / askEMBLY / BIN / SUB / Classb / Classb.dll.
... / askEMBLY / BIN / Classb.exe.
... / askEMBLY / BIN / Classb / Classb.exe.
... / assembly / bin / sub / classb.exe.
... / askEMBLY / BIN / SUB / CLASSB / CLASSB.EXE.
note:
If the app.exe reference is a strong named assembly, the CLR will first look for in the GAC and then look up in the order above.
4. Create and view public key / private key pairs
Creating a public key / private key pair file can be created with the Tool (sn.exe) of the .NET SDK.
First, create a public key / private key pair file
Sn -k app.key
Then, create a file containing only a common key with this file:
Sn -p app.key app.publicKey
Then view the -tp parameters
Sn -tp app.publicKey
5 Create a strong named assembly
With the public key / private key pair, it is easy to create a strong naming assembly. Just need to add the System.Reflection.assemblyKeyFileAttribute feature to the source code.
[assmbly: assemblykeyKeyfile ("app.key")]]
Generally added to the assemblyinfo.cs file.
Now re-build classb.cs, get a strongly named assembly:
CSC /OUT :BIN/CLASSB.DLL / T: library classb.cs assemblyinfo.cs
View ILDASM.EXE, you will find that the public key in Assembly will have a large string value, this is the public key of the assembly, which guarantees the uniqueness of the order set.
?
6. Add a strongly named assembly Classb.dll to the GAC.
Use tools Gacutil.exe
Add Classb.dll to the GAC:
Gacutil / i classb.dll
Delete Classb.dll and re-build app.exe:
CSC /OUT: BIN/APP.EXE / T: EXE App.cs /addmodule :bin/classa.module /R: Classb.dll
App.exe is running correctly, indicating that Classb.dll has successfully added to the GAC and becomes a shared assembly.
The rules of the assemblies are referenced by each other:
Program set type
Can I reference a weak naming assembly?
Can I refer to a strong named assembly?
Ordinary assembly
Yes
Yes
Strong naming assembly
no
Yes
Move the classb.dll from the GAC:
Gacutil / U Classb
note:
You cannot specify an extension when you move out (because each assembly in the GAC is a directory, not the actual assembly).
If Classb.dll is not a strong named assembly, and you want to make App.EXE Build as a strong name, it will be wrong:
Error CS1577: Assembly Generation Failed - Reference Assembly 'Classb' Does ??????? NOT HAVE A STRONG NAME
you may try it. J
7. Examples of Side-by-Side
http://www.microsoft.com/china/msdn/archives/library/dnnetdep/html/sidexsideNet.asp Reference:
l Applied Microsoft .NET Framework Programming ---- Jeffrey Richter
l Msnd Library