/// <summary>Asks the details for adding.</summary> /// <param name="addressBookName">Name of the address book.</param> /// <returns> /// <br /> /// </returns> private static string[] AskDetailsForAdding(string addressBookName) { label2: string[] personDetail = new string[9]; personDetail[0] = addressBookName; CustomPrint.PrintInRed($"Address Book Name : {addressBookName}", true); Console.Write("First Name : "); personDetail[1] = Console.ReadLine(); Console.Write("Second Name : "); personDetail[2] = Console.ReadLine(); if (SearchDublicates(personDetail[1], personDetail[2], addressBookName)) { CustomPrint.PrintInMagenta("This Person is already in " + addressBookName + " Address Book\nTry to add another", true); goto label2; } Console.Write("Address : "); personDetail[3] = Console.ReadLine(); Console.Write("City : "); personDetail[4] = Console.ReadLine(); Console.Write("State : "); personDetail[5] = Console.ReadLine(); Console.Write("Zip : "); personDetail[6] = Console.ReadLine(); Console.Write("Phone Number : "); personDetail[7] = Console.ReadLine(); Console.Write("Email Id : "); personDetail[8] = Console.ReadLine(); return(personDetail); }
/// <summary>Updates the contact.</summary> /// <param name="objAddressBook">The object address book.</param> public static bool UpdateContactInDB(AddressBookModel objAddressBook) { try { using (SqlConnection connection = new SqlConnection(connetionString)) { SqlCommand command = new SqlCommand($"update people_contact set Address = '{objAddressBook.Address}',City = '{objAddressBook.City}',State ='{objAddressBook.State}',Zipcode = '{objAddressBook.Zip}',PhoneNumber ='{objAddressBook.PhoneNo}',Email ='{objAddressBook.Email}' where FirstName= '{objAddressBook.FirstName}' and LastName = '{objAddressBook.LastName}'", connection); connection.Open(); int result = command.ExecuteNonQuery(); CustomPrint.PrintInRed($"{result} rows affected"); connection.Close(); if (result >= 1) { return(true); } throw new AddressBookException(AddressBookException.ExceptionType.CONTACT_NOT_FOUND, "Contact not found"); } } catch (AddressBookException ae) { CustomPrint.PrintInMagenta(ae.Message); return(false); } catch (Exception e) { CustomPrint.PrintInMagenta(e.Message); return(false); } }
/// <summary>Deletes the contact.</summary> /// <param name="addressBookName">Name of the address book.</param> public static void DeleteContact(string addressBookName) { //gets First Name And Second Name from User using string[] name = AskDetailForDeletingOrEditing(addressBookName, "Delete"); string fName = name[0]; string sName = name[1]; bool personFound = false; AddressBookModel personToDelete = new AddressBookModel(); //loops through contacts where First Name,Second Name and AddressBookName get matched Func <AddressBookModel, bool> condition = item => ((item.FirstName).ToLower() == fName.ToLower() && (item.LastName).ToLower() == sName.ToLower() && item.AddressBookName == addressBookName); foreach (AddressBookModel item in listContacts.Where(condition)) { personToDelete = item; personFound = true; break; } //Removes the Contacts if person found if (personFound && AddressBookDBWork.DeleteContactFromDB(personToDelete)) { listContacts.Remove(personToDelete); CustomPrint.PrintInRed("Person removed from Contacts in " + addressBookName, false); } //Gives error if person not found else { CustomPrint.PrintInMagenta("Person not found", false); } }
//For validating AddressBookName and person details public static bool Validate(object obj) { ValidationContext context = new ValidationContext(obj); List <ValidationResult> results = new List <ValidationResult>(); bool valid = Validator.TryValidateObject(obj, context, results, true); if (!valid) { foreach (ValidationResult TotalResult in results) { try { throw new AddressBookException(AddressBookException.ExceptionType.INCORRECT_DETAIL, $"Error Msg : {TotalResult.ErrorMessage}"); } catch (AddressBookException ae) { CustomPrint.PrintInMagenta(ae.Message); } } CustomPrint.PrintInMagenta($"Try Again"); return(false); } else { return(true); } }
/// <summary>Adds the contacts.</summary> /// <param name="addressBookName">Name of the address book.</param> public static void AddContacts(string addressBookName) { //Creates new Contact object by getting personDeatils from AskDetailsForAdding AddressBookModel objContacts = new AddressBookModel(AskDetailsForAdding(addressBookName)); //Adds objContact to listContacts if objContacts is valid if (AddressBookDetailsValidation.Validate(objContacts)) { objContacts.DateAdded = DateTime.Now; if (AddressBookDBWork.AddContactToDB(objContacts)) { listContacts.Add(objContacts); CustomPrint.PrintInRed($"Contact has been Added to {addressBookName}", false); } else { CustomPrint.PrintInMagenta($"Contact has not been Added to", false); } } //Given Error if objContacts is invalid else { CustomPrint.PrintInMagenta($"Contact has not been Added to", false); AddContacts(addressBookName); } }
public static void Main() { CustomPrint.PrintInRed("*****Welcome to Address Book Program*****", false); //For storing saved data from file in listContacts AddressBookDBWork.StoreAllContactsToList(); //Calling AddressBook Method for Choosing Option WorkingOnAddressBook.AddressBook(); }
//Write in JSON File public static void WriteAddressBookJSON() { string path = @"F:\MyPrograms\Assignments\A4-AddressBook\AddressBookSystem\AddressBookSystem\Utility\AddressBook.json"; JsonSerializer jsonSerializer = new JsonSerializer(); using (StreamWriter streamWriter = new StreamWriter(path)) using (JsonWriter writer = new JsonTextWriter(streamWriter)) { SortContacts.SortOnConditionChooses(Contacts.listContacts); jsonSerializer.Serialize(writer, Contacts.listContacts); CustomPrint.PrintInRed("Saved Data Successfully"); } }
/// <summary>Retirves alls the contacts in given date range.</summary> public static void AllContactsInGivenDateRange() { try { DateTime[] dates = AskForDateRange(); AddressBookDBWork.GetContactInGivenDateRange(dates[0], dates[1]); } catch (Exception e) { CustomPrint.PrintInMagenta(e.Message + "\nTry Again"); AllContactsInGivenDateRange(); } }
/// <summary>Gets the state of the contacts in given.</summary> /// <param name="state">The state.</param> /// <returns> /// <br /> /// </returns> /// <exception cref="AddressBookException">No Contacts in Given State</exception> public static bool GetContactsInGivenState(string state) { try { AddressBookModel addressBookObj = new AddressBookModel(); using (SqlConnection connection = new SqlConnection(connetionString)) { SqlCommand command = new SqlCommand($"select AddressBookName, pc.FirstName,pc.LastName,Address,City,State,Zipcode,PhoneNumber,Email,date_added " + $"from address_book_person_name adp inner join people_contact pc " + $"on adp.FirstName = pc.FirstName and adp.LastName = pc.LastName " + $"where State = '{state}'", connection); connection.Open(); SqlDataReader dr = command.ExecuteReader(); if (dr.HasRows) { CustomPrint.PrintInRed($"All Contacts from DB in state {state}"); CustomPrint.PrintDashLine(); Console.WriteLine(CustomPrint.PrintRow("AddressBookName", "Name", "Address", "City", "State", "Zip", "PhoneNo", "Email", "Date Added")); CustomPrint.PrintDashLine(); while (dr.Read()) { addressBookObj.AddressBookName = dr.GetString(0); addressBookObj.FirstName = dr.GetString(1); addressBookObj.LastName = dr.GetString(2); addressBookObj.Address = dr.GetString(3); addressBookObj.City = dr.GetString(4); addressBookObj.State = dr.GetString(5); addressBookObj.Zip = dr.GetString(6); addressBookObj.PhoneNo = dr.GetString(7); addressBookObj.Email = dr.GetString(8); addressBookObj.DateAdded = dr.GetDateTime(9); Console.WriteLine(addressBookObj); } CustomPrint.PrintDashLine(); connection.Close(); return(true); } throw new AddressBookException(AddressBookException.ExceptionType.No_DATA, "No Contacts in Given State"); } } catch (AddressBookException e) { CustomPrint.PrintInMagenta(e.Message); return(false); } catch (Exception e) { CustomPrint.PrintInMagenta(e.Message); return(false); } }
/// <summary>View all contacts in DB.</summary> public static void AllContacts() { //For Sorting Accoring to sorting type choosed SortContacts.SortOnConditionChooses(Contacts.listContacts); CustomPrint.PrintInRed($"All Contacts in every address book"); CustomPrint.PrintDashLine(); Console.WriteLine(CustomPrint.PrintRow("AddressBookName", "Name", "Address", "City", "State", "Zip", "PhoneNo", "Email", "Date Added")); CustomPrint.PrintDashLine(); foreach (AddressBookModel item in listContacts) { Console.WriteLine(item); } CustomPrint.PrintDashLine(); }
/// <summary>Edits the contact.</summary> /// <param name="addressBookName">Name of the address book.</param> public static void EditContact(string addressBookName) { //gets First Name And Second Name from User using string[] name = AskDetailForDeletingOrEditing(addressBookName, "Edit"); string fName = name[0]; string sName = name[1]; bool personFound = false; //loops through contacts where First Name,Second Name and AddressBookName get matched Func <AddressBookModel, bool> condition = item => ((item.FirstName).ToLower() == fName.ToLower() && (item.LastName).ToLower() == sName.ToLower() && item.AddressBookName == addressBookName); foreach (AddressBookModel item in listContacts.Where(condition)) { Console.Write("New Address : "); item.Address = Console.ReadLine(); Console.Write("New City : "); item.City = Console.ReadLine(); Console.Write("New State : "); item.State = Console.ReadLine(); Console.Write("New Address : "); item.Zip = Console.ReadLine(); //For having Valid Phone No while (true) { Console.Write("New Phone Number : "); item.PhoneNo = Console.ReadLine(); if (AddressBookDetailsValidation.Validate(item)) { break; } } //For having Valid Email while (true) { Console.Write("New Email : "); item.Email = Console.ReadLine(); if (AddressBookDetailsValidation.Validate(item)) { break; } } personFound = true; AddressBookDBWork.UpdateContactInDB(item); CustomPrint.PrintInRed("Details have been updated in " + addressBookName, false); } if (personFound == false) { CustomPrint.PrintInMagenta("Person not found"); } }
//Read from CSV file public static void ReadAddressBookCSV() { string path = @"F:\MyPrograms\Assignments\A4-AddressBook\AddressBookSystem\AddressBookSystem\Utility\AddressBook.csv"; using (var reader = new StreamReader(path)) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { var records = csv.GetRecords <AddressBookModel>().ToList(); CustomPrint.PrintInRed("Read Data Successfully from address book CSV"); foreach (AddressBookModel personDetail in records) { Console.WriteLine(personDetail); } } }
//Read txt file public static void ReadAddressBook() { string path = @"F:\MyPrograms\Assignments\A4-AddressBook\AddressBookSystem\AddressBookSystem\Utility\AddressBook.txt"; using (StreamReader sr = File.OpenText(path)) { CustomPrint.PrintInRed($"Saved Address Book Details in TXT file"); string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } sr.Close(); } }
//Write into txt file public static void WriteAddressBook() { string path = @"F:\MyPrograms\Assignments\A4-AddressBook\AddressBookSystem\AddressBookSystem\Utility\AddressBook.txt"; using (StreamWriter sr = File.AppendText(path)) { SortContacts.SortOnConditionChooses(Contacts.listContacts); foreach (AddressBookModel personDetails in Contacts.listContacts) { sr.WriteLine(personDetails); } sr.Close(); CustomPrint.PrintInRed("Address Book Txt file has been Appended", false); } }
//Read from JSON File public static void ReadAddressBookJSON() { string path = @"F:\MyPrograms\Assignments\A4-AddressBook\AddressBookSystem\AddressBookSystem\Utility\AddressBook.json"; IList <AddressBookModel> addressDatas = JsonConvert.DeserializeObject <IList <AddressBookModel> >(File.ReadAllText(path)); CustomPrint.PrintInRed("Read Data Successfully"); CustomPrint.PrintDashLine(); Console.WriteLine(CustomPrint.PrintRow("AddressBookName", "Name", "Address", "City", "State", "Zip", "PhoneNo", "Email")); CustomPrint.PrintDashLine(); foreach (AddressBookModel personDetail in addressDatas) { Console.WriteLine(personDetail); } CustomPrint.PrintDashLine(); WriteAddressBookCSV(); }
/// <summary>Asks the detail for deleting or editing.</summary> /// <param name="addressBookName">Name of the address book.</param> /// <param name="func">The function.</param> /// <returns> /// <br /> /// </returns> private static string[] AskDetailForDeletingOrEditing(string addressBookName, string func) { string[] name = new string[2]; if (func == "Delete") { CustomPrint.PrintInRed($"Delete Contact in {addressBookName}"); } else { CustomPrint.PrintInMagenta($"Edit Contact in {addressBookName}"); } Console.Write("First Name : "); name[0] = Console.ReadLine(); Console.Write("Second Name : "); name[1] = Console.ReadLine(); return(name); }
/// <summary>Adds the contact to database.</summary> /// <param name="addressBookObj">The address book object.</param> /// <returns> /// <br /> /// </returns> public static bool AddContactToDB(AddressBookModel addressBookObj) { bool result; try { SqlTransaction objTrans = null; using (SqlConnection connection = new SqlConnection(connetionString)) { connection.Open(); objTrans = connection.BeginTransaction(); SqlCommand command1 = new SqlCommand($"insert into people_contact values" + $"('{addressBookObj.FirstName}','{addressBookObj.LastName}','{addressBookObj.Address}','" + $"{addressBookObj.City}','{addressBookObj.State}','{addressBookObj.Zip}','{addressBookObj.PhoneNo}','" + $"{addressBookObj.Email}','{addressBookObj.DateAdded.Year}-{addressBookObj.DateAdded.Month}-{addressBookObj.DateAdded.Day}')", connection, objTrans); SqlCommand command2 = new SqlCommand($"insert into address_book_person_name values" + $"('{addressBookObj.AddressBookName}','{addressBookObj.FirstName}','{addressBookObj.LastName}')", connection, objTrans); try { int noOfRow1 = command1.ExecuteNonQuery(); int noOfRow2 = command2.ExecuteNonQuery(); objTrans.Commit(); CustomPrint.PrintInRed($"{noOfRow2} rows affected"); result = true; } catch (Exception e) { CustomPrint.PrintInMagenta(e.Message); objTrans.Rollback(); result = false; } finally { connection.Close(); } } } catch (Exception e) { CustomPrint.PrintInMagenta(e.Message); result = false; } return(result); }
/// <summary>Retrives all contacts from database.</summary> /// <returns></returns> public static bool RetriveAllContactsFromDB() { try { AddressBookModel addressBookObj = new AddressBookModel(); using (SqlConnection connection = new SqlConnection(connetionString)) { SqlCommand command = new SqlCommand("RetriveContacts", connection); command.CommandType = System.Data.CommandType.StoredProcedure; connection.Open(); SqlDataReader dr = command.ExecuteReader(); if (dr.HasRows) { CustomPrint.PrintInRed("All Contacts from DB"); CustomPrint.PrintDashLine(); Console.WriteLine(CustomPrint.PrintRow("AddressBookName", "Name", "Address", "City", "State", "Zip", "PhoneNo", "Email", "Date Added")); CustomPrint.PrintDashLine(); while (dr.Read()) { addressBookObj.AddressBookName = dr.GetString(0); addressBookObj.FirstName = dr.GetString(1); addressBookObj.LastName = dr.GetString(2); addressBookObj.Address = dr.GetString(3); addressBookObj.City = dr.GetString(4); addressBookObj.State = dr.GetString(5); addressBookObj.Zip = dr.GetString(6); addressBookObj.PhoneNo = dr.GetString(7); addressBookObj.Email = dr.GetString(8); addressBookObj.DateAdded = dr.GetDateTime(9); Console.WriteLine(addressBookObj); } CustomPrint.PrintDashLine(); } connection.Close(); return(true); } } catch (Exception e) { CustomPrint.PrintInMagenta(e.Message); return(false); } }
/// <summary>Views All contacts in same state or city for all address book.</summary> public static void SearchPersonByCityOrState() { //For Sorting Accoring to sorting type choosed SortContacts.SortOnConditionChooses(Contacts.listContacts); //For counting no of people in same city/state int slNo = 0; Console.Write("Enter City : "); string city = Console.ReadLine(); Console.Write("Enter State : "); string state = Console.ReadLine(); CustomPrint.PrintInRed("Search by City " + city + " are :\n"); CustomPrint.PrintDashLine(); Console.WriteLine(CustomPrint.PrintRow("AddressBookName", "Name", "Address", "City", "State", "Zip", "PhoneNo", "Email", "Date Added")); CustomPrint.PrintDashLine(); foreach (AddressBookModel personDetails in listContacts.Where(x => (x.City.ToLower().Equals(city.ToLower()) && x.State.ToLower().Equals(state.ToLower())))) { Console.WriteLine(personDetails); slNo++; } CustomPrint.PrintDashLine(); Console.WriteLine("\nCount by City is : " + slNo); CustomPrint.PrintInRed("Search by State " + state + " are :\n"); CustomPrint.PrintDashLine(); Console.WriteLine(CustomPrint.PrintRow("AddressBookName", "Name", "Address", "City", "State", "Zip", "PhoneNo", "Email", "Date Added")); CustomPrint.PrintDashLine(); slNo = 0; foreach (AddressBookModel personDetails in listContacts) { if (personDetails.State.Equals(state)) { Console.WriteLine(personDetails); slNo++; } } CustomPrint.PrintDashLine(); Console.WriteLine("\nCount by State is : " + slNo); }
/// <summary>Stores all contacts to list.</summary> public static void StoreAllContactsToList() { try { using (SqlConnection connection = new SqlConnection(connetionString)) { SqlCommand command = new SqlCommand("RetriveContacts", connection); command.CommandType = System.Data.CommandType.StoredProcedure; connection.Open(); SqlDataReader dr = command.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { AddressBookModel addressBookObj = new AddressBookModel(); addressBookObj.AddressBookName = dr.GetString(0); addressBookObj.FirstName = dr.GetString(1); addressBookObj.LastName = dr.GetString(2); addressBookObj.Address = dr.GetString(3); addressBookObj.City = dr.GetString(4); addressBookObj.State = dr.GetString(5); addressBookObj.Zip = dr.GetString(6); addressBookObj.PhoneNo = dr.GetString(7); addressBookObj.Email = dr.GetString(8); addressBookObj.DateAdded = dr.GetDateTime(9); Contacts.listContacts.Add(addressBookObj); } } connection.Close(); } } catch (Exception e) { CustomPrint.PrintInMagenta(e.Message); } }
/// <summary>Deletes the contact from database.</summary> /// <param name="addressBookObj">The address book object.</param> /// <returns> /// <br /> /// </returns> public static bool DeleteContactFromDB(AddressBookModel addressBookObj) { bool result; try { using (SqlConnection connection = new SqlConnection(connetionString)) { connection.Open(); SqlCommand command = new SqlCommand($"delete from people_contact " + $"where FirstName = '{addressBookObj.FirstName}' and LastName = '{addressBookObj.LastName}'", connection); int noOfRow = command.ExecuteNonQuery(); CustomPrint.PrintInRed($"{noOfRow} rows affected"); result = true; connection.Close(); } } catch (Exception e) { CustomPrint.PrintInMagenta(e.Message); result = false; } return(result); }
private static void ActionWithGivenKey(int key, WorkingOnAddressBook addressBookObj) { switch (key) { //For Adding the contact case 1: Contacts.AddContacts(addressBookObj.AddressBookName); WorkAddressBook(addressBookObj); break; //For Editing the Contacts case 2: Contacts.DeleteContact(addressBookObj.AddressBookName); WorkAddressBook(addressBookObj); break; case 3: Contacts.EditContact(addressBookObj.AddressBookName); WorkAddressBook(addressBookObj); break; //For opening new/saved address book case 4: AddressBook(); break; //Search By city/state case 5: Contacts.SearchPersonByCityOrState(); WorkAddressBook(addressBookObj); break; //Sort by Name case 6: SortContacts.sortType = SortContacts.SortingType.SORT_BY_NAME; CustomPrint.PrintInRed($"Sort by Name Selected"); WorkAddressBook(addressBookObj); break; //Sort by City case 7: SortContacts.sortType = SortContacts.SortingType.SORT_BY_CITY; CustomPrint.PrintInRed($"Sort by City Selected"); WorkAddressBook(addressBookObj); break; //Sort by State case 8: SortContacts.sortType = SortContacts.SortingType.SORT_BY_STATE; CustomPrint.PrintInRed($"Sort by State Selected"); WorkAddressBook(addressBookObj); break; //Sort by Zip case 9: SortContacts.sortType = SortContacts.SortingType.SORT_BY_ZIP; CustomPrint.PrintInRed($"Sort by Zip Selected"); WorkAddressBook(addressBookObj); break; //View All Contacts case 10: Contacts.AllContactsInSameAddressBook(addressBookObj.AddressBookName); WorkAddressBook(addressBookObj); break; //Read JSON File case 11: Contacts.AllContacts(); WorkAddressBook(addressBookObj); break; //Exit case 12: Contacts.AllContactsInGivenDateRange(); WorkAddressBook(addressBookObj); break; case 13: break; default: CustomPrint.PrintInMagenta("Try Again. Wrong key"); WorkAddressBook(addressBookObj); break; } }
public override string ToString() { string name = FirstName + " " + LastName; return(CustomPrint.PrintRow(AddressBookName, name, Address, City, State, Zip, PhoneNo, Email, DateAdded.ToShortDateString())); }