JScript.Net Tutorial

JScript.Net Tutorial #6

Welcome to the sixth C# tutorial (still haven't found a better way to start these tutorials). Now we are getting to the nitty gritty and to the heart of JScript.Net with the introduction of classes. It should be noted that classes are constructed differently in Javascript to bring it more in line with languages like C#. Now it has to be said that up till now I have not been a big fan of classes but they are growing on me and they are implemented quite nicely in C# but maybe not so well in JScript.Net but we shall carry on regardless. So what is the big mystery? What ARE classes? Well, I've already given you a big clue in the previous tutorial. A Class is a mixture of structures (which I can't really implement in JScript) and functions in one construct. Here is what a simple class looks like with its calling program:-

import System;

class HelloWorld
{
	var i : int = 1;

	function ShowHello()
	{
		Console.WriteLine
       			("Hello World with Classes!");
	}
}

public class Test 
{
    	public static function Main() : void 
	{
		var hw = new HelloWorld();
		hw.ShowHello();

		Console.WriteLine(hw.i);
		hw.i=2;
		Console.WriteLine(hw.i);
	}
}
Test.Main();

Note how I've implemented Main() in case you missed it last time. I think I need to explain first that the class TestHello is there just to contain the Main() program otherwise it won't compile. What I have done is create my own class outside of the Main() class (and it could be contained inside another file) which I can call upon from the Main() program. I can create an instance of it and call functions housed within it. I can also modify variables contained within it much like in a struct. All very clever.

So in Main(), I first create an instance of the HelloWorld Function which still invokes it and displays the message on the console. Then I write to the console the contents of the variable in HelloWorld, modify it and write it out again - this is how structures could be implemented in JScript.

So when should you use classes? Well, you could program in JScript and NEVER use them at all. But you would be missing out on a whole lot of stuff. I'm not going into classes any more deeply at this stage but there are some things you ought to know about classes.

It is my aim in these tutorials to teach you enough to be able to use databases and Windows GUI forms and you don't necessarily need all the extra stuff to do it but I may return this subject in later tutorials. I'll leave you with an enhancement to the above program before we move on:-

import System;

class HelloWorld
{
	var i : int = 1;

	function ShowHello()
	{
		Console.WriteLine
       			("Hello World with Classes!");
	}
}

class ShowTime
{
	function ShowCurrentTime()
	{
		Console.WriteLine
       			("The current time is: " + DateTime.Now);
	}
}

public class Test 
{
    	public static function Main() : void 
	{
		var hw = new HelloWorld();
		hw.ShowHello();

	Console.WriteLine(hw.i);
	hw.i=2;
	Console.WriteLine(hw.i);

	var st = new ShowTime();
	st.ShowCurrentTime();
	}
}
Test.Main();

This enables you to call a class to get the current time. I hope that all this will become clearer as we move further into these tutorials.

So that's it with classes. I have previously alluded to the fact that structures are the building blocks for creating databases. To complete such an application, you need to be able to save the information to disk and for that you need files. You need to be able to do the following things with files:-

Here is a sample program:-

import System;
import System.IO;

public class Test 
{
    	public static function Main() : void 
	{
        	var strPath : String = "Test.txt"
		var fi : FileInfo = new FileInfo(strPath);

		// create a file if not exist
		if(!fi.Exists)
		{
        		var sw : StreamWriter = fi.AppendText();
	        	sw.WriteLine("Hello");
        		sw.Close();
		}

		// add to existing file
		if(fi.Exists)
		{
        		var writer : StreamWriter = fi.AppendText();
	        	writer.WriteLine("Welcome");
        		writer.Close();
		}

		// read file
        	var sr : StreamReader = new StreamReader( fi.OpenRead() );

        	while (sr.Peek() != -1)
            	Console.WriteLine( sr.ReadLine() );
    	}
}
Test.Main();

Now I have to say that there seems to be a distinct lack of JScript.Net samples in the MSDN section of the MS site and it took a not inconsiderable amount of time to put together this small sample on files. I eventually discovered that I needed the FileInfo classes in JScript (although confusingly it can be used in other languages) but C# and VB classes won't work (or at least I couldn't get them to work) in JScript.Net. This isn't everything as you need to be able to update individual records within files but that is really beyond the scope of these tutorials as I'm sure you're itching to get to databases proper which does all this for you so I'll leave it at that. The above program is in three sections. The first sets the file name to the current directory and if the file doesn't exist (the ! operator means NOT) then create a text file and write a line to it. It isn't necessary to close a file in C# as the using keyword does that for you but it MUST be done both in JScript.Net and VB.Net. The second section appends a line of text to an existing file and the third reads it and writes the contents to the screen until the end of the file is reached.

That wraps up files. One other thing to aquaint you with (yes databases is next!) is error checking. This is done using try, catch, finally which has been part of C++ and Java for a while but has made it into C# (and Visual Basic.Net as well). Hres some code:-

import System;

public class Test 
{
    	public static function Main() : void 
	{
		try 
		{
			Console.WriteLine("Try");
			throw("New Error");
		}

		catch (e)
		{
			Console.WriteLine("Catch");
			Console.WriteLine("A new error");
		}

		finally
		{
			Console.WriteLine("Finally");
		}
	}
}
Test.Main();

It was quite difficult to find a simple bit of code to trip an exception (error to you) and the divide by zero error sample I used in my C# tutorials doesn't seem to work in JScript (probably because JScript is more relaxed about variable types) so I've had to resort to throwing an exception. The code we want to use goes inside the try section which would usually be some kind of open command which may trip an error if a file doesn't exist for example. If an error is generated then the catch part comes into play and generates an error message. The finally bit ALWAYS runs and would normally contain the file close command so the file would be closed no matter what. We will need this in the next tutorial (which will be databases...honest). See you then...

Back to JScript.Net Tutor

Written by Nick Cheesman. Last updated: 01/06/2007
Please eMail me at:
nickjc@nickjc.co.uk