Use a C # 2.0 command line compiler
Release Date: 12/22/2004
| Update Date: 12/22/2004
Andrew W. Troelsen, Microsoft MVP
Intertech Training
Abstract: This paper analyzes the process of generating an application using a C # command line compiler csc.exe. At the same time, it will also introduce a lot of compiler options for C # 2.0, for example, extended / Reference flags and strong name support. After reading the contents of this article, you will be able to easily generate single file assemblies and multi-file assemblies in an unwitting environment.
Applicable to:
Microsoft Visual C # 2.0
Note This article assumes that you are familiar with the structure of C # programming languages and .NET Framework. Experience the feeling of using the command line tool will also prove very helpful.
Download the cscsample.msi file.
This page
SCSC.exe Bringing the C # Compile Option Overview Configure Environment Variable Command Line Basics Use Options for Specify Input and Control Output Compilation .NET Code Base Using C # Response File Use / Reference Reference External Interface Understanding C # 2.0 Reference Alias / addModule Generates Multi-File Sets Create a Windows Form App To Use the Resource Using the Resource Using / Define Defining Prereated Symbol CSC.exe's Debugging Central Option Miscellaneous Skinding
SCSC.exe brings to the fun
Almost no one will deny that the integrated development environment (Ide) (for example, Visual Studio 2005 and Visual C # Express 2005) can make multi-functionality that makes programming work fairly simple. However, in fact IDE does not usually provide access to all aspects of the underlying compiler. For example, Visual Studio 2005 does not support generating multi-file assemblies.
In addition, understand the process of compiling code in the command line, for users who have the following feature:
•
Preference to the simplest method of generating .NET Framework applications.
•
The secret of the method of the IDE handling the source code file is hoped.
•
It is desirable to use .NET to generate utilities, for example, NANT or MSBUILD.
•
There is no integrated development environment, for example, Visual Studio (but actually has free .NET Framework SDK).
•
Based on UNIX-based systems (in this system, the command line is a tool that must be used) uses .NET Framework, and wants to better understand MONO and / or Portable .NET ECMA compatible C # compiler.
•
Studying is currently not integrated into the alternative .NET programming language in Visual Studio.
•
Just want to expand their C # programming language knowledge.
If you belong to these users described above, then you will be faithful to your choice and continue to read it.
Back to top
C # Compiler Overview
C # compiler CSC.exe provides a large number of options for controlling the way .NET assembly. Standing on a higher level, the command line option belongs to one of the following eight categories (Table 1).
Table 1. Category of tags provided by CSC.exe
C # Compiler Category Defines Output files to control the format of the generated assembly, optional XML document files and strong name information. Enter the file to make the user can specify an option to enter an assembly of the file and reference. Resources are used to embed any necessary resources (eg, icons and string tables) to options in the program. The code generates these options to control the generation of debug symbols. Errors and warning control compilers handle source code error / warning. Language Enable / Disable C # Language Functions (for example, unsafe code) and definitions of conditional compilation symbols. Miscellaneous Options of this category allow you to specify a CSC.EXE response file. Advanced This category specifies some more deeply and often less important compiler options. Note The / INCREMENTAL flag existing in the C # compiler of 1.0 and 1.1 is now outdated.
During reading this article, you will learn about the core flags existing in each compiler category (the most important word is the core). For most developments, many advanced options for the C # compiler can be safely ignored. If you need more information about the CSC.exe feature that this article is not discussed, you can refer to the Microsoft Visual Studio 2005 document help system (only from the "Search" tab to search "csc.exe" and look at ).
Note The MSDN document will also help you because it describes how to set specific options for CSC.exe in the Visual Studio (if available).
Back to top
Configure environment variables
Before using any .NET SDK command line tool (including C # compiler), you need to configure the development of your computer to identify their existence. The easiest way is to use the Start | All Programs | Visual Studio 2005 | Visual Studio Tools menu option, start the pre-configured Visual Studio command prompt. This particular console can automatically initialize the necessary environment variable without having to perform any operation. (Visual Studio .NET 2003 users need to launch their own command prompts).
Note If you don't have Visual Studio, but already installed .NET Framework SDK, you can start the pre-configured command prompt from the Start | All Programs | Microsoft .NET Framework SDK 2.0 menu option.
If you want to use the .NET command line tool from any command, you need to manually update the computer's path variable. Practice is, right-click on the My Computer icon on the desktop and select the Properties menu option. From the dialog box that appears, click the Environment Variables button under the Advanced tab. From the dialog box that appears, add the following directory list in the end of the current PATH variable in the System variable list box (note that you must separate each entry with a semicolon):
C: /Windows/Microsoft.Net/framework/v2.0.40607
C: / Program Files / Microsoft Visual Studio 8 / SDK / V2.0 / BIN
Note The above list points to my current .NET 2.0 beta path. Your path may be slightly different due to the installation and versions of Visual Studio and / or .NET SDK, make sure to perform an integrity check.
After updating the PATH variable, close all dialogs and any Console window currently open to submit the settings. You should now be able to perform CSC.exe and other .Net tools from any command prompt. To test, enter the following command:
CSC -?
ILDASM -?
If you see a lot of information is displayed, then you can continue. Back to top
Command line basics
Users who have been able to work in the command line will not have any problems when using CSC.exe, so you can jump to the next section. However, if you use the number of command lines, let me explain some basic details for necessary preparations.
First, you can specify the option of CSC.exe using a backslash or a single underline. Second, additional spaces have additional spaces between / or - and subsequent markers are illegal. Therefore, "- Help" is completely correct, and "- Help" will not pass. In order to explain, let's use the HELP logo to check the complete command line options set:
CSC -help
CSC / HELP
If everything is normal, you should see all possible signs, as shown in Figure 1.
Figure 1. Help sign
Many options provide a shorthand representation to save you some types of time. Assuming that the HELP flag is to list the options for csc.exe as follows:
CSC -?
CSC /?
Many options require additional modifications, for example, directory paths and file names. This nature of the nature uses a colon to separate the logo with its modification. For example, the / reference option requires the name of the .NET assembly to include in the assembly list:
CSC /Reference: MYLIBRARY.DLL ...
Other marks are binary in nature because they or is enabled ( ) or disabled (-). The binary flag is always default as their disabled state, so you usually only need to use a plus mark. For example, you have to treat all compilation warnings as an error, you can enable the warnaserror flag:
CSC / Warnaserror ...
The order of the logo is irrelevant, but the collection of all the flags must be listed before specifying the input file collection. Also worth mentioning is that there is an additional space between modification and its associated data. For example, please use /reference: milylibrary.dll without using /renence: milylibrary.dll.
Back to top
Options for specifying input and control output
The first set of command line options we will analyze is used to specify the compiler input (Table 2) and the output result (Table 3). Note that the following table also marks the option specific to C # 2.0 and any discretion representation.
Table 2. Csc.exe's input-centered option
The input flag defines whether it is specific to C # 2.0? / Recurse Notifies Csc.exe Compile C # files in the subdirectory structure located in the project. This logo supports wildcard syntax. NO / REFERENCE (/ R) is used to specify an external assembly to be referenced in the current compilation. No, but 2.0 compiler provides an alias variant. / addModule is used to specify the module to be included in the multi-file program set. no
Table 3. Csc.exe's Output-centric option
The output flag defines whether it is specific to C # 2.0? / OUT Specifies the name of the assembly to generate. If this flag is omitted, the name of the output file is based on the name of the initial input file (for * .dll assembly) or defines the name of the class of the main () method (for the * .exe assembly). No / target (/ t) Specifies the file format of the assembly to be created. No / DOC is used to generate an XML document file. No / DelaySign enables you to generate an assembly using the delayed signature of the strong name. Yes / keyfile specifies the path to the * .snk file that is strongly named for the assembly. Yes / keyContainer specifies the name of the container containing the * .snk file. Yes / Platform specifies the CPU (X86, Itanium, X64 or Anycpu) that must be present in to carry assembly. The default is Anycpu. It is perhaps the most used input / output option is / target. This flag tells the compiler to create which type .NET program interested in generating which type .NET assembly is interested in using additional modifications (Table 4).
Table 4. Variation of Target logo
Target Modification Definition / Target: EXE Creates an assembly based on a console. This is the default option if the / target option is not specified. / Target: Winexe Creates an Execute assembly based on a Windows Form. Although you can use / target: EXE to create a Windows Form Application, but the console window will hidden in the background of the main form. / Target: library is used to generate the .NET code base (* .dll). / Target: Module creates a module that will become part of the multi-file assembly.
Back to top
Compile .NET Code Base
To illustrate the procedure of the input / output option using CSC.exe, we will create a strongly named Single Wills Set to define a class type named SimpleType. In order to display the role of the / DOC option, we will also generate an XML document file.
First, create a new folder called Mycsharpcode on the drive C. In this folder, create a subdirectory called MyCodelibrary. Enter the following code using the text editor you selected (NOTEPAD.exe is fully desirable) and saves the file as SimpleType.cs in the C: / Mycsharpcode / MyCodelibrary directory just created.
// SimpleType.cs
Using system;
Namespace mycodelibrary
{
///
/// Simple Utility Type.
/// summary>
Public Class SimpleType
{
///
///Print out select Environment Information
/// summary>
Public static void displayenvironment ()
{
Console.writeline ("Location of this Program: {0}",
Environment.currentdirectory;
Console.writeLine ("Name of Machine: {0}",
Environment.machinename);
Console.writeline ("OS of Machine: {0}",
Environment.osversion);
Console.writeLine ("Version of .Net: {0}",
Environment.Version;
}
}
}
Now open the command prompt, and use the CD (Change Directory) command to navigate to the location of the SimpleType.cs file (c: / mycsharpcode / mycodelibrary): cd mycsharpcode / mycodelibrary
or
CD C: / Mycsharpcode / MycoDelibrary
To compile the source code file as a single file assembly called MyCodelibrary.dll, specify the following command set:
CSC / T: library /out:mycodelibrary.dll simpleType.cs
At this point, you should have a new .NET code base in the application directory, as shown in Figure 2.
Figure 2. New .NET Code Base
When compiling multiple C # files in the command line, each file can be listed separately - if you want to compile the subset of the C # file contained in a single directory, this may be helpful. Suppose we have created another C # code file called asminfo.cs (saved in the same directory), which defines the following assembly level properties to describe our code base:
// asminfo.cs
Using system;
Using system.reflection;
// a few assembly level attributes.
[Assembly: askMBLYVERSION ("1.0.0.0")]]]]
[Assembly: AssemblyDescription ("Just An Example Library)]]]
[Assembly: AssemblyCompany ("Intertech Training"]]]
To compile simpleType.cs and asminfo.cs files, type:
CSC / T: library /out:mycodelibrary.dll simpletype.cs asminfo.cs
As you may want, CSC.EXE supports wildcard representation. Thus, to compile all the files in a single directory, please specify * .cs as input options:
CSC / T: library /out:mycodelibrary.dll * .cs
Use / recurse specifies subdirectory
When you create an application, you know you like to create a logical directory structure for your project. You can organize them by placing code files in a specific subdirectory (/ Core, / Asminfo, / Menusystem, etc.) instead of dump up to 25 files to a single directory named myApp. Although our current example contains only a few files, it is assumed that you put the asminfo.cs file in a new subdirectory called / asminfo (as shown in Figure 3).
Figure 3. New / asminfo subdirectory
To tell the C # compiler to compile all C # files located in the root directory and the asminfo subdirectory, use the / Recurse option:
CSC / T: library /out:mycodelibrary.dll / recurse: asminfo /doc:32.xml * .cs
Here, / Recurse has limited the name of a particular subdirectory. To specify multiple subdirectories, we can use wildcard syntax again. If we want to move the SimpleType.cs file to a new subdirectory called Core, we can use the following command to compile all C # files in all subdirectory:
CSC / T: library /out:mycodelibrary.dll /Recurse :*.cs
In either case, the output is the same.
Generating an XML Document file using / doc The SIMPLETYPE class is already equipped with a variety of XML elements. As you are likely to know, the C # compiler will use these code comments with three slash generations to generate an XML document file. To tell CSC.exe to create such a file, you must provide / doc option, and modify it with the name of the file you want to generate:
CSC / T: library /out:mycodelibrary.dll /Recurse :*.cs /doc:mydoc.xml
In the application directory, you should now see a new file called MyDoc.xml. If you open this file, you will find that your type is described in XML, as shown in Figure 5.
Figure 5. Type document in XML
Note If you want to know more information about the C # XML code annotation, see the article XML Comments Let You Build Documentation Directly from your Visual Studio .NET Source Files.
Use / keyfile to build a strong name
The last task of the current example is to assign a strong name for our assembly. Under. NET 1.1, create a strong named assembly to use the [AssemblyKeyFile] property. Although this is good, the C # 2.0 compiler now provides the / keyfile flag to specify the position of the strong name key file (* .snk).
Create a new folder named myKeyPair on the drive C, then use the command prompt to change to this directory. Next, create a new key pair named myKeyPair.snk using the sn.exe utility "K option.
Sn -k myKeypair.snk
To make a strong naming using CSC.exe, make the following command set:
CSC / T: library /out:mycodelibrary.dll /Recurse :*.cs /doc: ys:/mykeypair/mykeypair.snk
To verify that the assembly does have a strong name, use the security utility (Secutil.exe) and "SECUTIL.EXE) and" € "display Strong Name information:
SECUTIL /SMYCODELIBRARY.DLL
You should find that the public key value recorded in the assembly list is displayed as the output shown in FIG.
Figure 6. Output of the public key value
The C # 2.0 compiler does have some other signs (/ DelaySign and / KeyContainer) with a strong name (/ delaySign and / KeyContainer, you may want to study when idle. In particular, use the / delaySign option if you want to enable latency signatures.
Back to top
Use C # response files
Although it can experience its with the benefits of the benefits through the command line, no one can deny that the button will not cause the finger cramps and entry errors. In order to help reduce these two questions, the C # compiler supports the use of response files.
Note All command prompts allow you to use the UP and Down arrow keys to traverse the previous command.
The response file (which uses the * .RSP file extension in accordance with the agreement) contains all the options you wish to supply to CSC.exe. After creating this file, you can specify its name as the unique options for the C # compiler. For convenience of explanation, the following provides a response file that will be used to generate MyCodelibrary.dll (note that you can use the # symbol specified annotation).
# Mycodelibraryargs.RSP
#
# THESE ARE THE OPTIONS Used
# t compile mycodelibrary.dll
# Output target and name.
/t :luded/out:mycodelibrary.dll
# Location of C # files.
/Recurse:*.cs
# Give me an XML DOC.
/DOC: MYDOC.XML
# Give Me A Strong Name as Well.
/keyfile:c:/mykeypair/mykeypair.snk
After the file is given, you can use the @ option to specify mycodelibraryargs.RSP:
CSC @ mycodelibraryArgs.RSP
If you like, you can specify multiple responses:
CSC @ mycodelibraryargs.rsp @ moreargs.RSP @ EvenMoreArgs.RSP
Keep in mind that the response file is processed in the order encountered. Therefore, the settings in the previous file may be rewritten by the settings in future files.
Default response file and / noconfig option
Finally, remember that there is a default response file - CSC.RSP, which is automatically handled by CSC.exe during each compilation. If you analyze the file (it is in the same folder in the same folder), you will just find a set of columns that are often referenced (System.Windows.dll, System.Data.dll, etc. ).
You can specify / noconfig flags in your homewress:
CSC / NOCONFIG @ mycodelibraryargs.RSP
Note If you reference the assembly, it does not actually use it, it will not be listed in the assembly list. Therefore, don't worry about the code expansion, because they don't exist at all.
Back to top
Use / Reference reference external assemblies
At this point, we have created a single file code library with a strong name (and instructions) using the command line compiler. Now we need a client application to use it. Create a new folder called MyClient in C: / MyCsharpcode. In this folder, create a new C # code file (SimpleTyPeclient.cs) that calls the static simpleType.DisplayEnvironment () method from the entry point of the program:
// simpleTypeClient.cs
Using system;
// Namespace in mycodelibrary.dll
Using mycodelibrary;
Namespace MyClientApp
{
Public class myapp
{
Public static void main ()
{
SimpleType.DisplayEnvironment ();
Console.readline ();
}
}
}
Because our client application uses MyCodelibrary.dll, we need to use / Reference (or just use / r) options. This flag is flexible because you can specify the full path to the * DLL discussed, as shown below:
CSC / T: EXE /R: C: /MYCSHARPCODE /MYCODELIBRARY/MYCODELIBRARY.DLL * .CS
Alternatively, if the copy of the private assembly is in the same folder with the input file, only the assembly name is specified:
CSC / T: EXE /R: MYCODELIBRARY.DLL * .CS
Please note that I don't specify the / out option. This condition is given, CSC.exe creates a name based on our initial input file (SimpleTyPeclient.cs). In addition, the default behavior of known / target is to generate a console-based application, so / t: EXE parameters are optional. In any case, because MyCodelibrary.dll is a private assembly, you need to put a copy of the library into myclient directories. After you do this, you can perform the SimpleTyPeclient.exe application. Figure 7 shows possible test operation.
Figure 7. Possible test run output
Note Please recall this problem that you don't have to deploy a set of strong names to the Global Assembly Cache (GAC). In fact, because strong names have natural security aspects, the strong name is provided to each assembly (regardless of sharing or not) is a .NET optimal policy.
Quote Multiple external assemblies
If you want to reference a large number of assemblies in the command line, you can specify multiple / reference options. To illustrate this, assuming that our client application needs to use the type included in the library named newlib.dll:
CSC / T: EXE /R: MYCODELIBRARY.DLL /R:Newlib.dll * .cs
As a slightly simple alternative, you can use a single / reference option and specify each assembly using a semicolon-separated list:
CSC / T: EXE /R: MYCODELIBRARY.DL should;Newlib.dll * .cs
Of course, use the same syntax when creating a C # response file.
Short description of / lib
Before viewing the role of the C # 2.0 assembly alias, please allow me to make a short description of the / lib flag. This option can be used to tell CSC.exe for the directory containing the assembly specified by the / Reference option. For instructions, assume that you have three * .dll assemblies in the root directory located on the drive C. To indicate CSC.exe in C: / Next, asm1.dll, asm2.dll, and asm3.dll, you need to issue the following command set:
CSC / lib: c: / / /reference :asm1.dll;asm2.dll;asm3.dll * .cs
If you don't use / lib, you need to manually copy these .NET code libraries into the directory that contains the input file. Also note that if the / lib flag is sent multiple times in a given command, the result will be accumulated.
Back to top
Understanding C # 2.0 Quote Alias
The last point of the / reference option is required is that in C # 2.0, you can now create an alias for the referenced assembly. With this feature, you can solve the name conflict between the names of the names that are identical in the unique name of the program.
To illustrate the practicability of this function, create a new folder called MyCodelibrary2 in the C: / MyCsharpcode directory. Place the copy of the existing SimpleType.cs and the ASMINFO.CS file in the new directory. Now add a new method to the SIMPLETYPE to display the string provided by the client:
///
/// Display a user support.
/// summary>
Public Static Void PrintMessage (String MSG)
{
Console.WriteLine ("You Said: {0}", MSG);
}
Compile these files to create a new assembly called MyCodelibrary2.dll, as shown below:
CSC / T: library /out:mycodelibrary2.dll * .cs Finally, place the copy of this new code library into the MyClient folder (Figure 8).
Figure 8. New code in myclient folder
Now, if our current client program wants to reference mycodelibrary.dll and mycodelibrary2.dll, we do the following:
CSC / T: EXE /R: MYCODELIBRARY.DLL (Mycodelibrary2.dll * .cs
The compiler tells us that we have introduced a name conflict, because these two assemblies define a class named SimpleType:
SimpleTypeClient.cs (13,7): Error CS0433: The Type 'MyCodelibrary.sIMpleType'
EXISTS in Both 'C: /mycsharpcode/myclient/mycodelibrary.dll' and
'c: /mycsharpcode/myclient/mycodelibrary2.dll'
At first glance, you may think that it can be repaired by using a fully qualified name in the client code. However, this cannot be corrected, because the two assemblies define the same fully qualified name (MyCodelibrary.SIMpleType).
With the new alias option for using the / reference flag, we can generate a unique name for each code library referenced. After we do this, we can update the client code to associate a type with a specific assembly.
The first step is to modify the SimpleTypeClient.cs file to use the alias that we will specify by the new Extern Alias syntax:
// Extern Alias Statements Must Be
// listed Before All Other Code!
Extern alias ST1;
Extern Alias ST2;
Using system;
Namespace MyClientApp
{
Public class myapp
{
Public static void main ()
{
// bind assembly to type using the '::' Operator.
St1 :: mycodelibrary.simpletype.displayenvironment ();
St2 :: mycodelibrary.simpletype.printMessage ("Hello!");
Console.readline ();
}
}
}
Please note that we have already used the C # 2.0 Extern Alias statement to capture alias defined in the command line. Here, ST1 (Simple Type 1) is an alias defined for MyCodelibrary.dll, and ST2 is mycodelibrary2.dll alias:
CSC /R :st1=mycodelibrary.dll /r :st2=mycodelibrary2.dll * .cs
Given these alias, please pay attention to the main () method how to use the C # 2.0 range resolution operator (: :) to bind the program set name to the type itself:
// this Says "I want the mycodelibrary.simpletype class
// That is defined in mycodelibrary.dll ".
St1 :: mycodelibrary.simpletype.displayenvironment ();
Furthermore, this variant of the / reference option provides a way to avoid name collisions (when two assemblies with unique names contain the names of the same name). Back to top
Generate multi-file assemblies using / addModule
As you may already know, the multi-file assembly provides a way to decompose a single .NET binary into multiple smaller small files, which proves to be helpful when downloading the .NET module. The ultimate effect of multi-file assembly is to make a set of files work like a separate reference and version control.
The multi-file assembly contains a master * .dll, which contains an assembly list. Other modules of the multi-file assembly (according to the agreement, they use the * .NetModule file extension) to be recorded in the list of main modules, and is loaded by the CLR on demand. To date, the only way to generate multi-file assemblies is to use the command line compiler.
To illustrate the process, create a new subdirectory called multifileASM in the C: / MyCsharpcode directory. Our goal is to create a multi-file assembly called AirVehicles. The main module (airvehicles.dll) will contain a single type of Helicopter (later definition). The assembly list catches an additional module (UFOS.NETMODULE), which defines a class type named UFO:
// ufo.cs
Using system;
Using system.windows.forms;
Namespace Airvehicles
{
Public Class UFO
{
Public void abductionhuman ()
{
MessageBox.show ("Resistance Is Futile);
}
}
}
To compile ufo.cs as a .NET module, specify / t: module as the target type, which will automatically follow the * .NetModule naming agreement (please recall, the default response file automatically references System.Windows.Forms.dll, so We don't need to explicitly reference the library):
CSC / T: module ufo.cs
If you want to load Ufo.netModule into ildasm.exe, you will find a module level list that describes the name and external reference set of the module (note, *. NetModules no specified version number, because that is the main module work):
.assembly extern mscorlib {...}
.assembly extern system.windows.forms {...}
.Module ufo.netModule
Now, create a new file called Helicopter.cs, which will be used to compile the main module airvehicles.dll:
// Helicopter.cs
Using system;
Using system.windows.forms;
Namespace Airvehicles
{
Public Class Helicopter
{
Public void takeoff ()
{
Messagebox.show ("Helicopter Taking Off!");
}
}
}
Assuming AirVehicles.dll is the main module of the multi-file assembly, you will need to specify / T: library flag. However, because you also want to encode the ufo.neetmodule binary to the assembly list, you must also specify / addModule options:
CSC / T: library /addmodule:ufo.neetmodule /out:airvehicles.dll helicopter.cs If you want to analyze the assembly level list included in the airvehicles.dll binary (using ildasm.exe), you will find that ufo.netmodule is indeed Is the .file CIL instruction record:
.assembly airvehicles {...}
.file ufo.neetmodule
Multi-file assembly users can share this fact that they want to collect by a large number of binary files. In fact, it will appear to be identical to the behavior of the single file assembly. In order to make this article more interesting, let's create a client application based on a Windows Form.
Back to top
Create a Windows Form Application
Our next example project will be a Windows Form Application using the AirVehicles.dll multi-file assembly. Create a new subdirectory called WinformClient in the C: / Mycsharpcode directory. Create a class derived from the form that defines a single Button type. When it is clicked, you will create a Helicopter and a UFO type and call them:
Using system;
Using system.windows.forms;
Using airvehicles;
Public Class MyForm: Form
{
Private button BTNUSEVEHICLES = New Button ();
Public myform ()
{
THIS.TEXT = "My Multifile ASM Client";
btnusevehicles.text = "Click Me";
Btnusevehicles.width = 100;
Btnusevehicles.height = 100;
Btnusevehicles.top = 10;
Btnusevehicles.Left = 10;
Btnusevehicles.click = new eventhandler (btnusevehicles_click);
This.Controls.Add (btnusevehicles);
}
Private Void Btnusevehicles_Click (Object O, Eventargs E)
{
Helicopter h = new helicopter ();
H.Takeoff ();
UFO U = New ufo ();
u.abducthuman ();
}
Private static void main ()
{
Application.run (new myform ());
}
}
Note Before proceeding, make sure that the airvehicals.dll and ufo.netModule binarys are copied to the WinformClient directory.
To compile the application as a Windows Form, make sure that Winexe is specified as the modification of the / target flag. Note that when you reference the multi-file assembly, you only have to specify the name of the main module:
CSC / T: Winexe /R :airvehicles.dll * .cs
After running your program and click the button, you should see each message box as expected. Figure 9 shows a message box I created.
Figure 9. Sample Message Box
Back to top
Use resources via CSC.exe
The next agenda is to analyze how to use CSC.exe to embed resources (eg, string tables or image files) into the .NET program. First, you can specify the path to the Win32 * .ico file using the / Win32In option. Suppose you have placed a icon file called HappyDude.ico in the application directory of the current Windows Form application. To set the happydude.ico to an icon for the executable, issue the following commands: CSC / T: Winexe /Win32icon:happyDude.ico /R :airvehicles.dll * .cs
At this point, the executable assembly should be updated, as shown in Figure 10.
Figure 10. Updated executable assembly
In addition to using the / Win32icon allocated application icon, CSC.exe also provides three additional resource-centered options (Table 5).
Table 5. CSC.exe's resource-centered options
Csc.exe's resource-centered option definition / resource is embedded in the current program set in the * .resources file inside the * .resources file. Note that you can "embed resources" in public way "by this option for all users, or" in private way "to embed resources for only the assembly usage. / LinkResource records links to external resource files in the assembly list, but actually not embedded in the resource itself. / Win32RES allows you to embed resources existing in old-style * .res files.
Before we understand how to embed resources into our program, let me introduce the nature of the resources in the .NET platform. As you may already know, the .NET resource is usually present as a group / value pair recorded as an XML (*. RESX file) or simple text (* .txt). This XML / text file is then converted to an equivalent binary, which uses a * .resources file extension. These binaries are then embedded in the program set and recorded in the list. When you need to read resources from the program, System.Resources namespace will provide a lot of types to complete this work, which is the most worthless of the ResourceManager class.
Although you must manually create a * .resx file, you'd better use the ResGen.exe command line tool (or you can of course use the Visual Studio .Net itself). Although this article does not intend to describe all of the details of ResGen.exe, let us exercise a simple example.
Embed resources using / resource
Create a new directory called MyResourceApp under Mycsharpcode. In this directory, create a new file called MyStrings.txt using NotePad.exe, and make it contain some interesting name / value pairs you selected. E.g:
# A List of Personal Data
#
Company = intertech training
LastClasstaught = .NET Security
LastPresentation = SD EAST BEST PRACTICES
Favoritegameconsole = Xbox
FavoriteComic = CEREBUS
Now, use the command prompt, convert the * .txt file to a XML-based * .resx file by the following command:
Resgen mystrings.txt mystrings.resx
If you open this file with NotePad.exe, you will find a number of XML elements that describe name / value, for example:
data>
data>
To convert the * .resx file into a binary * .resources file, you only need to update the file extension as the parameter of ResGen.exe:
Resgen mystrings.resx mystrings.resources
At this point, we have a binary resource file called MyStrings.Resources. The use of CSC.exe can be used to embed this data into the .NET program set. Suppose we have created the following C # files located in your MyResourceApp directory (RESAPP.CS):
// this Simple App Reads Embedded
// resources and displays the the the the THE
// console.
Using system;
Using System.Resources;
Using system.reflection;
Public Class ResApp
{
Private static void main ()
{
ResourceManager RM = New ResourceManager ("MyStrings",
AskEMBLY.GETEXECUTINGASSEMBLY ());
Console.Writeline ("Last Taught A {0} Class.",
Rm.getstring ("LastClasstaught"))));
}
}
To compile this assembly with respect to your mystrings.resources file, enter the following command:
CSC /Resource: Mystrings.Resources * .cs
Because I have not specified the / out flag, in this example, the name of our executable will be based on the file resapp.exe that defines main (). If everything is normal, you should find that the output is similar to Figure 11 after execution.
Figure 11. Output
I hope that you can easily create single files and multi-files .NET assemblies (with resources!) Using CSC.exe and selected text editor. You have learned the most common command line options for CSC.exe, and the rest of this article will analyze some options that are not common but still help.
If you are willing to continue learning, create a new directory called Finalexample in the Mycsharpcode folder.
Back to top
Use / define to define a pre-processor symbol
Although the C # compiler does not really preprocess code, the language does allow us to define the compiler and interact with it using preprocessor symbols similar to C. With the C # DEFINE syntax, you can create tags that control the execution path inside the application.
Note You must list the defined symbols before using any statement or other C # type definition.
In order to take advantage of common examples, assume that you want to define a symbol named debug. To do this, create a new file called FINALEX.CS and save it in the Mycsharpcode / Finalexample directory:
// define a 'preprocessor' symbol named debug. # Define debug
Using system;
Public Class FinalExample
{
Public static void main ()
{
#if Debug
Console.writeline ("Debug Symbol Defined");
#ELSE
Console.WriteLine ("Debug Not De De Defined");
#ENDIF
}
}
Note that after we use #define to define the symbol, we can use the # if, # else, and #ndif keywords to check and respond to the symbol. If you compile the program now, you should see that when FINALEX.EXE is executed, the message "debug symbol defined" is displayed on the console:
CSC * .cs
However, if you comment out the symbol definition:
// #define debug
The output will be as expected ("Debug Not De De DEfined").
During the development and testing of the .NET assembly, the command line definition symbol may be helpful. This can quickly specify symbols quickly without having to update the code base. For instructions, assume that you want to defbug symbols on the command line, please use the / define option:
CSC / Define: Debug * .cs
When you run the application again, you should see "debug symbol defined" - even if the #define statement has been commented away.
Back to top
CSC.exe's debugging-centric option
Even the best programmers sometimes find the need to debug their code base. Although I assume that most readers prefer to use Visual Studio .NET to debug activities, but some of the CSC.exe's options (Table 6) will be worthwhile.
Table 6. CSC.exe's debugging option
Csc.exe's debug-centered option definition / debug indicates that CSC.exe issues a * .pdb file for debugging tools (for example, Cordbg.exe, DBGCLR.exe or Visual Studio). / Warnaserror treats all warnings as a serious error. / WARN allows you to specify the currently compiled warning level (0, 1, 2, 3 or 4). / NOWARN allows you to disable a specific C # compiler warning. / bugreport If the application fails at runtime, the option generates an error log. This option prompts you to enter corrective information to send to anywhere you want (for example, QA Group).
To explain the usage of the / debug option, we first need to insert some coding errors in our Finalex.cs code file. Add the following code to the current main () method:
// CREATE AN ARRAY.
String [] mYStrings = {"csc.exe is cool"};
// Go out of bounds.
Console.writeLine (MyStrings [1]);
As you can see, we tried to use the cross-ribs to access our array content. If you recompile and run the program, you get indexoutofrangeexception. Although we can clearly point out the mistake, if it is a more complicated error, what should I do?
To debug the assembly created using CSC.exe, the first step is to generate a * .pdb file that contains the information you need to use a variety of .NET debug utilities. To do this, enter the following commands (they are equivalent): CSC / Debug * .cs
CSC / Debug * .cs
At this point, you should see a new file called Finalex.pdb in the application directory, as shown in Figure 12.
Figure 12. New Finalex.pdb in the application directory
You can define the / debug flag according to the situation. When you specify / debug: Full (it is a default mark), the assembly will be modified in an appropriate manner to allow it to attach it to the debugger currently executing. Since this option can influence the size and speed of the generated .NET assembly, make sure that this option is specified only during the debugging process. Because Full is the default behavior of the / debug flag, all of the above options are functionally equivalent:
CSC / Debug * .cs
CSC / Debug * .cs
CSC / Debug: full * .cs
On the other hand, specify / debug: PDBONLY can generate a * .pdb file, as well as an assembly that can only be debugged when the program is started directly by the debugging tool:
CSC / Debug: PDBONLY * .CS
In any case, since you have the required * .pdb file, you can use many debugging tools (Cordbg.exe, DBGCLR.EXE or VISUAL Studio) to debug applications. In order not to deviate from the characteristics of the command line, we will use the Cordbg.exe utility to debug the program:
Cordbg finalex.exe
After the debugging session begins, you can use the SO (Single Step Execution) command to perform each code line. When you click the wrong code line, you can find the code dump shown in Figure 13.
Figure 13. Single step execution command code dump
To terminate the Cordbg.exe utility, type EXIT and press Return.
Note This paper is not to explain the usage of the .NET debugging tool. If you want to know more about the process of debugging in the command line, find "Cordbg.exe" in the Visual Studio help system.
Back to top
Miscellaneous
At this point, you have learned the details behind the core options of the C # command line compiler. In order to make this paper more complete, Table 7 briefly describes the rest of the remaining flags I have not discussed.
Table 7. The rest of CSC.exe
CSC.EXE Option Definition / BaseAddress This option allows you to specify the expected base address of load * .dll. By default, the base address is selected by the CLR. / Checked Specifies whether an integer operation of overflow data type limits will cause anomalus during runtime. / CodePage Specifies the code page for all source code files to be used to compile. / FileAlign This option controls the section size adjustment inside the output assembly (512, 1024, 2048, 4096 or 8192 bytes). If the target device is a handheld device (eg, a Pocket PC), you can use / fileAlign to specify the minorted section that may exist. / LangVersion This option indicates that the compiler only uses ISO-1 C # language function, which basically can be concatenated as C # 1.0 language function. / main If the current project defines a plurality of main () methods (this may be helpful during unit test), you can use this flag to specify which main () method is performed when the assembly load is loaded. / NostDLIB By default, the assembly list automatically references mscorlib.dll. Specify this option can prohibit this line. / Optimize When (/ Optimize ) is enabled, you can indicate that the compiler generates minimal and fastest assemblies. This option will issue metadata that also indicates the CLR to optimize the code at runtime. / Platform This logo tells the compiler to optimize the assembly for 32-bit or 64-bit processor. In general, this option is only useful when the C # code base uses the P / Invoke and / or unsafe code structure. The default is "Anycpu". / UNSAFE When enabled, this option makes a C # file to declare an unsafe scope, which is usually used to manipulate the C style pointer. / UTF8output This option tells the compiler to use the UTF-8 encoding output data. It is important to understand that for most .NET projects, the options listed in Table 7 can only provide very few benefits. In view of this, please refer to MSDN if you need further details.
Back to top
summary
This article introduces you to the process of generating an assembly using the C # command line compiler. As you have learned, most work can be done using two flags - / target and / reference. In addition to analyzing the core logo of CSC.exe, this paper also explains the benefits of the response file and the structure of the multi-file assembly.
Although this article does not provide all the details of each option for CSC.exe, I hope that you can easily use the Visual Studio 2005 document to understand the rest of the flag.
I wish you a happy company!
Andrew Troelsen is a Microsoft MVP, who served as consultants and trainers in Intertech Training. Andrew creates many books, including winning C # and the .NET Platform Second Edition. He writes a column article every month, and he studies how to use SSCLI, Portible.Net and Mono CLI distribution in UNIX-based systems in these articles.
Go to the original English page
Back to top