Chapter 2 New
Transcript of Chapter 2 New
Chapter 2 – Building C# ApplicationsBUILDING C# APPLICATIONS: The Role of the Command Line Complier (csc.exe), Building C# Application using csc.exe, Working with csc.exe Response Files, Generating Bug Reports, Remaining C# Compiler Options, The Command Line Debugger (cordbg.exe), Using the Visual Studio .NET IDE, Other Key Aspects of the VS.NET IDE, C# “Pre processor:” Directives, An Interesting Aside: The System.Environment Class.
Role of Command Line Compiler(csc.exe) Is the easiest way to compile and run most of the programs. Able to create .NET assemblies using the C# Command Line compiler csc.exe, where csc stands for
C – Sharp Compiler. Configuring the C# Command Line Compiler To equip the development machine to compile *.cs files from any directory, follow these steps
Right click on the My Computer icon and select properties from the popup menu. Select the Advanced tab and click the Environment Variable button. Double click the path variable from the System Variables list box. Add the following line to the end of the current path value:
C:\Windows\Microsoft .NET\Framework\v2.0.50215 Make a test run by opening a new command line window and entering csc /?
Configuring Additional .NET Command Line Tools You can add the additional path variables to the System Variable list box:
C:\Program Files\Microsoft Visual Studio 8\SDK\V2.0\Bin You should now be able to run any .NET utility from any command window.
To create and run programs using C# csc.exe follow 3 steps:1. Enter the program using Text Editor
//A simple C# programusing System;class Testapp{
public static void Main( ){
Console.WriteLine(“A Simple C# program”);Console.ReadLine ( );
}}Save the file in a convenient location Testapp.cs
2. Compiling the programTo compile the program, execute the C# compiler csc.exe specifying name of the source file on the command line.
C:\> csc Testapp.csThe csc compiler creates a file called testapp.exe that contains the MSIL version of the program. The CLR automatically invokes JIT compiler when testapp.exe is executed.
3. Running the programTo run the program, just type the name on the command line C:/> Testapp
Building C# applications using csc.exeOnce the program is written and saved. Next step is to specify the name and type of assembly to create. Each possibility is represented by a specific flag passed into csc.exe as a command line parameter.
Chapter 2: Building C# applications Page 1
Some of the output centric options available in C# compiler are:
To specify the type of target, we can use csc /target:exe Testapp.cs. We can also use csc /t:exe Testapp.cs. Test.exe can now be run from the command line.
Referencing External Assemblies Means examining how to compile an application that makes use of types defined in a
separate .NET assembly. To illustrate the process of referencing external assemblies
using System.Windows.Forms; class Testapp {
public static void Main(string[] args) {
MessageBox.Show(“Hello! World”); }
} From the above program the reference to the System.Windows.Forms namespace is via the C#
using keyword. At the command line, you must inform the csc.exe which assembly contains the used namespaces. Since in the program we have used MessageBox class we must specify the
System.Windows.Forms.dll assembly using ‘/r’ reference flag. csc /r:System.Windows.Forms.dll Testapp.cs
Compiling Multiple Source files with csc.exe It is allowed to have all .NET types defined in a single *.cs file, most projects are composed of
multiple *.cs files to keep code base a bit more flexible.
Example : hello.csusing System;using System.Windows.Forms;class hello{
public void speak(){ MessageBox.Show(“Hello”); }
}
Chapter 2: Building C# applications Page 2
Testapp.csclass testapp{
Public static void Main( ){ hello h = new hello( );
h.speak( );}
} You can compile your C# files by listing each input file explicitly:
csc /r:System.Forms.dll testapp.cs hello.cs The C# compiler allows you to make use of the wildcard character to include all files contained in
the project directory. csc /r:System.Forms.dll *.cs
Referencing Multiple External AssembliesTo reference numerous external assemblies using csc.exe simply list each assembly using a
semicolon-delimited listcsc /r:System.Forms.dll;System.Drawing.dll *.cs
Working with csc.exe Response files To build a complex C# application at the command prompt, it will be tedious to type in the flags
that specify numerous referenced assemblies and *.cs input files. To help less the typing burden, the C# compiler honors the use of response files. C# response files contain all the instructions to be used during the compilation of the current build. These files end in *.rsp extension. Eg: Type the following commands in Notepad (Comments are given using # character.
#this is response file# for the test.exe application #external assembly references/r:System.Windows.Forms.dll#output and files to compile(using wildcard syntax)/target:exe /out:test.exe *.cs
Save the file (test.rsp) in the same directory as the C# source code files to be compiled and are able to build entire application as follows. >csc @test.rsp
To specify multiple response file *.rsp file as input>csc @firstfile.rsp @secondfile.rsp @thirdfile.rsp
While specifying multiple *.rsp 2 points to be noted are:o Compiler processes the command options as they are encountered. Therefore command-line
arguments in a later *.rsp file can override options in a previous response files.o Flags listed explicitly on the command line before a response file will be overridden by the
specified *.rsp fileo For Eg: > csc /out:Mycoolapp.exe @test.rspo The name of the assembly would still be test.exe rather than mycoolapp.exe.o If the flags are listed after a response file, the flag will override settings in the response file
Default response file C# compiler has an associated default response file csc.rsp which is located in the same directory as
csc.exe file csc.rsp file contains numerous .NET assemblies specified using /r:flag. When building C# program using csc.exe, this file will be automatically referenced even when
supplied with custom *.rsp file To disable automatic reading of csc.rsp, specify /noconfig option.
csc @test.rsp /noconfig
Chapter 2: Building C# applications Page 3
Generating Bug Report C# compiler provides a helpful flag named /bugreport. The /bugreport option is used to report source code bugs. It creates a text file containing the source code; versions of the operating system, compiler,
and .NET runtime; and the programmer's description of the problem and the expected result. The following example shows how to use the /bugreport option.
csc /bugreport:report.txt myCode.cs
The Command Line Debugger(cordbg.exe) The command Line debugger(cordbg.exe) tool provides dozens of options that allow you to debug
your assembly. At the command prompt if we type cordbg /? It gives flags recognized by cordbg.exe. To name a few.
Debugging at the Command Line Before debugging the application using cordbg.exe, the first step is to generate debugging symbols
for current application by specifying the /debug flag of csc.exe For eg:
Csc @testapp.rsp /debug This generates a new file named testapp.pdb(pdb- program debug database). Once *.pdb file is generated, open a session with cordbg.exe by specifying .NET assembly as a
command line argument. The *.pdb file will be loaded automatically.cordbg.exe testapp.exe
At this point, you are in a debugging mode and may apply any number of cordbg.exe flags at command prompt.
To quit from debugging type exit.
C# Pre-Processor Directives:C# preprocessor is fundamentally very similar to C preprocessor and the whole concept in C# has
been taken from C language specification. C# compiler does not have a separate preprocessor, the directives described I this C# are processed as if there was one.
#line Used to control the line numbers emitted for errors and warnings
Chapter 2: Building C# applications Page 4
#error, #Warning Used to issue errors and warnings for the current build.
Specifying Code Regions User is able to specify a block of code that may be hidden from view and identified by a friendly
textual marker. The use of regions can help keep lengthy *.cs files more manageable. Eg:
Class regionexample{ …..
#region public class Myclass{//stuff………… }Public interface Myinterface{ //stuff…. }#endregion
} When you place the mouse cursor over a collapsed region, you are provided with a snapshot of the
code lurking behind.
#define Defines a character sequence called a symbol. The existence or nonexistence of a symbol can determined by #if or #elif and is used to control
compilation. General form: # define Symbol No semicolon in this statement.
#undef Removes a previously defined symbol. It undefines a symbol General form: # undef Symbol Eg:
#define SMALL…..
#if SMALL//…#undef SMALL//at this point SMALL is undefined.
#undef is used to allow symbols to be localized to only those sections of code that need them.
Conditional Code Compilation: (#if, #elif, #else, #endif) Allows you to conditionally compile a block of code, based on predefined symbols. The classic use of these directives is to include additional code only compiled under debug builds. For eg: when your current application is configured under a debug build, you wish to dump out a
number of statistics to the console.using system;class Process{ …
Static void Main(String [ ] args){ # if (DEBUG)Console.WriteLine(“App directory {0}”,Environment.CurrentDirectory);Console.WriteLine(“Box {0}”,Environment.MachineName);
Chapter 2: Building C# applications Page 5
Console.WriteLine(“OS {0}”,Environment.OSVersion);Console.WriteLine(“Version {0}”,Environment.Version);#endif}
} If the DEBUG symbol is defined or true, the code that is between #if and #endif is compiled. Example for #elif and #else
using System;#define RELEASEClass test
{ public static void Main(){
#if EXPERIMENTALConsole.WriteLine(“this is an experiment”);
#elif RELEASEConsole.WriteLine(“Entered Release”);
#elseConsole.WriteLine(“compiled for internal testing”);
#endif #if TRIAL && !RELEASE
Console.WriteLine(“trail version”);#endif
Console.WriteLine(“This is in all version”);}
}Output: Entered RELEASE
This is in all version
Issuing Warnings and Errors #error directive
o Forces the compiler to stop compilation.o It is used for debugging
General form: #error error-messageo When #error directive is encountered, the error message is displayed. For eg: When the
compiler encounters this line#error This is a test error!
Compilation stops and the error message “ this is a test error!” is displayed. #Warning directive
o Is similar to #error except that a warning rather than a error is produced.o Compilation is stopped.o General form: #warning warning-message
Altering Line numbers: #Line: This directive allows you to alter the compiler’s recognition of #line numbers during its recording
of compilation warnings and errors. Allows you to specify the name of a file to dump said compiler anomalies To reset the default line numbering, you may specify the default tag. #line allows 2 options
o #line default which returns the line numbering to its original condition.o #line numeric value which sets the line number from the given value.o Example:
// the warning below will be issued on line set line number to 3000
Chapter 2: Building C# applications Page 6
#line 3000#warning “Custom warning on line 3000//resume default line numbering#line default
The System.Environment Class: When developing applications it is important for the developer to know the environment in which
the application is running. Environment class contains methods and properties that provide information about the current
environment and platform. It is important to note that this class cannot be inherited, nor one can extend the functionality in
this class to create own class. Some of the properties and methods that this class contains are
o Environment.OSVersion – Gets the current OS version. o Environment.CurrentDirectory – Get the present working directory. o Environment.GetLogicalDrives() – Gets all the drives present in the computer. o Environment.Version – Gets the version of the .NET platform. o Environment.MachineName – Gets the name of the current machine o Environment.NewLine – Gets the new line symbol for the current environment o Environment.ProcessorCount – Returns the number of processors on the current machine. o Environment.SystemDirectory – Returns the full path to the system directory. o Environment.UserName – Returns the name of the entity that started this application.
//Here are some of the interesting static members of the Environment classUsing System;Class Enviclass
{public static int Main(string[ ] args){
//Which OS version are we running on?Console.WriteLine(“Current OS:{0}”, Environment.OSVersion);
//DirectoryConsole.WriteLine(“Current Directory:{0}”, Environment.CuurentDirectory);//Logical drivesString[ ] drives = Environment.GetLogicalDrives();for(int i=0;i<drives.Length;i++)
Console.WriteLine(“Drive {0}: {1}”, I, drives[i]);
//Which version of .NET platformConsole.WriteLine(“Current Version of .NET:{0}”,Environment.Version);
return 0;}
}
Building .NET applications using Visual Studio 2005 Some of the features provided by visual studio are
GUI designer Database manipulation tools Object and project browsing utilities An integrated help system Visual XML editors/designers
Chapter 2: Building C# applications Page 7
Support for mobile device development Support for Microsoft Office development The ability to track changes for a given source document and view revisions Integrated support for code refactoring An XML based code expansion library Visual class design tools and object test utilities A code definition window
The Solution Explorer Utility
The solution explorer utility allows you to view the set of all content files and referenced assemblies that comprise the current project.
The ‘references’ folder of solution explorer displays the list of each assembly you have currently referenced.
When you need to reference additional assemblies, right click the references folder and select add reference. Select the assembly from the resulting dialogue box.
When you double click the icon named properties, you are presented with the enhanced project configuration editor.
The Class View Utility The purpose of this utility is to show all of the types in your current project from an object
oriented perspective. The top pane displays the set of namespaces and their types, while the bottom pane displays
the currently selected types members.
The Code Definition Window This tool allowed you to type in the name of a .NET type and views its C# definition.
Chapter 2: Building C# applications Page 8
An enhanced version of this tool has been integrated with visual studio 2005. Place the mouse pointer over any type in your C# code file; you will be presented with the
snapshot of the type. For example, if you click on the ‘String’ in any method, you find the definition of System.String class type.
The Object Browser Utility
Visual studio 2005 provides a utility to investigate the set of referenced assemblies within your current project.
Integrated Support for Code Refactoring Refactoring is a formal and mechanical process to improve an existing code base. Visual
studio 2005 does a great deal of automated refactoring. Using refactor menu, related keyboard shortcuts, smart tags and/or context sensitive mouse
clicks, you can dramatically reshape your code with minimal bother.
Code Expansions and Surround with Technology
Chapter 2: Building C# applications Page 9
Visual studio 2005 has the capability to insert complex blocks of C# code using menu selections, context sensitive mouse clicks, and/or keyboard shortcuts.
The number of available code expansions can be broken down into two main groups: o Snippets: These templates insert common code blocks at the location of the mouse
cursor. o Surround with: These templates wrap a block of selected statements within a relevant
scope. Right click on the blank line within your Main() method and activate the insert snippet menu.
Once you select a given item, you will find the related code expanded automatically. If you right click and select surround with menu, you would be presented with a list of
options.
The Visual Class Designer Visual studio 2005 gives us the ability to design classes visually. The class designer utility
allows you to view and relationships of the types in your project. You are able to visually add and remove members to or from a type and have the
modifications reflected in the corresponding C# files.
Object Test Bench Object test bench allows you to quickly create an instance of a class and invoke its members without
the need to compile and run the entire application.
The Integrated Help System Visual studio 2005 provides the dynamic help window, which changes its contents based on
what item is currently selected. For example, if you place the cursor on the Console class, the dynamic help window displays
a set of links regarding the System.Console type.
Chapter 2: Building C# applications Page 10