Что такое assembly manifest
Сборки имеют следующие составляющие:
Манифест, который содержит метаданные сборки
Метаданные типов. Используя эти метаданные, сборка определяет местоположение типов в файле приложения, а также места размещения их в памяти
Собственно код приложения на языке MSIL, в который компилируется код C#
Все эти компоненты могут находиться в одном файле, и тогда сборка представляет один единственный файл в формате exe или dll.
Манифест сборки
Манифест хранит следующие данные:
Номер версии : основной и дополнительный номера. Используется для управления версиями
Язык и региональные параметры : информация о языке и региональных параметрах, которые поддерживает сборка
Информация о строгом имени : открытый ключ издателя
Список всех файлов сборки : хэш и имя каждого из входящих в сборку файлов
Таким образом, манифест позволяет системе определить все файлы, входящие в сборку, сопоставить ссылки на типы, ресурсы, сборки с их файлами, управлять контролем версий.
Атрибуты сборки
По умолчанию Visual Studio при создании проекта добавляет файл AssemblyInfo.cs, который можно найти в узле Properties:
Это обычный файл на языке C# и в моем случае выглядит так:
Смысл этого файла состоит в том, что он задает настройки манифесту сборки. Через атрибуты типа [assembly: AssemblyVersion(«1.0.0.0»)] можно установить значения в манифесте. Префикс assembly: перед атрибутом указывает на то, что это атрибут уровня сборки, в данном случае атрибут номера версии сборки.
В принципе, исходя из названия, я думаю, предназначение многих атрибутов итак понятно:
AssemblyCompany : название компании
AssemblyConfiguration : конфигурация сборки (Retail или Debug)
AssemblyCopyright : авторское право на программу
AssemblyDefaultAlias : псевдоним по умолчанию, используемый при ссылке на данную сборку из других сборок
AssemblyDescription : краткое описание сборки
AssemblyProduct : информация о продукте
AssemblyTitle : название сборки как информационного продукта
AssemblyTrademark : сведения о торговой марке
AssemblyCulture : задает язык и региональные параметры, поддерживаемые сборкой (например, установка русской культуры: [assembly:AssemblyCultureAttribute(«ru»)] )
AssemblyInformationalVersion : полная версия сборки
AssemblyVersion : версия сборки
AssemblyFileVersion : номер версии файла Win32. По умолчанию совпадает с версией сборки.
Манифест сборки
Любая сборка, статическая или динамическая, содержит коллекцию данных с описанием того, как ее элементы связаны друг с другом. Эти метаданные содержатся в манифесте сборки. Манифест сборки содержит все метаданные, необходимые для задания требований сборки к версиям и удостоверения безопасности, а также все метаданные, необходимые для определения области действия сборки и разрешения ссылок на ресурсы и классы. Манифест сборки может храниться в PE-файле (EXE или DLL) с кодом MSIL или же в отдельном PE-файле, содержащем только данные манифеста.
На следующей иллюстрации показаны различные способы хранения манифеста сборки.
Для сборки с одним связанным файлом манифест включается в PE-файл, чтобы получить однофайловую сборку. Создать многофайловую сборку можно, включив в нее отдельный файл манифеста или же добавив манифест в один из PE-файлов сборки.
Манифест сборки предназначен для следующих задач:
перечисление файлов, составляющих сборку;
сопоставление ссылок на типы и ресурсы сборки с файлами, содержащими объявления и реализации этих типов и ресурсов;
перечисление других сборок, от которых зависит эта сборка;
обеспечение косвенного обращения пользователей сборки к подробностям ее реализации;
предоставление собственного описания сборки;
Содержание манифеста сборки
В следующей таблице показаны данные, содержащиеся в манифесте сборки. Первые четыре элемента — имя сборки, номер версии, язык и региональные параметры и данные строгого имени — составляют удостоверение сборки.
Сведения | Описание |
---|---|
Имя сборки | Текстовая строка, задающая имя сборки. |
Номер версии | Основной и дополнительный номера версии, номер редакции и номер построения. Среда CLR использует их для применения политики управления версиями. |
culture | Сведения о поддерживаемых сборкой языке или региональных параметрах. Эти сведения должны использоваться только для назначения сборки в качестве сопутствующей сборки, содержащей сведения о языке или региональных параметрах (сборка, содержащая сведения о языке и региональных параметрах, автоматически считается сопутствующей). |
Данные о строгом имени | Открытый ключ издателя, если для сборки задано строгое имя. |
Список всех файлов сборки | Хэш и имя каждого входящего в сборку файла. Обратите внимание, что все входящие в сборку файлы должны находиться в той же папке, что и файл с манифестом сборки. |
Сведения о ссылках на типы | Сведения, используемые средой выполнения для сопоставления ссылок на типы с файлами, содержащими их объявления и реализации. Это касается типов, которые экспортируются сборкой. |
Сведения о ссылках на сборки | Список других сборок, на которые имеются статические ссылки из данной сборки. Каждая ссылка включает в себя имя зависимой сборки, метаданные сборки (версию, язык и региональные параметры, операционную систему и т.д.) и открытый ключ, если у сборки есть строгое имя. |
С помощью задания атрибутов сборки в коде можно добавить или изменить некоторые данные в манифесте сборки. Можно изменить данные о версии и информационные атрибуты, включая сведения о товарном знаке, авторском праве, продукте, компании и информационной версии. Полный список атрибутов сборки см. в разделе Настройка атрибутов сборки.
Assembly manifest
Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly’s version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information.
The following illustration shows the different ways the manifest can be stored.
For an assembly with one associated file, the manifest is incorporated into the PE file to form a single-file assembly. You can create a multifile assembly with a standalone manifest file or with the manifest incorporated into one of the PE files in the assembly.
Each assembly’s manifest performs the following functions:
Enumerates the files that make up the assembly.
Governs how references to the assembly’s types and resources map to the files that contain their declarations and implementations.
Enumerates other assemblies on which the assembly depends.
Provides a level of indirection between consumers of the assembly and the assembly’s implementation details.
Renders the assembly self-describing.
Assembly manifest contents
The following table shows the information contained in the assembly manifest. The first four items: assembly name, version number, culture, and strong name information make up the assembly’s identity.
Information | Description |
---|---|
Assembly name | A text string specifying the assembly’s name. |
Version number | A major and minor version number, and a revision and build number. The common language runtime uses these numbers to enforce version policy. |
Culture | Information on the culture or language the assembly supports. This information should be used only to designate an assembly as a satellite assembly containing culture- or language-specific information. (An assembly with culture information is automatically assumed to be a satellite assembly.) |
Strong name information | The public key from the publisher if the assembly has been given a strong name. |
List of all files in the assembly | A hash of each file contained in the assembly and a file name. Note that all files that make up the assembly must be in the same directory as the file containing the assembly manifest. |
Type reference information | Information used by the runtime to map a type reference to the file that contains its declaration and implementation. This is used for types that are exported from the assembly. |
Information on referenced assemblies | A list of other assemblies that are statically referenced by the assembly. Each reference includes the dependent assembly’s name, assembly metadata (version, culture, operating system, and so on), and public key, if the assembly is strong named. |
You can add or change some information in the assembly manifest by using assembly attributes in your code. You can change version information and informational attributes, including Trademark, Copyright, Product, Company, and Informational Version. For a complete list of assembly attributes, see Set assembly attributes.
Assembly Manifest Класс
Определение
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Описывает манифест сборки Win32.
Комментарии
Это формат сериализации, не удаляйте и не переименовывайте закрытые поля.
Конструкторы
Инициализирует новый экземпляр класса AssemblyManifest.
Свойства
Задает удостоверение манифеста.
Имя сборки, передаваемое задаче создания манифеста
Задает набор сборок, на которые ссылается манифест.
Указывает текстовое описание манифеста.
Определяет ссылку на сборку, которая является точкой входа приложения.
Указывает набор внешних прокси-заглушек, на которые ссылается манифест, для изолированных приложений и объектов COM без регистрации.
Задает набор файлов, на которые ссылается манифест.
Входной поток, из которого был считан манифест. Используется ManifestWriter для воссоздания входных данных, которые не представлены в представлении объекта.
Указывает, является ли манифест частью развертывания на основе запуска, для чего требуется несколько отличий при создании и проверке манифеста.
Содержит коллекцию текущих предупреждений и сообщений об ошибках.
Указывает, работает ли манифест в режиме только для чтения или режиме чтения и записи. Если манифест используется только для чтения, установите для этого флага значение true. Если используется для записи нового манифеста, установите для этого флага значение false. Значение по умолчанию – false. Этот флаг предоставляет дополнительный контекст для генератора манифестов и влияет на то, как регистрируются некоторые сообщениях об ошибках.
Указывает расположение, где загружался или сохранялся манифест.
Получает или задает свойство, используемое для сериализации свойства AssemblyIdentity в XML-файл.
Получает или задает свойство, используемое для сериализации свойства AssemblyReferences в XML-файл.
Получает или задает свойство, используемое для сериализации свойства Description в XML-файл.
Получает или задает набор внешних прокси-заглушек, на которые ссылается манифест, для изолированных приложений и объектов COM без регистрации в формате XML.
Получает или задает свойство, используемое для сериализации свойства FileReferences в XML-файл.
Получает или задает свойство, используемое для сериализации схемы в XML-файл.
Методы
Определяет, равен ли указанный объект текущему объекту.
Служит хэш-функцией по умолчанию.
Возвращает объект Type для текущего экземпляра.
Создает неполную копию текущего объекта Object.
Находит все ссылки на заданные сборки и файлы, выполнив поиск в том же каталоге, в котором находится загруженный манифест, или в текущем каталоге. Расположение каждой сборки и файла, на которые указывают ссылки, требуется для вычисления хэша и разрешения идентификатора сборки. Все возникшие ошибки или предупреждения выводятся в коллекции OutputMessages.
Находит все указанные ссылки на сборки и файлы, выполняя поиск в заданных каталогах. Расположение каждой сборки и файла, на которые указывают ссылки, требуется для вычисления хэша и разрешения идентификатора сборки. Все возникшие ошибки или предупреждения выводятся в коллекции OutputMessages.
Возвращает имя манифеста.
Обновляет сведения о файлах для каждой сборки и файла, на которые имеется ссылка. Сведения о файле включают в себя вычисление хэша и размер файла для каждого используемого файла и сборки. Кроме того, удостоверение сборки получается для всех сборок, на которые имеются ссылки, с не указанным идентификатором сборки. Все возникшие ошибки или предупреждения выводятся в коллекции OutputMessages.
Обновляет Сведения о файле для каждой сборки и файла, на которые стоит ссылка, используя указанную версию целевой платформы
Выполняет различные проверки правильности этого манифеста. Все возникшие ошибки или предупреждения выводятся в коллекции OutputMessages.
Assembly Manifests
An assembly manifest is an XML file that describes a side-by-side assembly. Assembly manifests describe the names and versions of side-by-side assemblies, files, and resources of the assembly, as well as the dependence of the assembly on other side-by-side assemblies. Correct installation, activation, and execution of side-by-side assemblies requires that the assembly manifest always accompany an assembly on the system.
For a complete listing of the XML schema, see Manifest File Schema.
Assembly manifests have the following elements and attributes.
Element | Attributes | Required |
---|---|---|
assembly | Yes | |
manifestVersion | Yes | |
noInheritable | No | |
assemblyIdentity | Yes | |
type | Yes | |
name | Yes | |
language | No | |
processorArchitecture | No | |
version | Yes | |
publicKeyToken | No | |
dependency | No | |
dependentAssembly | No | |
file | No | |
name | Yes | |
hashalg | No | |
hash | No | |
comClass | No | |
description | No | |
clsid | Yes | |
threadingModel | No | |
tlbid | No | |
progid | No | |
miscStatus | No | |
miscStatusIcon | No | |
miscStatusContent | No | |
miscStatusDocPrint | No | |
miscStatusDocPrint | No | |
typelib | No | |
tlbid | Yes | |
version | Yes | |
helpdir | Yes | |
resourceid | No | |
flags | No | |
comInterfaceExternalProxyStub | No | |
iid | Yes | |
baseInterface | No | |
numMethods | No | |
name | No | |
tlbid | No | |
proxyStubClsid32 | No | |
comInterfaceProxyStub | No | |
iid | Yes | |
name | Yes | |
tlbid | No | |
baseInterface | No | |
numMethods | No | |
proxyStubClsid32 | No | |
threadingModel | No | |
windowClass | No | |
versioned | No |
File Location
Assembly manifests can be installed in three locations:
File Name Syntax
For example, an assembly manifest that refers to myassembly would use the following file name syntax. You can omit the field if the assembly manifest is being installed as a separate file or if the resource ID is 1.
Because of the way side-by-side searches for private assemblies, the following naming restrictions apply when packaging a DLL as a private assembly. A recommended way of doing this is to put the assembly manifest in the DLL as a resource. In this case, the resource ID must equal 1 and the name of the private assembly may be the same as the name of the DLL. For example, if the name of the DLL is Microsoft.Windows.mysample.dll, the value of the name attribute used in the assemblyIdentity element of the manifest may also be Microsoft.Windows.mysample. An alternate way is to put the assembly manifest in a separate file. In this case, the name of the assembly and its manifest must be different than the name of the DLL. For example, Microsoft.Windows.mysampleAsm, Microsoft.Windows.mysampleAsm.manifest, and Microsoft.Windows.Mysample.dll. For more information about how side-by-side searches for private assemblies, see Assembly Searching Sequence.
Elements
Names of elements and attributes are case-sensitive. The values of elements and attributes are case-insensitive, except for the value of the type attribute.
assembly
A container element. Its first subelement must be an assemblyIdentity or noInheritable element. The assembly manifest uniquely describes the side-by-side assembly identified by the assemblyIdentity. Required.
The assembly element must be in the namespace «urn:schemas-microsoft-com:asm.v1». Child elements of the assembly must also be in this namespace, by inheritance or by tagging.
The assembly element has the following attribute.
Attribute | Description |
---|---|
manifestVersion | The manifestVersion attribute must be set to 1.0. |
noInheritable
Include this element in an assembly manifest to indicate that the assembly manages the activation contexts and its objects. The noInheritable element must be a subelement of an assembly element. The assemblyIdentity element should come after any noInheritable element. The noInheritable element is required in the assembly manifest if the assembly is used by any application manifests that include the noInherit element. A noInheritable element in an application manifest has no effect. A noInheritable element has no child elements.
assemblyIdentity
Describes and uniquely identifies a side-by-side assembly.
As the first subelement of an assembly element, assemblyIdentity describes and uniquely identifies the side-by-side assembly that owns this assembly manifest. This is called the DEF-context assemblyIdentity of the assembly manifest.
As the first subelement of a dependentAssembly element, assemblyIdentity describes and uniquely identifies a side-by-side assembly that is used by the DEF-context assemblyIdentity. This is called a REF-context assemblyIdentity of the assembly manifest. The DEF-context assembly requires the REF-context assembly to work correctly. Note that every REF-context assemblyIdentity must exactly match a corresponding DEF-context assemblyIdentity in the referenced assembly’s own assembly manifest.
This element has no subelements. The assemblyIdentity element does have the following attributes.
Attribute | Description |
---|---|
type | Specifies the assembly type. The value must be win32 and in lower case. Required. |
name | Uniquely names the assembly. Use the following format for the assembly name: Organization.Division.Name. For example, Microsoft.Windows.mysampleAsm. Required. Note that in the case of a DLL packaged as a private assembly with a separate manifest file, the name of the assembly must be different than the name of the DLL and the manifest. |
language | Identifies the language of the assembly. Optional. If the assembly is language-specific, specify the DHTML language code. In the DEF-context assemblyIdentity of an assembly manifest intended for worldwide use (language neutral) omit the language attribute. In a REF-context assemblyIdentity of an assembly manifest intended for worldwide use (language neutral) set the value of language to «*». |
processorArchitecture | Specifies the processor. The valid values are x86 for 32-bit Windows and ia64 for 64-bit Windows. Optional. |
version | Specifies the assembly version. Use the four-part version format: mmmmm.nnnnn.ooooo.ppppp. Each of the parts separated by periods can be 0-65535 inclusive. For more information, see Assembly Versions. Required. |
publicKeyToken | A 16-character hexadecimal string representing the last 8 bytes of the SHA-1 hash of the public key under which the assembly is signed. The public key used to sign the catalog must be 2048 bits or greater. Required for shared side-by-side assemblies. |
dependency
A container element including at least one dependentAssembly. The first subelement must be a dependentAssembly element. A dependency has no attributes. Optional.
dependentAssembly
The first subelement must be an assemblyIdentity element that describes and uniquely identifies a side-by-side assembly that is used by the side-by-side assembly that owns this assembly manifest. Every dependentAssembly must be inside exactly one dependency. Optional.
file
Contains files used by a side-by-side assembly. Contains comClass, typelib, windowClass, comInterfaceProxyStub subelements. Optional.
The file element has the following attributes.
Attribute | Description |
---|---|
name | Name of the file, for example, Conctl32.dll. |
hashalg | Algorithm used to create a hash of the file. This value should be SHA1. |
hash | A hash of the file referred to by name. A hexadecimal string of length depending on the hash algorithm. |
comClass
A subelement of a file element. Optional.
The comClass element has the following attributes.
The comClass element can have
elements as children, which list the version dependent progids.
The following example shows a comClass element included in a file element.
If your COM class is an OCX class that requires the MiscStatus registry subkey to specify how to create and display an object, you can enable the object by duplicating this information in the assembly manifest. Specify the object’s characteristics by using the miscStatus, miscStatusIcon, miscStatusContent, miscStatusDocprint, and miscStatusThumbnail attributes of the comClass element. Set these attributes to a comma-separated list of attribute values from the following table. These attributes duplicate the information that would be provided by a DVASPECT enumeration. If a no value is found for miscStatusIcon, miscStatusContent, miscStatusDocprint, or miscStatusThumbnail, the default values specified in miscStatus is used. Use attribute values from the following table. These correspond to the bit flags of a OLEMISC enumeration.
Attribute Value | OLEMISC Constant |
---|---|
recomposeonresize | OLEMISC_RECOMPOSEONRESIZE |
onlyiconic | OLEMISC_ONLYICONIC |
insertnotreplace | OLEMISC_INSERTNOTREPLACE |
static | OLEMISC_STATIC |
cantlinkinside | OLEMISC_CANTLINKINSIDE |
canlinkbyole1 | OLEMISC_CANLINKBYOLE1 |
islinkobject | OLEMISC_ISLINKOBJECT |
insideout | OLEMISC_INSIDEOUT |
activatewhenvisible | OLEMISC_ACTIVATEWHENVISIBLE |
renderingisdeviceindependent | OLEMISC_RENDERINGISDEVICEINDEPENDENT |
invisibleatruntime | OLEMISC_INVISIBLEATRUNTIME |
alwaysrun | OLEMISC_ALWAYSRUN |
actslikebutton | OLEMISC_ACTSLIKEBUTTON |
actslikelabel | OLEMISC_ACTSLIKELABEL |
nouiactivate | OLEMISC_NOUIACTIVATE |
alignable | OLEMISC_ALIGNABLE |
simpleframe | OLEMISC_SIMPLEFRAME |
setclientsitefirst | OLEMISC_SETCLIENTSITEFIRST |
imemode | TOLEMISC_IMEMODE |
ignoreativatewhenvisible | OLEMISC_IGNOREACTIVATEWHENVISIBLE |
wantstomenumerge | OLEMISC_WANTSTOMENUMERGE |
supportsmultilevelundo | OLEMISC_SUPPORTSMULTILEVELUNDO |
typelib
A subelement of a file element. Optional.
The typelib element has the attributes shown in the following table.
Attribute | Description |
---|---|
tlbid | The unique ID of the type library. Required. |
version | The two-part version number of the type library. If only the minor version number increases, all the features of the previous type library are supported in a compatible way. If the major version number changes, code that compiled against the type library must be recompiled. The version number of the type library may differ from the version number of the application. Required. |
helpdir | The directory where the Help file for the types in the type library is located. If the application supports type libraries for multiple languages, the libraries may refer to different file names in the Help file directory. If no value, then specify «». Required. |
resourceid | The hexadecimal string representation of the locale identifier (LCID). It is one to four hexadecimal digits with no 0x prefix and no leading zeros. The LCID may have a neutral sublanguage identifier. For more information, see Locale Identifiers. Optional. |
flags | The string representation of the type library flags for this type library. Specifically, it should be one of «RESTRICTED», «CONTROL», «HIDDEN» and «HASDISKIMAGE». These are the values of the LIBFLAGS enumeration, and are the same flags specified in the uLibFlags parameter of the ICreateTypeLib::SetLibFlags method. Optional. |
The following example shows a typelib element included in a file element.
comInterfaceExternalProxyStub
The comInterfaceExternalProxyStub is a subelement of an assembly element and is used for automation interfaces. For example, IDispatch and its derived interfaces. Optional.
The default proxy-stub implementation is adequate for most automation interfaces, such as interfaces derived from IDispatch. The interface proxy stub, and all other external proxy-stub interface implementations, must be listed in the comInterfaceExternalProxyStub. The comInterfaceExternalProxyStub element has the attributes shown in the following table.
The following example shows a comInterfaceExternalProxyStub element.
comInterfaceProxyStub
A subelement of a file element. Optional.
If a file in the assembly implements a proxy stub, the corresponding file tag must include a comInterfaceProxyStub subelement having attributes that are identical to a comInterfaceProxyStub element. Marshaling interfaces between processes and threads may not work as expected if you omit some of the comInterfaceProxyStub dependencies for your component.
The comInterfaceProxyStub element has the following attributes.
windowclass
The name of a windows class that is to be versioned. The windowclass element has the following attribute.
Attribute | Description |
---|---|
versioned | This attribute controls whether or not the internal window class name used in registration contains the version of the assembly containing the window class. The value of this attribute can be «yes» or «no». The default is «yes». The value «no» should only be used if the same window class is defined by a side-by-side component and an equivalent non-side-by-side component and you wish to treat them as the same window class. Note that the usual rules about window class registration apply only the first component that registers the window class will be able to register it since it is not versioned. |
The following example shows a windowclass element included in a file element.
Example
The following is an example of an assembly manifest.