Analytics


Google

Tuesday, May 5, 2009

Programmer's Journal - Chapter 1

Before starting this blog, I wrote a quick guide on getting started on .Net. Since it took me several months to prepare the book, I thought I will share it here.

This is chapter 1.

Chapter 1 - Getting Started

Writing your first dotNet program.

Before you can start writing a dotNet program, you need to install the framework. This can be obtained from the Microsoft website. All Framework related download and information are available at http://msdn.microsoft.com/netframework/programming/.

There are currently three versions of the .Net framework – Version 1.0 (which is not used anymore), Version 1.1 (it is recommended that you install service pack 1 if you are using this version) and Version 2.0 (which has just been released).

The framework will be installed in the windows directory. Assuming your windows directory is c:\windows and you are installing framework 1.1, the framework will be installed into C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322. Two compilers are included with the framework, vbc.exe (for Visual Basic) and csc.exe for (C#). Framework 2.0 will be installed in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727.

With this you should be able to write your first Visual Basic.Net program. As you can see in the screen below, you can even write programs just using the dos prompt.



So what is next? In order to write program in any language, we need to know what is available. Microsoft has graciously provided such information. It is all packaged in the dotNet SDK. It comes with the documentation, tools and tutorials to get started.

Visual Studio.Net 2003 comes with its own set documentation containing all the documentation provided in the SDK but adds information that are applicable in Visual Studio.

Note that the documentation in SDK for Framework 2.0 is not as complete as the documentation in SDK for Framework 1.1. The documentation in Framework 2.0 only provide code samples, while the documentation in Framework 1.1 provides samples and also notes of the different classes, properties and methods.

Versioning

Start the Windows explorer and go to the HelloWorld.exe we generated earlier and select the properties, either by using the right button and select properties or highlighting the file and press Alt-Enter. You will then see the following window:




In the version tab, all the values are blank and the version numbers are all 0.0.0.0.

That is because the versioning information was not provided in the sourcecode when the program was compiled. The version information can be added into the program by adding the following code:

Imports System.Reflection

<Assembly: AssemblyTitle("Hello World")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Programmer's Journal")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("Programmer's Journal")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyVersion("1.0.0")>
<Assembly: AssemblyFileVersion("1.0.0")>


This can be done either directly in the program file or in a separate vb file and compile it together with your program file. Visual Studio 2003 uses the separate file approach and generates a file called AssemblyInfo.vb. The AssemblyVersion is set 1.0.* and is incremented automatically each time the project is compiled. This information has been moved to project file in Visual Studio 2005 – (for vb programs, that will be the .vbproj file).

Assuming we stored the above program as AssemblyInfo.vb, we need to compile the program using the following command:

C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\vbc helloworld.vb assemblyinfo.vb /out:helloworld.exe

If you want to compile using Framework 2.0, the the command will be:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\vbc helloworld.vb assemblyinfo.vb /out:helloworld.exe

Windows will know which version of the framework to use when the program is invoked when more than one framework is installed in the machine. This allows multiple version of Framework to coexist on one machine.

After compiling, look at the properties of the exe again – the version information has been added to the file properties:



Multiple files can be compiled into one .exe or .dll file – by specifying list of files in the command line (separated by space) when invoking the compiler. In dotNet, all programs and libraries are referred to as assemblies.

In a production environment, version information is important when taking calls from users. The problem the encountered may have been fixed, it is important to make it simple for the user to know the version number of the program they are running. The version information can be obtained using the following method: System.Diagnostics.FileVersionInfo.GetVersionInfo against itself. The function that you can use for the assembly to refer to itself is System.Reflection.Assembly.GetExecutingAssembly.Location.

There are two types of version: AssemblyVersion and AssemblyFileVersion. The AssemblyFileVersion is the version number you will see when you look at the properties of the file. The AssemblyVersion is used by the Version binding policy – can be used when there are multiple incompatible versions of assembly. The binding policy is only available for strong name assemblies.

The following program contains different ways of getting the assembly version number:

Imports System.Reflection

<Assembly: AssemblyTitle("Hello World")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Programmer's Journal")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("Programmer's Journal")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyVersion("1.2.3")>
<Assembly: AssemblyFileVersion("2.4.6")>


Module ShowVersion

Function Ver As String
Dim fInfo As system.Diagnostics.FileVersionInfo
fInfo = _
system.Diagnostics.FileVersionInfo.GetVersionInfo(system.Reflection.Assembly.GetExecutingAssembly.Location)
Return _
finfo.FileMajorPart & "." & fInfo.FileMinorPart & "." & fInfo.FileBuildPart _
& "." & fInfo.FilePrivatePart

End Function

Function Ver2() As String
With _
System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .FileMajorPart & "." & .FileMinorPart & "." & .FileBuildPart & "." & .FilePrivatePart
End With
End Function

Function Ver3() As String
With _
System.Diagnostics.FileVersionInfo.GetVersionInfo(system.Reflection.Assembly.GetExecutingAssembly.Location)
Return .ProductMajorPart & "." & .ProductMinorPart & "." _
& .ProductBuildPart & "." & .ProductPrivatePart
End With
End Function

Function Ver4() As String
Return _
System.Diagnostics.FileVersionInfo.GetVersionInfo(system.Reflection.Assembly.GetExecutingAssembly.Location).ProductVersion
End Function

Function Ver5() As String
Return _
System.Diagnostics.FileVersionInfo.GetVersionInfo(system.Reflection.Assembly.GetExecutingAssembly.Location).FileVersion
End Function

Function Ver6() As String
Return _
System.Reflection.Assembly.GetExecutingAssembly.GetName.Version.ToString
End Function

Sub Main
System.Console.WriteLine("Version - " & Ver())
System.Console.WriteLine("Version 2 - " & Ver2())
System.Console.WriteLine("Version 3 - " & Ver3())
System.Console.WriteLine("Version 4 - " & Ver4())
System.Console.WriteLine("Version 5 - " & Ver5())
System.Console.WriteLine("Version 6 - " & Ver6())
End Sub
End Module




After compiling, look at the file property and it will look like this:



The following is the output of the above program.



Assembly File Version is obtained by the various functions except for the last one, which returns the Assembly version. Assembly Version is important when we use strong named assembly since it can be used to control compatibility. Only strong named assembly can be placed into the Global Assembly Cache.

Assemblies in the Global Assembly Cache can be referred to from anywhere in the machine. For non-global assemblies, the Framework expects them in the same directory as the executing program (for Console and WinForm) or in the specially designated subdirectory (bin) in the virtual application in IIS.

Tools
Even though coding with the Framework can be done using simple text editors and the command prompt, it is very tedious (especially with the amount of typing needed to compile the program using the vbc command line). There are a few ways reduce the amount of typing, one is to use a batch files. However, there are tools that can help with the process.

The most obvious and comprehensive tool is Visual Studio.Net.

However, there are a lot of other options (most of them free) available.

Web Matrix

For designing and laying out ASP.net program, you can you Web Matrix. Since this tool was released by Microsoft to promote the use of Framework 1.1, it does not contain the newer controls that are introduced in Framework 2.0. This can be obtained from:

http://www.asp.net/webmatrix

It is unlikely that this tool will be updated to support Framework 2.0 since Microsoft will introduce Visual WebDeveloper 2005 Express Edition for that – which can be obtained for free during the first year of its introduction.

Snippet Compiler

This is a useful tool to perform compilation of C# and VB program – supports compiling codebehind file and will perform verification against the aspx file. It contains a limited IntelliSense – capable of only showing options for original classes, not for variables or derived objects. It has the capability of importing Visual Studio Projects.

You can also add references to your new library (DLL). The file will be locked if it is referenced, so you will need to remove the reference and shutdown the snippet compiler and restart if you want to compile the library.

Nevertheless, it is still a good utility for formatting and compilation. It provides an option to import a Visual Studio project, which is good if you have access to the source code but do not have Visual Studio handy. Unfortunately, at the time of writing does not recognize some of the newer classes in Framework 2.0 (there is a separate version for 1.1 and 2.0 but the version 2.0 still does not recognize some of the newer classes – probably because it was written while 2.0 was still in Beta).

The tool is available from http://www.sliver.com. The following is the snapshot of the tool:



SharpDeveloper

This is a free dotNet IDE that started with support for C# only but it has since extended its support into Visual Basic. It comes with a lot of features you can see in Visual Studio. It can be used for designing WinForm program, Console programs and console programs. It does not provide a design interface for ASP.Net.

It has a better-developed IntelliSense compared to Snippet Compiler. However, in order to write programs that refer more assemblies than the basic assembly, a project will need to be created (just as you do in Visual Studio).

Since it is a full fledge IDE, you will need to create a combined project – similar to project in Visual Studio to take add reference and control the Framework version you want to use. At the time of writing, there is no ASP.Net designer – it is asking for volunteers to work on that module. It also lacks the option to import project from Visual Studio.

The screen shot of the interface is shown below:



This tool is available from http://www.icsharpcode.net.

NANT

Nant brings the same functionality of ANT to dotNet (It is a powerful tool for performing compilations). It uses an XML to provide the necessary instruction to perform compilation. The following is a sample project for one of my projects:


<?xml version="1.0"?>
<!--
NANT build File for Create Partition
Author Strovek
Date Apr 08, 2005
Revised

-->
<project name="crePartDate" default="build" basedir=".">
<property name="project.name" value="File Limit Alert"/>
<property name="project.version" value="1.1.0" />
<description>Create Oracle Partition.</description>
<property name="debug" value="true" unless="${property::exists('debug')}" />
<property name="verbose" value="true" />
<target name="clean" description="remove all generated files">
<delete file="crePartDate.exe" failonerror="false" />
<delete file="crePartDate.pdb" failonerror="false" />
</target>
<target name="build" description="compiles the source code">
<vbc target="exe" output="crePartDate.exe" debug="${debug}">
<sources>
<include name="crePartDate.vb" />
</sources>
<references>
<include name="System.dll" />
<include name="System.Web.dll" />
<include name="System.XML.dll" />
<include name="System.Data.dll" />
</references>
</vbc>
</target>
</project>



This tool is available from:

http://nant.sourceforge.net/

By default, it will use the framework version the program is compiled in (version 1.1). If you want to use a different version, use the switch –t:net-2.0. This is controlled in the configuration file nant.exe.config in the bin directory of the nant folder. You may need to verify the copy you have since the Framework 2.0 build number was changed between Beta 1, 2 and RTM. (Changing from v2.0.40607 in Beta 1 to v2.0.50727 for the RTM) and update the version accordingly.

Microsoft introduced a new build utility – msbuild with Framework 2.0 that provides similar capabilities as NANT.

Visual Studio.Net 2005 Express

Visual Studio.Net 2005 express edition was launched on November 07, 2005. It comes in five different modules introduced:

1. Web Developer
2. Visual Basic
3. Visual C#
4. Visual C++
5. J#

For the first year (Nov 2005 to Nov 2006), it can be downloaded and used for free. After the first year the free download will no longer be available – will need to purchase but at a very low price. This express edition packages support only Framework 2.0.

Oracle SQL Developer

Oracle SQL Developer is a free tool that was introduced by Oracle to access their database, write stored procedures/function/packages. It can be downloaded from http://www.oracle.com/technology/software/index.html. This tool supports Oracle 9i and above. It may work with earlier versions of Oracle but you will not have all the functionalities.

It comes in a zip file; just unzip it to a directory and use. When you unzip to a directory (say c:\sqldeveloper, you will find two files sqldeveloper and sqldeveloper.exe, If using Windows then use sqldeveloper.exe (you should probably create a shortcut to this and put it in your desktop or start menu to make it easier for yourself). The other one (sqldeveloper), is used to start the sql developer in Unix.

When launched the program looks like this:



I created all the above connections. When you first start there will be no connections. To add Connections; right click on the Connections and then select New Database Connection… You will see the following:



You can then specify the database (by specifying all the information or use the information from your Oracle Client (if it is already installed on your computer), change the name, add the account and password.

After connecting, you will be able to browse the various objects within the instance as shown below:



When viewing each of the categories, if the number of object exceeds a certain limit, you will encounter the following icon:



Double click it and you will get the following:



As you browse through the tables, you will be able to change the values directly. You can also filter the data you are shown etc.



You can also open the SQL Worksheet and type in your sql statements to execute (F9 or ). If you have a date field within your table, you need to execute the following to specify the format you want, this has to be done each time you connect back into the database:

alter session set nls_date_format = 'dd-Mon-yyyy HH:mi'

Before executing the above command:



After:



When running your scripts, you can also click the . However, this will only work if the Explain table is available (it will be created for you if you have the right privileges. This is very useful, if you need to tune your scripts.

You can also edit your packages, stored procedure/functions directly.

There is too much features in this tool to cover here but I wanted to introduce you with some of the functions. You will need to experiment with the rest yourself.

Where is my INI?

In previous version of Visual Studio languages, ini was used to store many of the application configurations. In ASP, global.asa is used for this purpose.

With dotNet, Microsoft has standardized the configuration files to Xml format. For asp.net, you would use web.config in the virtual application directory and for executables (winform, Window service and console programs), the configuration file will reside in the same directory and the configuration file will match the program name followed by .config at the end – for example Hello.exe will have Hello.exe.config.

The following is an illustration how we can use the configuration file for a console program:

The configuration files looks like this:

<?xml version="1.0" encoding="UTF-8" ?>

<configuration>

<appSettings>
<add key="KeyString" value="Value in KeyString" />
</appSettings>

</configuration>


To access the above value, you need to use (if you are using Framework version 1.1) System.Configuration.ConfigurationSettings.AppSettings(“KeyString”)

If you are using Framework version 2.0, you should use the following instead:
For console/winform application:

System.Configuration.ConfigurationManager.AppSettings(“KeyString“)

For ASP.Net applications:

System.Web.Configuration.WebConfigurationManager.AppSettings(“KeyString“)

Let us proceed to modify the code; the modified code is as follows:


Module Hello
Sub Main
System.Console.writeline("Hello World")
System.Console.WriteLine( _
System.Configuration.ConfigurationSettings.AppSettings("KeyString"))
End Sub
End Module


If you try to compile the above code using our previous approach, you will encounter an error



This is because the code required for reading the configuration file resides in the assembly called system.dll in the runtime directory (there are 86 base assemblies provided when you install the framework). We need to add /r:system.dll to let the compiler know to look up the code in that assembly. Once added, the compilation will produce the following result:



There is actually another kind of executable, which is an Internet Explorer hosted executable. The configuration is configured using the following tag:

<link rel=”ConfigurationFileName” href=”location”>

In addition to this configuration, there is also the machine.config and security.config file. Both of these files reside in the config directory below the where you install the framework (i.e. the runtime install location). For example the configuration file may reside in:
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG. These two files will control the configuration and security of the entire computer. It is recommended that changes be made through the .Net framework configuration tool (accessible via the administrative menu in Windows 2000) or using the Code Access security Policy tool (caspol.exe).

For most cases, it is not necessary to change the machine.config and security.config.

We will go into details on separate sections of the application configuration file later in the book.


No comments: