Hudzilla Coding Academy: Project One

Code
Hudzilla Coding Academy

 

This is our first programming project, so it's going to be really easy to do. The main goals are to get you up and running with your programming environment so you're able to create and run programs, and in doing so we'll be producing a simple program that tracks a list of tasks that you need to do. Once you finish the main tutorial, you'll get to try adding some extra features as part of the homework. I have tried to cover everything in a slow and simple way - if you've programmed before and already know what variables, loops and conditional statements are, you may want to skip some parts.

Enough waffling from me - let's get you started with a program...

MonoDevelop, your new best friend

The list of software you need is pretty small. This entire series will be focused on the C# programming language using a platform known as Mono. Mono converts our C# code into runnable programs, and it also provides a massive amount of functionality that you can just call upon as you make your programs.

The most popular text editor for Mono developers is called MonoDevelop, and has lots of neat features that make programming easier - you'll discover these as you go along. For now, what matters is that both Mono and MonoDevelop are included as standard in many Linux distributions, which makes them very easy to install. All the tutorials and assignments were written and tested using Ubuntu 8.10, which means if you're using a different distribution you will need to mentally rewrite some of the instructions so they work for you! If you're one of my students, I would strongly recommend you also use Ubuntu 8.10 for your programming so that I can help you if you run into problems.

Time to install your new programming software:

  1. Click System > Administration > Synaptic Package Manager. You'll need to enter your password when prompted.
  2. In Synaptic's Quick Search box, type "MonoDevelop" and press Enter.
  3. The "monodevelop" package should be in the results list somewhere (probably first). Right-click it then choose Mark For Installation.
  4. Synaptic will warn you that installing MonoDevelop will mean installing lots of other things. That's OK, because we need them! Click Mark when it prompts you.
  5. Now click the Apply button from the menu bar, then click Apply again in the confirmation window that will appear.
Installing MonoDevelop also installs Mono and lots of other requirements.

Installing MonoDevelop brings with it Mono and a big set of dependencies - thus saving us from having to choose them all by hand!

Once Ubuntu has finished downloading MonoDevelop and all its requirements, close Synaptic then go to Applications > Programming > MonoDevelop to fire it up.

Printing to the screen

Our first project is going to work on the Linux command line. In fact, many of our programs will be designed for the command line, simply because I'm more interested in teaching you how to code than teaching you how to drag and drop things in a user interface designer!

MonoDevelop can give our command-line projects a kickstart by providing some basic code to get it working. Go to File > New Solution, then choose C# from the list of templates and Console Project from the list of options on the right. A Solution, if you were wondering, is a fancy name for a collection of projects, and a project is a fancy name for a collection of files that work together to make a program. Big solutions often contain multiple projects, but that's not likely in our projects.

Choosing a Console Project gets you started with free code.

Choose C# then Console Project to have MonoDevelop set you up with a basic console skeleton to get you started.

Where it says "Name" (just under "Location") enter ToDoList, then click Forward. MonoDevelop will ask you whether you want to include support for any extra features, but you don't, so click OK to continue.

The code it gives you should look something like this:

// Main.cs created with MonoDevelop
// User: hudzilla at 00:47 31/01/2009
//
// To change standard headers go to Edit->Preferences->Coding->Standard Headers
//
using System;

namespace ToDoList
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Hello World!");
		}
	}
}

You can ignore most of that - you'll figure out what it means and why it's important later, but for now it's just meaningless fluff. Focus on the line that starts with Console.WriteLine(): that's us asking Mono to write a line of text to the console (the terminal window). Hopefully you should be able to guess that it will print out the string of letters "Hello World!", which is a traditional (if incredibly cliched) first coding project.

Nearly all the rest of that code is just there as boilerplate stuff, ensuring the program actually works. The exception are the few lines at the top that start with "//" - those two double slashes tell Mono that those lines are actually plain-text comments that are for our eyes only, so they will be ignored by Mono when building the program.

Go to the Project menu and choose Run (or just press F5). Mono will convert the code into instructions that can be executed by the computer (a process known as "compiling"), and will run it - look in the bottom part of the Mono window for a pane marked "Application Output", which should now say "Hello World". Easy!

The Application Output pane shows what the program outputs.

The Application Output pane is just below your code window, and will automatically be shown when your program is run.

Reading from a file

Our project needs to read a to do list from a text file then be able to make a few simple changes to it. We're going to make it so that each to do list item is on its own line in the text file so that it's easy to work with them individually. So, the first thing we need to do is give it a file to read from - go to Applications > Accessories > Terminal to start a console for us to type into. Now type this:

cd ToDoList/ToDoList/bin/Debug

The first "ToDoList" is where your solution lives and the second is the name of the project - one solution can have multiple projects, remember. The "bin" and "Debug" directories get automatically created by MonoDevelop whenever you build your program, because that's where the executable version (known as a "binary") of your program lives. As you ran this program already, you should find a ToDoList.exe file in that directory (run the "ls" command to list the files).

Now let's create a to do list file in that directory. Run this command from your terminal window:

echo Meh > todo.txt

That will save one line of text ("Meh") into the file todo.txt. Now switch back to MonoDevelop - it's time to make Mono read and print that file!

Create a basic to do list to get our program started.

It's not hard to create a to do list in our program, but as this is the first tutorial we'll do it by hand - it's always good to have some basic command-line skills around!

The first line of code in our program that isn't a comment is this one:

using System;

These "using" statements are there to tell Mono what kind of functionality we want to use. You see, Mono is made up of a gigantic amount of code that you can draw upon at any time. But rather than having to pull in all that extra weight just for it not to be used, Mono only imports the bits you ask it to. The "using System" line means "please give me the absolute basic bits required to make a program.

We're going to need to read some input into our program (our file) and later write some output (our changes to the file), so we need to ask Mono to switch on a new piece of functionality known as System.IO - the IO part is just short for "input/output". Change that one "using" line to this:

using System;
using System.IO;

Now that input/output functionality is enabled, we need to read our file into the program. Take a look at this code and see if you can figure out what it means:

var contents = File.ReadAllText("todo.txt");

Put that into your program just before the Console.WriteLine() line; we'll be using it soon.

The second half of that line ought to make immediate sense: we're asking Mono's "File" code (the bits that handle all the stuff to do with files) to "ReadAllText" inside todo.txt. When that code runs, Mono loads todo.txt, reads it all in, then thinks "OK, now where should I put the text?" That's where the first half of the line comes in: "var contents =" - that tells Mono to give us a variable called "contents", and assign to it whatever File.ReadAllText() reads from its file.

MonoDevelop's code completion helps remind you what code does.

As soon as you type the dot in "File.", MonoDevelop will show you a list of things you can do. Use your Up and Down cursor keys to choose an option, then press Enter to accept it.

If you've never programmed before, you'll have no idea what a "variable" is and why it wants to vary in the first place. Well, these things are used nearly everywhere in programming, which means you need to figure them out sooner or later, so here goes: a variable is simply a piece of memory on your computer that you can refer to in your program.

In the example above, we have a variable and call it "contents", which means any time we want to work with the value stored in that particular chunk of memory, we can just refer to "contents" and Mono will know what we mean. If you were wondering, the reason variables are called "variables" is because their value can change over time if you want it too. For example:

var contents = File.ReadAllText("todo.txt");
contents = File.ReadAllText("someotherfile.txt");
contents = "Hello World!";

Printing our file's contents

As we now have the data from todo.txt inside the "contents" variable, the next step is to print it out to the screen. Thanks to MonoDevelop's skeleton C# file, we already have the functionality required to print something in this line:

Console.WriteLine("Hello World!");

To make our program print out the contents of the file instead, just tell it to print the variable rather than "Hello World!", like this:

Console.WriteLine(contents);

If you run the program now, it should print out "Meh", because that's all that todo.txt contains right now.

If you want to, you can miss out the "contents" variable altogether and send the output from File.ReadAllText() straight into Console.WriteLine(), like this:

Console.WriteLine(File.ReadAllText("todo.txt"));

On the plus side, this condensed method uses less screen space. But it's much harder to read, it doesn't allow you to use the contents of todo.txt more than once without having to run File.ReadAllText() again, and ultimately it won't make your code any faster - so use it with caution!

I came here for an argument!

It's very common to run programs from the command line using one or more parameters, like this:

cd /foo/bar/baz
ls -la *.txt

In the first command, "/foo/bar/baz" is being passed as a parameter to the "cd" command. In the second, "-la" is the first parameter and "*.txt" is the second, both of which are being passed to the "ls" command.

Our program accepts parameters too, which means we can let the user control what it does by sifting through those parameters to see what they passed in. First things first, though: from now on you need to use your terminal window to run your program, because it lets you type parameters on the fly. You should still have the terminal window open from before, back when we created the todo.txt file, so type this in there:

./ToDoList.exe hello from mono

If that doesn't work, don't fret - try running this instead:

mono ./ToDoList.exe hello from mono

When you press Enter, our program will run and print "Meh" as before - that's because we haven't told it to do anything with the parameters that get passed into it. Switch back to MonoDevelop and look for this line of code amongst the others that MonoDevelop provided:

public static void Main(string[] args)

It's the "string[] args" part that we're particularly interested in, because that's where Mono hands us all the arguments that the user typed. The two square brackets [ and ] means that this "args" variable actually holds several values rather than just one, which is usually called an array. If you try printing out the whole array at once, it won't work. Here, try it:

Console.WriteLine(args);

If you build that program (choose Project > Build Solution or just press the F8 key) then switch to your terminal window and run the same command ("./ToDoList.exe hello from mono") again, you'll see this:

System.String[]

D'oh!

Loop the loop

To get the output we want, we need to tell Mono that for each variable in the "args" array, send it to Console.WriteLine(). Happily, the code to do this is almost the same as those words I just typed! Check it out:

foreach (var arg in args) {
	Console.WriteLine(arg);
}

Don't worry about what it means just yet - just press F8 to have Mono compile your program again, then switch to the command line window and run the program again. This time you should see the following on your screen:

hudzilla@academy:~/ToDoList/ToDoList/bin/Debug$ ./ToDoList.exe  hello from mono
hello
from
mono

It worked! This "foreach" statement is what's known as a "loop", because it loops over the code multiple times. Now to unpick what the code actually means. You probably thought it would look something like this:

foreach (var in args) {

After all, that would be identical to the description of what we wanted in English - "for each variable in the args array." The problem is, once Mono gives us the first variable in the array, we need to be able to reference it so that it can be sent to Console.WriteLine(). That's what the "arg" part means: assign each value to a variable called "arg" so we can use it.

A foreach loop assigns each array item to a temporary variable.

A foreach loop assigns each array item to a temporary variable for you to use inside the loop.

Those { and } symbols are usually called braces, and they mark the beginning and end of code blocks. Our skeleton MonoDevelop code has several of them already, and these new foreach braces are used to mark what code should be executed for each variable in the array. For example, let's say you want to do more with each variable...

foreach (var arg in args) {
	Console.WriteLine(arg);
	Console.WriteLine(arg.ToUpper());
}

Before you build and run that program, try to figure out what it does. Here's a hint: using ToUpper() on our argument makes it uppercase. Can you picture in your head what it should print out?

If you try running it, you should get this output:

hello
HELLO
from
FROM
mono
MONO

So as you can see, the braces mark the start and end of the code that makes up the loop.

The neat thing about these arguments is that Bash (the Linux shell) does a little bit of magic on your behalf. For example, if the user runs this command:

./ToDoList.exe "hello from mono"

...then your program will only receive one argument: "hello from mono". That's because Bash knows that text passed inside quotes is actually all part of a single argument.

You can have as much functionality inside your foreach loops as you want to, but for now let's return to our program...

Adding things to do

Now that we know how to read user arguments, we can make it so that the user can choose to either show their current to do list or add a new item. Let's start with adding an item - ideally we want the user to be able to run a command like this:

./ToDoList.exe add "Feed the cats"

Remember, any arguments in quote marks will be passed as a single argument, so when that command is run our app will receive two arguments: "add" and "Feed the cats". What we need to do is check the first argument to see what it is, and, if it is "add", add the second argument to the to do list.

I would love to tell you that writing all that in C# is almost as easy as writing it in English, but it's not quite true. In fact, there are two problems that trip up newbies:

  1. C# counts all its arrays from 0, not 1. That is, the first variable inside args is accessed using args[0], not args[1]. Cunningly, this means that args[1] is actually the second variable inside args! Don't worry, this isn't C# being weird - this is common in many popular programming languages.
  2. If you want to check whether a variable is equal to something, you don't use the = sign. That's because C# already uses = to mean "assignment", as in "var content = File.ReadAllText(blahblahblah)". Instead, you need to use ==, which is two equals signs next to each other.

With those two important points in mind, here's how to check whether the first argument is "add" or not:

if (args[0] == "add") {
	// do something here
}

You can also specify what should happen if args[0] isn't equal to "add" by using more braces. For example:

if (args[0] == "add") {
	// do something here
} else {
	// args[0] isn't "add" - do something else!
}

If args[0] is "add", we need to append the second argument to our todo.txt file, which can be done by calling File.AppendAllText(). To use this, you need to tell it which file should be written to (todo.txt) then tell it what text should be appended to the end of the file. Because these two pieces of data are completely separate, we need to put a comma inbetween them. So, a first attempt at writing this in C# might look like this:

if args[0] == "add") {
	File.AppendAllText("todo.txt", args[1]);
	// note the comma inbetween "todo.txt" and args[1]!
} else {
	// args[0] isn't "add" - do something else!
}

I say that's what a first attempt might look like, because it has one flaw: if you remember from earlier, we're designing this program so that each item in todo.txt will be on its own line in the file. But if you append text to the end of the file, it will be put directly onto the end of whatever was there before, rather than having its own line. For example, let's say our file just contains "Meh", and we then run these three commands:

./ToDoList.exe add "Feed cats"
./ToDoList.exe add "Wash socks"
./ToDoList.exe add "Take over the Earth"

At the end of it, the file won't look like this:

Meh
Feed cats
Wash socks
Take over the Earth

Instead, this is what the file will look like:

MehFeed catsWash socksTake over the Earth

As you can see, because we haven't told Mono to add a line break in there after appending the arguments, the new to do list items just get added onto the end of the existing line!

The solution lies in a special little character sequence you can use with any text in Mono: \n. If you type a backslash followed by an "n", Mono will understand that to mean "new line".

File.AppendAllText("todo.txt", args[1] + "\n");

So, if you want to append args[1] to the file then start a new line on the end of it, make sure you include the \n!

What's on the agenda?

If you rebuild the program and try running it, you should be able to add items to the list using the "add" command. Don't try running it without any arguments just yet - that's something we'll be looking at later. For now, let's extend it so that if anything other than "add" is passed in (eg "list", or "wobble"), the program shows all the items that are on the list.

Right now, your code looks like this:

if args[0] == "add") {
	File.AppendAllText("todo.txt", args[1]);
} else {
	// args[0] isn't "add" - do something else!
}

You need to change that so that actually do some work in the "else" block. Just by shuffling around the existing code a little, you should be able to get this far:

if args[0] == "add") {
	File.AppendAllText("todo.txt", args[1] + "\n");
} else {
	var contents = File.ReadAllText("todo.txt");
	Console.WriteLine(contents);
}

That certainly works, but it's not very easy to modify. For example, what if we wanted to print the position of each item in the list? It's not possible right now, because ReadAllText() returns all the items as one variable. What we need to do is read each of the lines individually into an array, then use a foreach loop to print out the items ourselves.

You already know how to use a foreach loop, so the question is: how can we get the contents of todo.txt into an array of individual lines? Well, it's actually not so hard - thanks to the existence of File.ReadAllLines()! Take a look at this:

var contents = File.ReadAllLines("todo.txt")
foreach(var item in contents) {
	Console.WriteLine(item);
}

When you run that code, you'll see it does exactly the same thing as before, so why bother doing it this way? Well, now we can have Mono print out the item position as we go by introducing another variable. For example:

var contents = File.ReadAllLines("todo.txt");
var counter = 1;
foreach(var item in contents) {
	Console.WriteLine(counter + ": " + item);
	counter = counter + 1;
}

Press F8 to build the program again, and try running it from the command line using "./ToDoList.exe list" to print out the items - remember, you can provide anything except "add" to make it print the items out. You should see this:

1: Meh
2: Wash socks

Obviously your output might be different depending on what items you've added to your to do list. But as you can see, we've combined three things together to send to Console.WriteLine(): counter, ": " and item. That middle piece of text is just there to make the output look a little nicer - you're welcome to change it to something fancier if you want to.

The output from our program so far.

The output from our program so far - by reading the file as an array of lines, we can add numbers to make it easier to read.

The real piece of code that's new is the counter variable: we set it to 1 to begin with, then add one to it each time the loop runs. Yes, internally Mono counts all its arrays from 0, but our users don't care about that so we number from 1. Previously your variables have either contained text or arrays of text, but as you can see they can hold numbers just as easily.

Before we move on, you should know that few programmers ever write "counter = counter + 1", because it's such a common thing to do that the smart people behind Mono added a shortcut: ++ (that's two plus symbols). For example, these two lines do the same thing:

counter = counter + 1;
counter++;

The opposite of ++ is, of course, -- (two minus symbols together), which subtracts one from a variable:

var counter = 1;
counter++; // counter is now 2
counter--; // counter is 1 again

Deleting items

Unless you're particularly skilled at procrastination, you're going to want to delete tasks sooner or later, so let's give that a try. Thanks to the counter code we just put in, we can figure out a given task's position in the list and show it to the user. Ideally they should be able to type "del 3" to delete the third task.

But first, we need to detect when the "del" command is being given. Right now, we look for "add", and, if it isn't found, just show the list. What we need is to say "if it's add, do this... if it's del, do this..., and otherwise, do this...". Fortunately that's not hard at all:

if (args[0] == "add") {
	// do add stuff
} else if (args[0] == "del") {
	// do del stuff
} else {
	// just list the items
}

You can have as many "else if" conditions in there as you want, but it gets a little messy after a while. For now, it's fine, so let's focus on replacing "do del stuff" with meaningful code!

The plan of action is this:

  • Read the full list in to our contents array.
  • Delete the file, so we can write it fresh.
  • Set counter to be 1.
  • Read the second argument to see which item should be deleted.
  • Loop over the contents array. If counter is not equal to the number they want to delete, write the item to todo.txt.

By only writing items if they don't match the number that should be deleted, we're basically skipping over the item the user specified - thus making sure it doesn't get written back to todo.txt.

How we're going to delete an item from our to do list.

The easy way to delete an item is just to rewrite the list, missing out the item that should be removed.

The best way to do all this is for me to show you the code, and type some comments into it as I go. So, here it is:

// load the file into an array
var contents = File.ReadAllLines("todo.txt");

// delete the old file - we have it all in our program now
File.Delete("todo.txt");

// this variable is used to count our position nside the list
var counter = 1;

// and this is the one that stores the item to delete
var deleteme = int.Parse(args[1]);

// now loop over all the items in the list
foreach(var item in contents) {
	// != means "not equal to", and is the opposite of == (equal to)
	// so, if counter is not equal to the number to delete...
	if (counter != deleteme) {
		// ...write this item todo.txt
		File.AppendAllText("todo.txt", item + "\n");
	}
	
	// add 1 to counter
	counter++;
}

Now, there are two bits of magic in there that need explaining. First, if you use File.AppendAllText() on a file that doesn't exist, Mono will automatically create the file. Second, I've snuck in a call to int.Parse(), which is something completely new and potentially a little tricky to grasp at first.

If I set the variable counter to be 5, what would counter++ do? Hopefully you're thinking "it would set counter to be 6", and that would be the right answer. But what if I set the value of counter to be "fish" - what would counter++ do then? The answer is that Mono would simply implode: you can't add 1 to a word, because it just doesn't make sense.

You see, all this time you've been using "var" to store data in variables, Mono has, behind the scenes, been figuring out exactly what kind of data you want to store in there and assigning the right amount of memory. This is a bit of a problem now because our counter holds a number, and the arguments from the command line are received as text. In our code, both look like "var", but behind the scenes Mono sees a number on one side and some text on the other, and won't let us compare them. The solution is to convert the text into a number and store that in the deleteme variable.

That brings up back to the int.Parse() line, which is designed to read some text and convert it into a integer (or "int" for short), which is Mono-speak for whole numbers such as 1, 50 or 123456789. Technically speaking, the "counter" variable we've been using so far has been an integer all along, but the args array is full of text, so we need to convert it to an integer before comparing it against counter.

At this point our program allows people to add, delete and list items, which makes it pretty much feature complete. But before we're done, there's one extra thing I'd like to cover just quickly...

Fixing bugs

Try running this command:

./ToDoList.exe

Yes, that's running the program without specifying any action at all. The result? The program explodes in an ugly way - in geek speak, it crashes, and spits out some meaningless error message as a free bonus.

When your program crashes, Mono will print an error message that might help you out.

Running our program without any parameters will cause it to crash with the message "Array index is out of range" - that means we're trying to read an item that doesn't exist inside an array. Fortunately, this is easily fixed!

The reason it's crashing is because we're trying to access args[0], and if no arguments are passed in then args[0] doesn't exist - we're trying to read something in the array even though the array is empty. The solution is to run a simple check: when the program runs, check how many arguments were passed in, and if the answer is 0 then print a usage message and quit. To do that, put this code before the "if (args[0] == "add)" line:

if (args.Length == 0) {
	Console.WriteLine("Usage: list | add <item> | del <num>");
	return;
}

The args.Length value is set to the number of variables inside the args array, so we check whether that value is 0 - if it is, no arguments have been passed in. That code is the first time we've used the "return" statement, which means "exit the current piece of code". In the current situation, it means the program exits immediately, without bothering to execute all the code underneath it.

It's really important to go over your code to try to fix all the problems you can. Ultimately, your program should never crash. Sure, it might say, "we've encountered a problem" if something really strange happens, but it should never explode and spit out error messages - even if the user does something unexpected. Later on in this series I'll be teaching you ways to catch these kinds of unexpected problems, but for now your best bet is to try all sorts of ways to run your program and try to make sure no problems crop up!

Let's wrap up

This has been a really long tutorial, but I hope you'll agree it was worth it because you should have learned several fundamental programming techniques while producing a working program. So far you've learned how to create a MonoDevelop solution, work with files, create loops, read arguments from the command line, write conditional statements, and more.

So yes, this was long, but that's just to ensure no one is left behind at the beginning. You'll be using all these techniques in future tutorials, which means we'll be able to talk less and code more - just as I like it.

Homework

If you're following this with a tutor, you will be required to complete the following homework before continuing. If you're working by yourself, I strongly recommend you find someone who can help check your work and provide feedback.

The homework for this project is made up of three coding problems; all are required.

  • When we're listing the items on the to do list, put a message at the beginning of the list saying "Number of items: ", followed by the number of items on the list. For example, "Number of items: 5".
  • We've fixed the program so that it doesn't crash when no arguments are passed in. But it still crashes if "add" or "del" are used without a second argument, eg "./ToDoList.exe add". Fix the program so that if "add" or "del" are used without second arguments, they print the usage message and exit.
  • Add a new command, "clear", that deletes the todo.txt file and recreates it as a blank file. Remember, calling AppendAllText() automatically creates a file if it doesn't exist, even if the text you're trying to append is empty.

If you have problems, try to solve them yourself - you might not succeed, but you'll learn a lot by trying! If you're still having problems, drop your tutor an email and ask for help.

The small print

This work was produced for TuxRadar.com as part of the Hudzilla Coding Academy series. All source code for this project is licensed under the GNU General Public License v3 or later. All other rights are reserved.

You should follow us on Identi.ca or Twitter


Your comments

var ??

when i try an assign a variable with var in mono i get the error:

error CS0246: The type or namespace name `var' could not be found. Are you missing a using directive or an assembly reference?

what is wrong and how do i fix it.

Re: var ??

You're almost certainly using an older version of Mono, eg from Ubuntu 8.04. As the tutorial says, I recommend people use a relatively recent distro (such as Ubuntu 8.10) to ensure compatibility with my code.

"var" is only available as standard in Mono 1.9 or later, but - if you're building from the command line - you might have luck by specifying -langversion:linq

That's a pretty good

That's a pretty good tutorial for newbies wishing to get into coding - bookmarked :)

Out of Range!

Unhandled Exception: System.IndexOutOfRangeException: Array index is out of range.
at ToDoList.MainClass.Main (System.String[] args) [0x00000] in /home/dave/ToDoList/ToDoList/Main.cs:15

Here is my code so far...
public static void Main(string[] args)
{
if(args[0] == "add"){
File.AppendAllText("todo.txt", args[1] + "\n");
}
else{
var contents = File.ReadAllText("todo.txt");
var counter = 1;
foreach(var item in contents){
Console.WriteLine(counter + ": " + item);
counter++;
}
}

}

Any ideas?
Google didn't help!

Thanks

P.S.
Thanks for selecting me for the academy Paul! <3

Out of Range!

Just realized where I went wrong lol. Sorry! :D

Struggling.

Struggling with the homework part 1 and part 2. Part 3 is done.
Gonna get to sleep now and try again in the morning, if not, then I'm really stuck!
Hints might be nice :P

Thanks.

Struggling.

Struggling with the homework part 1 and part 2. Part 3 is done.
Gonna get to sleep now and try again in the morning, if not, then I'm really stuck!
Hints might be nice :P

Thanks.

Delete

Seriously, add the ability to remove your own posts to this...SPAM FTW!

What do you use to create your flowcharts?

What program do you use to crete the flowcharts in the tutorial? I've been looking for something in Linux to create my charts and have had limited success.

Hi

Hi, i use Visual Studio 2008 and when i want to pass an argument, i just got System.String [] even when i write exactly the same code as you did. Does this code even work on windows, and can i learn C# from your academy, for windows?

Thanks in advance!

Hi again

Nvm, i fixed the problem. Everything works great on Windows too:) I already done my homework, and the program is stable. Thank you again for this GREAT tutorials, i really learned new things :)

Help!

I'm having the same Out of Range exception error as Dave - I wish he'd posted the solution! Can anyone help, it is driving me nuts!

RE: Help!

The only difference I can spot is:

Code of Dave:
var contents = File.ReadAllText("todo.txt");

Tutorial:
var contents = File.ReadAllLines("todo.txt");

With the foreach function you are reading out an array. I coul be wrong, but the only thing I can think of is that the File.ReadAllText doesn't return an array and the File.ReadAllLines does.

homework part 2

Cant figure out how this is done. That is to make the program not crash when typing in add or del by itself. Anybody have the solution? Great tutorial by the way!

Homework Part1

Hello, got parts 2 and 3 working,but part 1 only half working. Having problems with printing the number of lines.
thank you.

Re: homework part 2

Here is my code so far.

using System;
using System.IO;

namespace ToDoList
{
class MainClass

{
public static void Main(string[] args)

{
if (args.Length==0){
Console.WriteLine("Usage: List | add<item> | del<num> | clear");
return;
}

if(args[0]=="list"){
var contents=File.ReadAllLines("todo.txt");
var counter=1;

Console.WriteLine("Number of items:");
foreach(var item in contents){
Console.WriteLine(counter+":"+item);
counter++;
}
}else if (args[0]=="clear"){
File.Delete("todo.txt");
File.Create("todo.txt");

}

else if (args.Length==1){
Console.WriteLine("Usage: List | add<item> | del<num> | clear");
return;
}else if(args[0]=="add"){
File.AppendAllText("todo.txt",args[1]+"\n");
} else if(args[0]=="del"){
//load file into the array
var contents=File.ReadAllLines("todo.txt");
// delete the old file
File.Delete("todo.txt");
//this variable is used to count our position inside the list
var counter=1;
//and this is the one that stores the item to delete
var deleteme=int.Parse(args[1]);
// now loop over all the items in the list

foreach(var item in contents){
//!= means "not equal to" it is the opposite of ==(equal to)
//so if counter is not equal to the number delete...
if(counter!=deleteme){
//...write this item todo.txt
File.AppendAllText("todo.txt", item + "\n");
}

//add 1 to counter
counter++;
}
}
else{
Console.WriteLine("Usage: list | add<item> | del<num> | clear");
return;
}

}
}
}

Exception Handling

Quick tip for homework problem 2:

try {
File.AppendAllText ("todo.txt", args[1] + "\n");
} catch (IndexOutOfRangeException) {
Console.WriteLine ("Usage: ls | add <item> | del <num> | clear");
}

For more information, web search for "c# exception handling".

Hope that helps!

Homework 1

Hello! Here's a hint for homework Part 1:

somevariablehere.Length counts the number of files in a variable.

Try using that with some other editing at the part where you wrote the code that listed the items.

simplest solution

public static void Main (string[] args)
{
if (args.Length == 0 || args.Length==1 &&(args[0]=="add"||args[0]=="del"))

{
Console.WriteLine("Usage: list | add <item> | del <num> |clear");
return;
}

if(args[0]=="list")
{
var c=0;
var count=File.ReadAllLines("todo.txt");
foreach(var item in count)
{
c++;
}
Console.WriteLine("Number of items = "+c);
}

else if(args[0]=="add")
{
File.AppendAllText("todo.txt",args[1]+"\n");
}

else if(args[0]=="del")
{
var contents = File.ReadAllLines("todo.txt");
// delete the old file - we have it all in our program now
File.Delete("todo.txt");
// this variable is used to count our position inside the list
var counter = 1;
// and this is the one that stores the item to delete
var deleteme = int.Parse(args[1]);
// now loop over all the items in the list
foreach(var item in contents)
{
// != means "not equal to", and is the opposite of == (equal to)
// so, if counter is not equal to the number to delete...
if (counter != deleteme)
{
// ...write this item todo.txt
File.AppendAllText("todo.txt", item + "\n");
}
// add 1 to counter
counter++;
}
}

else if(args[0]=="clear")
{
File.Delete("todo.txt");
File.AppendAllText("todo.txt","");
}

else
{
var content = File.ReadAllLines("todo.txt");
var counter=1;
foreach(var item in content)
{
Console.WriteLine(counter + ":" + item);
counter++;
}
}
}

Failing at the start!!!!

Hello,I'm struggling to get this command to work ..cd ToDoList/ToDoList/bin/Debug it says something like file not found.
I'm sure this is so basic its not true,but I cant find a way round it-what am I doing wrong/not doing?
Its not a good start,particularly as I shelled out for the magazine only to find the same stuff on here for free...

Reply to Ted

Hi Ted,

It is very basic but its very normal when you start working with files and folder paths in the command line.

Make sure that you are in the Directory where the ToDoList folder exist.

Example: if your ToDoList is in your development folder under your home directory, you might want to type in the following command

cd home/development/ToDoList/ToDoList/bin/Debug.

Hope that works out well.

FAILING AT BEFORE THE START.

This tutorial presumes you know what to do with the "code" you have to down load to even get started. I can download it sure. I could probably figure out how to extract it... but where should you extract it to??? Does monodevelope MAGICALLY know where it will be once it's extracted can I tell monodevelope where to look for it if it doesn't know??? or is there a specific place I should extract it to so that the system can find it...

Granted I just moved from the legacy OS to linux so maybe some of these questions have simple commonplace answers to more experienced linux users but to a REAL BEGINNER these things are important.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

CAPTCHA
We can't accept links (unless you obfuscate them). You also need to negotiate the following CAPTCHA...

Username:   Password:
Create Account | About TuxRadar