RicH and FamouS

       Home         Glosar IT                                                                                                                                                                                                              SUBSCRIBE NOW!
        

12.04.2009

C# - Agenda (Command line)

Am hotarit sa rezolv asa o problema: Sa se scriu un program tip 'agenda telefonica' (pentru a se demonstra folosirea ArrayList)

Am scris urmatorul cod (impartit in 4 fisiere, pentru o mai usoara urmarire a codului):

Codul din fisierul agenda.cs (care contine si functia main)

Cod:
using System;
using System.Collections;

namespace agenda
{
class agenda
{
static void Main()
{
PhoneBook ph = new PhoneBook();
ph.Import(input.ReadFromFile());
int user_choice;
bool again = true;
while (again)
{
user_choice = output.DoMenu(ph.Count);
switch (user_choice)
{
case 1: //print all records from agenda
ph.PrintAgenda();
break;
case 2: // add a record to agenda
ph.Add(input.ReadNewRecord());
break;
case 3: // edit an record in agenda
string to_edit;
Console.Write("Enter the name of record you want to edit: ");
to_edit = Console.ReadLine();
if (ph.IsSet(to_edit))
ph.EditRecord(to_edit);
else
Console.WriteLine("Name not found!");
break;
case 4: // delete record
string to_delete;
Console.WriteLine("Warning!!! Delete is PERMANENT!");
Console.Write("Enter the name of record you want to delete: ");
to_delete = Console.ReadLine();
if (ph.IsSet(to_delete))
{
ph.Delete(to_delete);
}
else
{
Console.WriteLine("Name not found!");
}
break;
case 0: //exit
again = false;
Console.WriteLine("Bye! Bye! (Enter... exit!)");
output.WriteToFile(ph.Export());
Console.ReadLine();
break;
}
} //while
} //end Main()
}
}

Apoi am creat un nou fisier, PhoneBook.cs unde am creat class PhoneBook, clasa al carei rol este sa gestioneze un ArrayList. codul este urmatorul:

Cod:
using System;
using System.Collections;

namespace agenda
{
class PhoneBook
{
private ArrayList pBook = new ArrayList();
public void Add(record rec)
{
pBook.Add(rec);
} // Add(record rec)
public void Add_at_index (record rec, int index)
{
pBook.Insert(index, rec);
} // Add_at_index (record rec, int index)
public int Count
{
get { return pBook.Count; }
} //Count
public record this[int index]
{
get
{
if (index < 0 || index >= Count) throw new
Exception("Invalid index. Must be an integer between [0 .. " + (Count -
1) + "]");
//if (this[index] == null) throw new Exception("Null record");
return (record)pBook[index];
}
set
{
if (index < 0 || index > Count) throw new
Exception("Invalid index. Must be an integer between [0 .. " + (Count -
1) + "]");
pBook[index] = value;
}
}
public record GetbyName(string name)
{
if (name.Trim() == "") throw new Exception("Invalid request. Void name");
for (int i = 0; i < Count; i++)
if (((record)pBook[i]).FName == name) return (record)pBook[i];
throw new Exception("Invalid request. " + name + " cannot be found.");
} // GetbyName(string name)
public bool IsSet(string name)
{
if (name.Trim() == "") return false;
for (int i = 0; i < Count; i++)
if (((record)pBook[i]).FName == name) return true;
return false;
} //IsSet(string name)
public bool IsSet(int index)
{
if (pBook[index] == null) return false;
return true;
} //IsSet(int index)
public void Delete(string name)
{
if (!IsSet(name))
{
Console.WriteLine("Invalid name. Record NOT FOUND!");
return;
}
pBook.RemoveAt(GetIndexByName(name));
Console.WriteLine("{0} Removed Succesfuly!", name);
}
public int GetIndexByName(string name)
{
if (name.Trim() == "") return -1;
for (int i = 0; i < Count; i++)
if (((record)pBook[i]).FName == name) return i;
return -1;
} //GetIndexByName(string name) this return -1 if name is not in PhoneBook
public void PrintAgenda()
{
Console.WriteLine();
for (int i = 0; i < Count; i++)
Console.WriteLine(i.ToString() + ". " + (record)pBook[i]);
} // PrintAgenda() - full print of agenda
public void PrintAgenda(char FirstLetter)
{
for (int i = 0; i < Count; i++)
if (((record)pBook[i]).FName[0] == FirstLetter)
Console.WriteLine((record)pBook[i]);
} // PrintAgenda() print all records that start with specified char
public void EditRecord(string name)
{
int index = GetIndexByName(name);
if (index == -1) //invalid name
throw new Exception("Invalid Record Name.");
record current = GetbyName(name);
Console.WriteLine("Current First Name is: " + current.FName);
Console.Write("Do you want to change it (y/n)? ");
if (Console.ReadLine().ToLower() == "y")
{
current.FName = input.ReadFirstName();
}
Console.WriteLine("Current Second Name is: " + current.SName);
Console.Write("Do you want to change it (y/n)? ");
if (Console.ReadLine().ToLower() == "y")
{
current.SName = input.ReadSecName();
}
Console.WriteLine("Current phone no is: " + current.Tel_no);
Console.Write("Do you want to change it (y/n)? ");
if (Console.ReadLine().ToLower() == "y")
{
current.Tel_no = input.ReadTelNo();
}
//Add_at_index(current, index); greseala undeva
pBook[index] = current;
current.Print();
} //EditRecord(string name)
public void Import(string file_content)
{
bool new_records = false;
string[] records_row;
char separator = ';';
string[] found_rec;
records_row = file_content.Split('n');
if (records_row == null) return; //empty file (or file not found)
foreach (string row in records_row)
{
try
{
found_rec = row.Split(separator);
if (found_rec.Length != 4) continue; //invalid record
pBook.Add(new record(found_rec[0], found_rec[1], found_rec[2], DateTime.Parse(found_rec[3])));
new_records = true; // records found
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
if (new_records) Console.WriteLine("{0} record(s) loaded from file!", pBook.Count);
} // Import(string file_content)
public string Export()
{
string content = "";
foreach (record curent in pBook)
{
content += curent.FName + ";" + curent.SName + ";"
+ curent.Tel_no + ";" + curent.EntryData + Environment.NewLine;
}
return content;
} // Export() - export curent agenda (arraylist) to a string (to be write in a file)!
}
}

Urmeaza un nou fisier: record.cs care are functia de a defini ce inseamna record. codul este urmatorul:

Cod:
using System;
using System.Collections;

namespace agenda
{
class record
{
private string fName;
private string sName;
private string tel_no;
private DateTime entryData;
public string FName
{
get { return fName; }
set
{
string name = value.Trim();
if (name == "") throw new Exception("Name cannot be void");
fName = name;
}
}
public string SName
{
get { return sName; }
set
{
string name = value.Trim();
if (name == "") throw new Exception("Second Name cannot be void");
sName = name;
}
}
public string Tel_no
{
get { return tel_no; }
set
{
string no = value.Trim();
if (no == "") throw new Exception("Empty Phone Number");
for (int i = 0; i < no.Length; ++i)
if (no[i] < '0' || no[i] > '9')
throw new Exception("Phone numer must contain only digits. Invalid entery at pos " + (i+1));
tel_no = no;
}
}
public DateTime EntryData
{
get { return entryData; }
set { entryData = value; }
}
public record(string fname, string sname, string tel, DateTime dt)
{
FName = fname;
SName = sname;
Tel_no = tel;
EntryData = dt;
}
public record(string fname, string sname, string tel)
: this(fname, sname, tel, DateTime.Now)
{
}
public void Print()
{
Console.WriteLine("{0} [{1}]", ToString(), EntryData);
}
public override string ToString()
{
return FName + " " + SName + " - " + Tel_no;
}
}
}

Un ultim fisier, input.cs, are rolul de "helper"... sunt functii care au sarcina de a comunica (in si out) cu utilizatorul (citeste date, exporta date, importa.. etc). codul este:

Cod:
using System;
using System.Collections;
using System.IO;

namespace agenda
{
class input
{
public static string ReadFirstName()
{
string fn;
while(true)
{
Console.Write("First Name: ");
fn = Console.ReadLine();
fn = fn.Trim();
if (fn == "")
{
Console.WriteLine("Invalid input. Name cannot be empty");
continue;
}
if (fn.Length > 12) fn = fn.Substring(0, 12);
return fn;
}
} //ReadFirstName()
public static string ReadSecName()
{
string sn;
while (true)
{
Console.Write("Second Name: ");
sn = Console.ReadLine();
sn = sn.Trim();
if (sn == "")
{
Console.WriteLine("Invalid input. Second Name cannot be empty");
continue;
}
if (sn.Length > 12) sn = sn.Substring(0, 12);
return sn;
}
} //ReadSecName()
public static string ReadTelNo()
{
string no;
bool IsValidNo;
while (true)
{
IsValidNo = true;
Console.Write("Phone no: ");
no = Console.ReadLine();
no = no.Trim();
if (no == "")
{
Console.WriteLine("Invalid input. Tel number cannot be empty");
continue;
}
if (no.Length > 12)
{
Console.WriteLine("Invalid input. Phone Number cannot have more than 12 digits");
continue;
}
for (int i = 0; i < no.Length; ++i)
if (no[i] < '0' || no[i] > '9')
{
Console.WriteLine("Phone numer must contain only digits. Invalid entery at pos " + (i + 1));
IsValidNo = false;
break;
}
if (IsValidNo)
return no;
}
} //ReadTelNo()
public static record ReadNewRecord()
{
return new record(ReadFirstName(), ReadSecName(), ReadTelNo());
} //ReqadNewRecord()

public static string ReadFromFile()
{
string file_content = "";
try
{
StreamReader sr = new StreamReader("./agenda.txt");
file_content = sr.ReadToEnd();
sr.Close();
}
catch (Exception)
{
}
Console.WriteLine(file_content); //to remove after tests
return file_content;
}
}
class output
{
public static int DoMenu(int Counter)
{
string rec_no = "";
string user_chose;
if (Counter > 0) rec_no = Counter.ToString() + " record(s)"; else rec_no = "No records";
Console.WriteLine("nAgenda v.1.0 - " + rec_no + "n-----------------------------");
Console.WriteLine("1. Print Agenda");
Console.WriteLine("2. Add Record");
Console.WriteLine("3. Edit Record");
Console.WriteLine("4. Delete Record");
Console.WriteLine("0. Exit");
Console.WriteLine();
Console.Write("You chose: ");
while (true)
{
user_chose = Console.ReadLine();
if (user_chose == "0" || user_chose == "1" || user_chose == "2" || user_chose == "3" || user_chose == "4")
return int.Parse(user_chose);
Console.WriteLine("Wrong choice! Try again!");
Console.Write("Your choice: ");
}
} //DoMenu(int Counter)
public static void WriteToFile(string content)
{
try
{
StreamWriter sw = new StreamWriter("./agenda.txt", false);
sw.Write(content);
Console.WriteLine("Saved succesfuly!");
sw.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
} //WriteToFile(string content) - write a string to file
}
}

Am postat acest articol (poate are si elemente de tutorial - desi am cam sarit comentariile) in sperantza ca va fi de folos cuiva.

    Blog din Moldova    FastCounter 

 
Copyright © 2008-2010 Foster1. All rights reserved.