Thursday, July 23, 2009

Your First Console Application

In this short tutorial, we will create a simple C# Console Application to verify that our Visual Studio is installed correctly and that the .Net Framework is working properly. We will create the famous "Hello World" application.

Having just installed Visual Studio, we should just test that the installation is working ok. To do this we will create a "Hello World" console application. We will introduce a few constructs that may be unfamiliar, but don't worry, we will cover these in greater detail in the upcoming tutorials.

For now, open up the Visual C# and create a new Console Application. In order to keep things as simple as possible for the first lesson, select all the code (Ctrl+A) or Edit » Select All, and delete it. Next, you need to type in, or copy and paste the following code into the editor.

using System;

class HelloWorld
{
static void Main()
{
Console.WriteLine("Hello World!");
}
}

Listing 1-1, Hello World Application

You should now run the program by pressing (Ctrl+F5) which will start without debugging, or from the menu select Debug » Build Without Debugging. I'll explain why in the next tutorial, but now you should see the console window that says "Hello World!"

Let's Examine the Code

On the first line, we are telling the compiler that we want to use something called System. System is a namespace that is provided by Microsoft. Namespaces are an important concept in C# (and the .Net Framework in general) and will be covered in a future tutorial. It is similar to include statements in languages such as C/C++ and PHP.

The next line of code is creating a class called HelloWorld. Again, a class is a fundamental concept in object orientated programming and will be covered in great detail in future tutorials. For now, think of a class as a container. Everything must be contained within a class in C#, unlike C/C++ and PHP where you can have variables inside or outside a class or function.

The next line of code defines the Main function for the program. We don't need to worry too much about Main at this stage, as we will cover it in a later session. Finally, our last line of code simply tells the program to write a line onto the screen. Console.WriteLine will write a line of text to the console screen and automatically add a new line, carriage return to the end. Notice there is a semi-colon at the end of the line. C#, like a lot of programming languages, uses the semi-colon to separate lines of code or operations. Every statement will have a semi-colon at the end.

Summary and Conclusion

Now you have built your first C# program using Visual C# Express, and we have introduced the basics of C# programming as well as some important concepts. In the next tutorial we will look at the features of the Visual Studio IDE and see how it can make our lives easier, and save a lot of typing.

Visual Studio Task List


Visual Studio contains a nice feature that is a Task List. This view is similar to the Output view, but shows all the tasks associated with the project or solution.

To view the task list select View menu then Task list (Ctrl+W, T). Tasks can be added with the "Create User Task" button and checked off when done.

Visual Studio Task List

The best feature for me however is its ability to automatically add and track TODO comments in your source code. When coding I often add a comment for things that need fixing or implementing in the future, the task list will pick up on these items so you can view them all and go directly to them.

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
myArrayList myList = new myArrayList();
// TODO: Genereate these dynamically
myList.Add("iulwrg");
myList.Add("3847987");

Console.WriteLine(myList.ToString());
}
}

class myArrayList : System.Collections.ArrayList
{
public override string ToString()
{
//HACK: This is a messy way, but works for now. Make it better.
string result = "";

//UNDONE: Removed for testing
//string[] theItems = (string[])base.ToArray(typeof(string));

foreach (string item in theItems)
{
result += " " + item;
}
return result;
}
}
}

This code will be scanned by the task list view and will pickup on the comment tags TODO, HACK and UNDONE.

You can define your own tags from the options screen (Tools » Options » Environment » Task List »Task List Options and add a comment token with the appropriate priority). FIXME is my personal favorite.

Visual Studio Task List - Comment Tags

.Net Command Line Tools


Visual Studio provides a set of command line tools to software engineers to acomplish some tasks that are either not available in the IDE or tools that can be run in batch.

Some of these tools are essential for distributing applications over the Internet. Listed below are the main tools and essential tools, together with a description and example usage. This is not a comprehensive or definitive list of the tools.

Csc.exe - C Sharp Compiler

Command line compiler tool compiles .cs files to .exe.

csc.exe mySource.cs - compile to mySource.exe with a target of release.

csc.exe mySource.cs /debug - compile to mySource.exe with a target of debug.

csc.exe mySource.cs /out:Demo.exe - compile to Demo.exe.

csc.exe mySource.cs /target:library - compile to mySource.dll.

csc.exe *.cs - compiles all cs files to exe.

csc.exe -? - display full list of command line parameters.

Gacutil.exe - Global Assembly Cache Tool

Command line tool to inspect the current machine's global assembly cache. You can view, install or uninstall assemblies from the GAC with this tool.

gacutil.exe /l - List all assemblies currently installed on the machine.

gacutil.exe /i myfile.dll - Install an assembly into the GAC.

gacutil.exe /u myfile.dll - Uninstall an assembly from the GAC.

gacutil.exe - display full list of command line parameters.

Ildasm.exe - Intermediate Language Dissembler

Not strictly a command line tool, but not installed onto the start menu. This program will provide a disassembly of a file provided that it is a Portable Executable (PE) executable (generated by the ILASM tool or C# compiler).

The tool will inform you of any references the program has, the classes, methods and data objects in the executable and other debug information.

Ilasm Intermediate Language Assembler

Compile Intermediate Language to Portable Executable (PE)

ilasm.exe source.il - compiles to source.exe.

ilasm.exe source.il /dll - compiles to source.dll.

ilasm.exe source.il /key:keyfilename - compiles to source.exe using keyfilename to strongly signed private key.

Sn.exe Strong Name Tool

Helps sign assemblies with strong names. It provides options for key management, signature generation and signature verification.

sn -k mykey.snk - generate a random key and store it in mykey.snk.

sn -v mykey.snk - verify an assembly

XML Documentation


Visual Studio 2003 and onwards provides the ability to generate project documentation using comments in the code with embedded xml tags. These can be easily converted to a printable or human readable document using stylesheets.

The code editor will automatically provide the XML tags, all you need to do is to fill in the text as you code. XML documentation is slightly different from normal code comments in that it uses three forward slashes (///) instead of the two. The editor will provide a list of tags that you can use, including a title and description for methods.

By typing /// in front of a method, the editor will auto complete a basic documentation layout for that method.

///
///
///

///
static void Main(string[] args)
{

All you need to do is fill in a summary of the method (what it does, called by, any data it returns etc…) and a description of the parameters it takes.

Using IntilliSense (Ctrl+Space) you can bring up a list of tags that can be used, including examples, seealso and permissions.

It is good practice to comment your code as you progress.

A well-commented application permits a developer to fully understand the structure of the application and how the various aspects interact with each other. It also allows other developers to understand the project much quicker as they spend less time trying to work out what everything does.

When your code is complete and commented you can generate documentation by configuring the project properties.

Either right click the project in the Solution Explorer or select Properties from within the Project menu. At the bottom of the build tab there is an option to generate XML Documentation. Just enter a path for the documentation to be stored within. It will default to your project directory + "bin/debug/ .xml".

You can also use the command line tool, csc.exe, to generate a documentation file:

csc program.cs /doc:my-xml-documentation.xml

This will generate an XML file containing the documentation which you can use XML Transformation on to generate a "pretty printed" version.

The text within the

tags is used by IntelliSense as the method description when prompting for info in the code designer. If you are developing code that will be reused by different people it is highly recommended that each method have at a minimum a summary section.

No comments:

Post a Comment