C # Study Notes-the first application

Source: Internet
Author: User

Directory

One application-Programming System product

Second, the first. Net Program

Three Assembly

I. ApplicationProgram-- Programming System products

What is an application? Simply put, it is a programming system product. I like the evolution of programming products described in The Mythical man-month. Let's take a look at what we are developing.

ProgramProgram isCodeThe most direct product is complete and can be run in our development environment. The most common is executable files. What we get most easily is the program. For us, the program is only the first step of development. It only indicates that our code can run, but it is not our goal, we also need to further upgrade our results.

Programming ProductsProgramming products promote programs to stable running on different platforms and provide general programming products with certain functions for users. We can write relevant documents and provide technical support through strict testing and continuous improvement of programs to convert our programs into programming products. An example of a programming product is the serial port debugging tool.

Programming SystemA program can also be converted into a component unit in a programming system. It complies with certain specifications and works with other programs to form a system. The company's internal framework can be seen as a programming system.

Programming System productsThis is the form of program evolution, and it is the sublimation of the Programming System to the product level. Such as Word and other commercial software. This is the goal of most of our software projects and the value of software products.

We must be clear that software development is not a personal task. It is difficult for us to upgrade our programs to the product level by ourselves, so most of our programmers are still producing programs, that is, a component unit of the programming system. (That's why we have low salaries .)

Second, the first. Net Program

We can use NotePad to develop C # programs, but generally no one is doing this. Remember this name as "Visual Studio". This powerful ide makes countless peers (non-development.. Net Program. VS is too powerful. Combining vs with Microsoft's TFs can quickly help an enterprise meet the cmmi3 standard. Vs will be our development tool. We can also install various plug-ins to enhance the tools in our hands. (Vs functions are comprehensive, so I won'tArticleThe usage is described in. Please learn it by yourself .)

The first. Net Program "Hello World ":

UsingSystem;

NamespaceClrtest
{
ClassProgram
{
Static VoidMain (String[] ARGs)
{
Console. writeline ("Hello world.");
Console. readkey ();
}
}
}

(1) reference an assembly

When using vs to create a project, you must first select. net Framework Version, later version.. NET Framework supports more development templates, updated C # syntaxes, and advanced FCL libraries. Although the later version. net Framework provides more powerful functions for us, but it also requires the running environment of the program, which may increase the operating costs of the system. Therefore, we need to make a trade-off based on the actual situation, the latest is not necessarily the most reasonable.

After selecting a development template, Vs will automatically reference the corresponding assembly for us and create some structured files to reduce our workload. To use other assemblies, we also need to manually add references in.

In addition to adding references to an assembly during development, you can also dynamically load and create an assembly during runtime. It is a relatively advanced method to dynamically load and create an assembly. It will be described in future articles and will not be described here.

(2) namespace

To ensure that all types in the base class library can be well organized, the. NET platform puts forward the concept of namespace. A namespace is a group of related types in an assembly. Any language based on the. NET Runtime Library can use the same namespace and the same data type. In the above example,Namespace"Clrtest"Become type"Program"Conceptual containers, as long as the types are in the same namespace, we can think that they are conceptually grouped. Therefore, we can define two types with the same name, which are differentiated by namespaces.Note that the types contained in any nested Microsoft namespace are used to interact with services that only belong to the Microsoft operating system. These types cannot run on other operating systems.

We can neither use a namespace nor introduce a namespace. If the namespace is not explicitly declared, the defined type belongs to the default namespace, which is also called global, that is, the namespace where the system is located. If the namespace is not appealing, you can use a fully qualified name to avoid ambiguity. The IL code obtained by these two methods is the same and has no impact on the Assembly size and performance. In fact, in CLR code, the type is always defined by a fully qualified name.

You can create an alias for a namespace. The C # Using Keyword can be used to create aliases with fully qualified names and namespaces. For example, "using mynamespace = XXXX. yyyy. zzzz. some; ", we can directly use mynamespace to replace XXXX. yyyy. zzzz. some, especially for long namespaces. (The type alias is similar to that of the namespace)

General namespace naming rules: <Company Name>. (<Product Name> | <related technology> )[. <purpose>] [. <sub-namespace>] (Note: Do not use too general type names, causing unnecessary type name conflicts .)

In addition, C # provides a mechanism to resolve namespace naming conflicts by using the namespace alias qualifier (: :) and global identity. If we change the "Hello World" code to the following, it will cause ambiguity:

ClassProgram
{
Public ClassSystem {};

Static VoidMain (String[] ARGs)
{
System. Console. writeline ("Hello world.");
System. Console. readkey ();
}
}

The Global keyword used before the: Operator references the global namespace to solve ambiguity. For example:

Global: system. Console. writeline ("Hello world .");
Global: system. Console. readkey ();

Namespace nestingNamespaces can be nested in two ways:

(1) Hierarchical

 
NamespaceCity
{
NamespaceTown
{
...
}
}

(2) compact (in most cases, we use compact)

 
NamespaceCity. Town
{
...
}

(3) assemblyinfo. CS

Assemblyinfo. CS is automatically created by Vs to describe the general information of the Assembly, that is, the configuration assembly list. We can modify the content of assemblyinfo. CS through the "assembly information" dialog box in Vs, for example:

We will get the following code (note the differences between the two versions described in my comments ):

 Using System. reflection;
Using System. runtime. compilerservices;
Using System. runtime. interopservices;

// For general information about the assembly, use the following property set
// Control. You can modify these attribute values.
// Information associated with the Assembly.
// Title
[Assembly: assemblytitle ( " Test "title" " )]
// Remarks
[Assembly: assemblydescription ( " Test Description" " )]
// Configuration File
[Assembly: assemblyconfiguration ( "" )]
// Company
[Assembly: assemblycompany ( " Test "Company" " )]
// Product
[Assembly: assemblyproduct ( " Test "product" " )]
// Copyright
[Assembly: assemblycopyright ( " Test "Copyright" " )]
// Trademark
[Assembly: assemblytrademark ( " Test "Trademark" " )]
// Language and culture, which is very important to the auxiliary assembly
[Assembly: assemblyculture ( "" )]

// Set comvisible to false to make the type in this Assembly
// COM components are invisible. If you need to access the types in this Assembly from com,
// Set the comvisible attribute of this type to true.
[Assembly: comvisible ( False )]

// If this project is made public to com, the following GUID is used for the ID of the Type Library
[Assembly: GUID ( " C7ea708d-9c07-4b4d-b234-69db65bec2b7 " )]

// The Assembly version information consists of the following four values:
//
// Main version
// Next version
// Internal version number
// Revision No.
//
// You can specify all these values, or use the default values of "internal version number" and "revision number,
// Use "*" as follows:
// [Assembly: assemblyversion ("1. 0. *")]
// This version number is very important. It is the unique identifier of the assembly version, and it is stored in metadata.
[Assembly: assemblyversion ( " 1.2.333.4 " )]
// The version number for reference only is stored in Win32 resources. You can view it using Windows resource manager, but CLR does not use it.
[Assembly: assemblyfileversion ( " 4.3.222.1 " )]

The Assembly uses the language culture as part of its identity, so that the Assembly can be oriented only to one language. The language and culture are identified by a string that contains a primary tag and a secondary tag. For example, en (primary tag)-US (secondary tag) indicates American English. Generally, the Assembly that contains the specific code implementation does not specify the language culture, because the code implementation should not involve the language culture. An assembly without a specified language culture is called a language culture neutral.

The Assembly version number format is as follows:

The primary version number and the secondary version number constitute a public understanding of a single version and do not change frequently, but the last two versions are often changing. If no version is displayed, the Assembly is set to 0.0.0.0 by default.

    • Major, minor: The main version number and minor version number constitute a public understanding of a version. When an assembly is loaded, the CLR automatically finds the latest installed maintenance version that matches the major and minor versions of the requested assembly.
    • Build and revision: each time we generate an assembly, we need to increase the build number. The subsequent revision shows the current build revision. If we fix the bug two times, the revision number is 2. Build and Revision reflect the new and old maintenance versions.

We can obtain assembly information through programming, such as assembly. getexecutingassembly (). fullname, which can return information including class name, version, and public key.

For private assembly (the private assembly will be analyzed in detail below), the version issue is not important, because the referenced program assembly is replicated together with the main program, but the version corresponds to the software project management is very important. Version Control is part of project configuration management. Many projects do not deliberately maintain the version number during implementation. This is wrong. It is hard to imagine a project that does not even manage versions, how is configuration management performed. Although the code that can work better than the rich documentation is promoted today, readers are still expected to develop a habit of using version control in their own projects, so don't figure out the seeds of disaster at the moment.

(4) Application Object and executable program entry point main

It is impossible to create a full function or global data in C #. All its members and methods must be included in a type definition.

The program defines only one main () method class type. By default, Vs will name the class that defines main () as "program ". Each executable program must contain a class that defines main (). This method is used to indicate the entry point of the application. This class is called "Application Object ".

The main () method has the static keyword modifier (This allows C # To run programs without creating instance objects.). At the same time, you can accept the parameter and use void to return the value (INT can also be returned ). If the access modifier is not displayed, main () is implicitly private by default to ensure that other applications cannot directly call the entry point of another application.

Most programs use void as the return value of main (). In fact, 0 is implicitly returned as the error code. 0 indicates that the program ends, and other values indicate that an error occurs. This value is passed to the system at the end of the program and saved in "% errorlevel %" (environment variable). You can use the system. Diagnostics. process. exitcode attribute to get the value of % errorlevel %.

(5) debugging and release

Debug in vs is set to/optimize-And/debug: full by default. The generated program set is the debug version. The generated il code and the final Local Code are not optimized, in addition to the main file, it also includes debugging information (*. PDB, the file records debugging information such as breakpoints in the Code); release is set to/optimize + and/debug: pdbonly by default, does not contain debugging information, the generated il code and the final local code will be optimized. In the end, we need a program of the "release" version.

(6) deployment and Configuration

You can use vs or other packaging software to package programs as installation files, but the simplest way to package an assembly is to copy all the files directly (a simple application developed by myself is to make the Assembly a "self-extracting" file-without installing the green version ). When you detach an assembly, delete the file. This simple installation, movement, and uninstallation can be implemented because each Assembly uses metadata to indicate the self-referenced assembly and does not need to rely on registry settings.

Most. NET applications have configuration files by default. The configuration file contains XML Code, and its nodes are associated with an application.

    • The Configuration File Name of the executable program is: “xxx.exe. config ".
    • The Configuration File Name of the Web application is "Web. config ".

Configuration can be divided into the following categories:

    • Startup settings, used to specify the version of the Runtime Library.
    • Runtime settings are used to specify how the runtime collects garbage, if the Assembly is bound.
    • Special Application configurations, such as WCF, database connection, and log4net.
    • Security Settings.
    • Custom configuration section.

The configuration will be affected by three configuration files:

(1) The application configuration file (the one described above) is in the directory where the executable program is located.

(2) apply the full system configuration in the machine configuration file. In the config directory of the installation path, it is called "machine. config ". Do not modify it easily. Once this file is set incorrectly, it may cause the. NET platform to crash.

(3) Publish the policy file (described later) to specify that the shared assembly can be compatible with the old version and stored in GAC.

In addition, you can customize the configuration file through the code. For large projects, custom configuration files are flexible. For small projects, the default configuration file is enough.

(In configuration management, we pay close attention to the parameter settings in the configuration file and must form a set of standard configuration management procedures .)

Three Assembly

An assembly, simply put, is a CLR-based, versioned, and self-described binary file. A. NET application can be assembled by multiple assemblies. An assembly has the following advantages:

    • Assembly promotes code reuseWhen we need to split a single executable file into multiple. Net datasets, We can reuse language-independent code.
    • Assembly determining Type BoundaryThe fully qualified name of the type consists of the namespace and the type name. Strictly speaking, this type identity also needs to add the assembly of the type. The two assembly types defined in the same namespace are considered to be different.
    • An assembly is a versionable unit.The version number and the optional public key value allow different versions of the assembly to coexist on the same machine without conflict.
    • The Assembly is self-described.The Assembly records the information required for normal operation.
    • The Assembly is configurable.You can deploy an assembly in a "private" or "shared" manner. You can write configuration files.

An assembly is divided into a dll library assembly and an EXE application assembly. Their boundaries are very vague. What you can do with a dll library assembly can also be done with an EXE application assembly. However, the opposite is not true, for example:

    • You can directly run the application assembly, but cannot start a class library.
    • Only the application set that starts the process has the right to speak about which CLR version to use.

(1) Composition of the Assembly

An assembly consists of the following parts:

    • Pe32 (pe32 +) Header
    • CLR Header
    • Assembly List
    • Metadata
    • Il
    • Resources

1 pe32 (pe32 +) header,CLR header,Assembly List

Pe32 (pe32 +) HeaderThe pe32 (pe32 +) header enables the Assembly to be loaded and operated by the OS. It identifies the type of the application (console, Gui, *. dll) that will reside in the OS.

CLR HeaderThe CLR header defines multiple tags so that the CLR can understand the layout of hosted files.

Assembly ListA list is a collection of metadata tables. It describes the Assembly itself and provides logical attributes shared by all modules and components in the Assembly. A list consists of the following parts:

    • Identifier (name, version, culture, public key)
    • A list of files belonging to this Assembly
    • List of referenced assembly
    • A set of license requests (the license required to run this Assembly)
    • Type (if a group of types are defined in a module, the module will be referenced in the Assembly, and the list will contain them; otherwise, they will not be included)

Each list contains a password hash for different modules in the Assembly. when the Assembly is loaded ,.. Net re-calculates the password hash of this module during runtime. If it is different from the password hash in the list, the Assembly will be refused to be loaded and an exception will be thrown. At the same time,The list is also a method in which. Net collects information about other referenced sets. Configuration information is particularly important to ensure version compatibility and interaction between assemblies.

Use ildasm to open the hello word assembly and view the detailed information of the Configuration:

. Assembly externBlock, which consists of. publickeytoken and. Ver .. Publickeytoken information is used only when the Assembly is set to a strong name .. Ver indicates a digital version ID

. AssemblyMark the friendly name (clrtest) used to identify the assembly ).

. CustomIdentifies the Assembly feature, that is, the company name and other information we set above.

. ModuleThe name of the module.

. VerIndicates the assembly version number. The version number is assemblyversion rather than assemblyfileversion.

2 metadata

Metadata is a binary data block consisting of several tables. These tables are divided into three categories: Definition table, reference table, and list table (a set of metadata, contains the names of some files in the Assembly, and also describes the assembly version, language, publisher, co-occurrence type, and all files required by the Program ). Common Metadata tables and relationships are as follows:

Use ildasm to view the metadata of the hello World Program as follows:

. Net uses metadata to remotely call and send messages across execution boundaries. Metadata is an accurate and formal description of object types and programs.

3 IL, resources

IlUse ildasm to view the main method Il of the hello World Program as follows:

ResourcesAn assembly can be embedded with resources, labels, images, string tables, and so on. (. NET refers to an assembly that only contains resources specific to the language and culture and does not contain any code implementation. These Assembly sets provide support for "localization. When looking for a subsidiary assembly, CLR ignores the version number and only uses language and cultural information .)

(2)Generate assembly

Among all the files in the Assembly, there must be a file that contains the list. CLR always loads the file containing the "list" metadata table first, and obtains the names of other files in the Assembly based on the "list. Type must be placed in a module as part of the Assembly for smooth packaging, version control, security protection, and use.To generate an assembly, You must select your own PE file as the inventory host, and all files in the Assembly must exist. Then, you can use the compiler csc.exe or the connector al.exe to create an assembly.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.