ContactBook console based app
Clash Royale CLAN TAG#URR8PPP
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;
up vote
0
down vote
favorite
I wrote this simple contact book app. It helps the user to store and retrieve contact information. The app uses a SQL database server to store all the user data. One significant fact is that the db and its table are only created when the user uses the application for the first time. Moreover, this app can log error information in a local .log file(it's possible to send the log file to the developer as well, if required(though not implemented in this project)). I've tried to apply my limited understanding of different concepts of core C#. I'd appreciate if someone(an experienced c# developer, if possible) to point out the mistakes that I have made and suggest how I could optimize this app. A non-related Question: is it possible to write this project exactly in C++?
PhoneBookAppCore.cs
/*Written by AJ*/
using System;
using System.Threading;
namespace PhoneBook
class PhoneBookAppCore
private static readonly InputEngine _inputEngline = new InputEngine();
private static readonly SqlEngine _sqlEngine = new SqlEngine();
/// <summary>
/// Wrapper func: checks if an entry exists in the db table
/// </summary>
/// <param name="keyword"></param>
/// <param name="show"></param>
/// <returns></returns>
private static Tuple<string,string,bool> ExistInDbWrapper(string keyword, bool show=true)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
var searchTuple = _inputEngline.SearchInit(keyword);
bool exists = _sqlEngine.ExistInDbServer(searchTuple.Item1, searchTuple.Item2);
if (show is true) Console.WriteLine(exists ? Constants.ExistInDbWrapper01 : Constants.ExistInDbWrapper02);
Thread.Sleep(Constants.ConstIntArray[4]);
return new Tuple<string, string, bool>(searchTuple.Item1, searchTuple.Item2, exists);
/// <summary>
/// Wrapper func: checks if an entry exists in the db table
/// </summary>
/// <param name="searchKeyword"></param>
/// <param name="updateKeyword"></param>
/// <returns></returns>
private static Tuple<string, string,string,string, bool> ExistInDbWrapper(string searchKeyword, string updateKeyword)
var searchTuple = ExistInDbWrapper(searchKeyword);
if (searchTuple.Item3 is false) return new Tuple<string, string, string, string, bool>(null,null,null,null,searchTuple.Item3);
var updateTuple = ExistInDbWrapper(updateKeyword, show:false);
Thread.Sleep(Constants.ConstIntArray[4]);
return new Tuple<string, string, string,string,bool>(updateTuple.Item1,updateTuple.Item2,searchTuple.Item1,searchTuple.Item2,searchTuple.Item3);
/// <summary>
/// Use this to run this app
/// </summary>
public void Run()
try
Init(Constants.Dbname, Constants.TableName);
//Display cover menu
OutputEngine outputEngine = new OutputEngine();
outputEngine.DisplayCoverMenu();
bool continueProgram = true;
while (continueProgram)
//display main menu
int userChoice = outputEngine.DisplayMainMenu();
switch (userChoice)
case 1:
CreateNewContact();
break;
case 2:
var dataTuple = ExistInDbWrapper(Constants.Run01);
if (dataTuple.Item3 is false) break;
else SearchContact(dataTuple.Item1, dataTuple.Item2);
dataTuple = null;
break;
case 3:
var dataTupleUpdate = ExistInDbWrapper(Constants.Run01, Constants.Run02);
if (dataTupleUpdate.Item5 is false) break;
else ModifyContact(dataTupleUpdate.Item1, dataTupleUpdate.Item2, dataTupleUpdate.Item3, dataTupleUpdate.Item4);
dataTupleUpdate = null;
break;
case 4:
dataTuple = ExistInDbWrapper(Constants.Run03);
if (dataTuple.Item3 is false) break;
else DeleteContact(dataTuple.Item1, dataTuple.Item2);
dataTuple = null;
break;
case 5:
continueProgram = false;
break;
catch (Exception e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
finally
Console.Clear();
Console.WriteLine(Constants.ErrorGlobalMessage);
Thread.Sleep(Constants.ConstIntArray[5]);
Exit(Constants.FailedExitCore);
/// <summary>
/// Wrapper func: searches an entry and displays result
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
private static void SearchContact(string searchKey, string searchValue)
string dataArr = _sqlEngine.ReadFromDbServer(searchKey, searchValue);
OutputEngine outputEEngineForDisplay = new OutputEngine();
outputEEngineForDisplay.SetProperties(outputEEngineForDisplay, dataArr);
outputEEngineForDisplay.DisplayPhoneBook();
Console.ReadKey();
/// <summary>
/// Wrapper func: modifies an existing db entry
/// </summary>
/// <param name="updateKey"></param>
/// <param name="updateValue"></param>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
private static void ModifyContact(string updateKey, string updateValue, string searchKey, string searchValue)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.UpdateDbServer(updateKey, updateValue, searchKey, searchValue);
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Wrapper func: deletes an entry from db
/// </summary>
/// <param name="deleteKey"></param>
/// <param name="deleteValue"></param>
private static void DeleteContact(string deleteKey, string deleteValue)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.DeleteFromDbServer(deleteKey, deleteValue);
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Wrapper func: terminates an running app
/// </summary>
/// <param name="exitCode">S</param>
private static void Exit(int exitCode)
Environment.Exit(exitCode: exitCode);
/// <summary>
/// Wrapper func: creates new db table entries
/// </summary>
private static void CreateNewContact()
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.WriteToDbServer(_inputEngline.AddSingleQuote(_inputEngline.UserInput()));
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Checks if a db and db tables exists or not; if no db or tb table, then creates them in the server
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
private static void Init(string dbName, string tableName)
bool isDbExists = _sqlEngine.ExistsDbInServer(dbName);
bool isTabExists = _sqlEngine.ExistsTableInDbInServer(tableName);
if (isDbExists is false && isTabExists is false)
_sqlEngine.CreateDbInServer(dbName);
_sqlEngine.CreateTableInDbServer(dbName, tableName);
else return;
SqlEngine.cs
/*Written by AJ*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
namespace PhoneBook // Constants.(fildname) could be simplified to only fildname since class SqlEngine inherits from class Constants
class SqlEngine : Constants //this inheritance is to gain access to protected sql command texts
private string _connectionStringWithDbname = Constants.ConnectionStringWithDbname;
private string _connectionString = Constants.ConnectionString;
/// <summary>
/// Enables conn with a db in the sql server
/// </summary>
/// <param name="connStr"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
private SqlConnection CreteDbLink(string connStr)
SqlConnection conn = new SqlConnection(connStr);
return conn;
/// <summary>
/// Inserts entry values in the db table
/// </summary>
/// <param name="dataArr"></param>
/// <exception cref="SqlException"></exception>
public void WriteToDbServer(string dataArr)
VoidFuncHelper(Constants.WriteCommText + String.Join(Constants.WriteToDbServer01, dataArr) + Constants.WriteToDbServer02, this._connectionStringWithDbname); // this string consists of one protected const string and two public const string
/// <summary>
/// Updates value of an entry in the db table
/// </summary>
/// <param name="updateKey"></param>
/// <param name="updateValue"></param>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <exception cref="SqlException"></exception>
public void UpdateDbServer(string updateKey, string updateValue, string searchKey, string searchValue)
VoidFuncHelper(String.Format(Constants.UpdateCommText, updateKey, updateValue, searchKey, searchValue), this._connectionStringWithDbname);
/// <summary>
/// Retrieves string array of searched entry from db
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public string ReadFromDbServer(string searchKey, string searchValue)
string readCommStr = String.Format(Constants.ReadCommText, searchKey, searchValue);
List<string> rawDataList = new List<string>();
SqlConnection conn = CreteDbLink(this._connectionStringWithDbname);
using (conn)
conn.Open();
SqlCommand sqlCommand = new SqlCommand(readCommStr, conn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) foreach (int i in Enumerable.Range(Constants.ConstIntArray[0], Constants.ConstIntArray[1])) rawDataList.Add(reader.GetValue(i).ToString());
conn.Close();
return rawDataList.ToArray();
/// <summary>
/// Checks if an entry exists in db table
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistInDbServer(string searchKey, string searchValue)
return BoolFuncHelper(String.Format(Constants.ExistsCommText, searchKey, searchValue), this._connectionStringWithDbname);
/// <summary>
/// Deletes the value of a searched entry from db table
/// </summary>
/// <param name="deleteKey"></param>
/// <param name="deleteValue"></param>
/// <exception cref="SqlException"></exception>
public void DeleteFromDbServer(string deleteKey, string deleteValue)
VoidFuncHelper(String.Format(Constants.DeleteCommText, deleteKey, deleteValue), this._connectionStringWithDbname);
/// <summary>
/// Checks if a db exists in the server
/// </summary>
/// <param name="dbName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsDbInServer(string dbName)
return BoolFuncHelper(String.Format(Constants.ExistsDbInServerExistCommText, dbName), this._connectionString);//only db exists or not
/// <summary>
/// Checks if a table exists in the db server
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsTableInDbInServer(string tableName)
return BoolFuncHelper(String.Format(Constants.ExistsTableInDbInServerExistCommText, tableName), this._connectionString); //look out could be this._connectionStringWithDbname
/// <summary>
/// returns True if both db and table exist in the server
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsBothDbAndTable(string dbName, string tableName)
return BoolFuncHelper(String.Format(Constants.ExistsBothDbAndTableExistCommText, dbName, tableName), this._connectionStringWithDbname);
/// <summary>
/// Creates a db in the sql server
/// </summary>
/// <param name="dbName"></param>
/// <exception cref="SqlException"></exception>
public void CreateDbInServer(string dbName)
VoidFuncHelper(String.Format(Constants.CreateDbInServerCommText, dbName), this._connectionString);
/// <summary>
/// Deletes a db from the sql server
/// </summary>
/// <param name="dbName"></param>
/// <exception cref="SqlException"></exception>
public void DeleteDbInServer(string dbName)
VoidFuncHelper(String.Format(Constants.DeleteDbInServerCommText, dbName), this._connectionString);
/// <summary>
/// Creates a table in the specified db
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <exception cref="SqlException"></exception>
public void CreateTableInDbServer(string dbName, string tableName)
VoidFuncHelper(String.Format(Constants.CreateTableInDbServerCommText, dbName, tableName), this._connectionString); //look out could be this._connectionStringWithDbname
/// <summary>
/// Helper func : enables db conn
/// </summary>
/// <param name="commStr"></param>
/// <param name="connStr"></param>
/// <returns>bool value from the executed sql command</returns>
/// <exception cref="SqlException"></exception>
private bool BoolFuncHelper(string commStr, string connStr)
bool exist = false;
SqlConnection conn = CreteDbLink(connStr);
try
using (conn)
conn.Open();
SqlCommand sqlCommand = new SqlCommand(commStr, conn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) exist = (reader.GetValue(Constants.ConstIntArray[0]).ToString() == Constants.OceStr ? true : false);
conn.Close();
catch (SqlException e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
Environment.Exit(Constants.FailedExitCore);
return exist;
/// <summary>
/// Helper func : enables db connection and executes sql comm
/// </summary>
/// <param name="commStr"></param>
/// <param name="connStr"></param>
/// <exception cref="SqlException"></exception>
private void VoidFuncHelper(string commStr, string connStr)
try
using (SqlConnection conn = new SqlConnection(connStr))
conn.Open();
SqlCommand sqlCom = conn.CreateCommand();
sqlCom.CommandText = commStr;
sqlCom.ExecuteNonQuery();
conn.Close();
catch (SqlException e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
Environment.Exit(Constants.FailedExitCore);
OutputEngine.cs
/*Written by AJ*/
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;
using System.IO;
namespace PhoneBook
class OutputEngine
// list of default values of properties
private string _fName = String.Empty;
private string _lName = String.Empty;
private string _pNum = String.Empty;
private string _mNum = String.Empty;
private string _fNum = String.Empty;
private string _email = String.Empty;
private string _address = String.Empty;
// list of properties
public string FName get => this._fName; set => _fName = value;
public string LName get => this._lName; set => _lName = value;
public string PhoneNum get => this._pNum; set => _pNum = value;
public string MobileNum get => this._mNum; set => _mNum = value;
public string FaxNum get => this._fNum; set => _fNum = value;
public string Email get => this._email; set => _email = value;
public string Address get => this._address; set => _address = value;
/// <summary>
/// Assigns values to the properties of a class instance
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance"></param>
/// <param name="dataArr"></param>
public void SetProperties<T>(T instance, object dataArr) where T : class
Enumerable.Zip(instance.GetType().GetRuntimeProperties(), dataArr, Tuple.Create).ToList().ForEach((tup) => tup.Item1.SetValue(instance, tup.Item2, null));
/// <summary>
/// Displays phonebook entries
/// </summary>
public void DisplayPhoneBook() // can someone suggest me to reduce/optimize the code, I wanna print only the value that is not NULL or String.Empty
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
string formatAll = String.Format(Constants.FormatAll, FName, LName, PhoneNum, MobileNum, FaxNum, Email, Address);
string formatOnlyPhone = String.Format(Constants.FormatOnlyPhone, FName, LName, PhoneNum);
string formatOnlyMobile = String.Format(Constants.FormatOnlyMobile, FName, LName, MobileNum);
string formatOnlyFax = String.Format(Constants.FormatOnlyFax, FName, LName, FaxNum);
string formatOnlyEmail = String.Format(Constants.FormatOnlyEmail, FName, LName, Email);
string formatOnlyAddress = String.Format(Constants.FormatOnlyAddress, FName, LName, Address);
string formatOnlyPhoneAndMobile = String.Format(Constants.FormatOnlyPhoneAndMobile, FName, LName, PhoneNum, MobileNum);
string formatOnlyPhoneAndFax = String.Format(Constants.FormatOnlyPhoneAndFax, FName, LName, PhoneNum, FaxNum);
string formatOnlyPhoneAndFaxAndEmail = String.Format(Constants.FormatOnlyPhoneAndFaxAndEmail, FName, LName, PhoneNum, FaxNum, Email);
string formatOnlyPhoneAndEmailAndAddress = String.Format(Constants.FormatOnlyPhoneAndEmailAndAddress, FName, LName, PhoneNum, Email, Address);
string formatOnlyPhoneAndFaxAndAddress = String.Format(Constants.FormatOnlyPhoneAndFaxAndAddress, FName, LName, PhoneNum, FaxNum, Address);
string formatOnlyPhoneAndEmail = String.Format(Constants.FormatOnlyPhoneAndEmail, FName, LName, PhoneNum, Email);
string formatOnlyPhoneAndAddress = String.Format(Constants.FormatOnlyPhoneAndAddress, FName, LName, PhoneNum, Address);
string formatOnlyMobileAndFax = String.Format(Constants.FormatOnlyMobileAndFax, FName, LName, MobileNum, FaxNum);
string formatOnlyMobileAndEmail = String.Format(Constants.FormatOnlyMobileAndEmail, FName, LName, MobileNum, Email);
string formatOnlyMobileAndEmailAndAddress = String.Format(Constants.FormatOnlyMobileAndEmailAndAddress, FName, LName, MobileNum, Email, Address);
string formatOnlyMobileAndFaxAndAddress = String.Format(Constants.FormatOnlyMobileAndFaxAndAddress, FName, LName, MobileNum, FaxNum, Address);
string formatOnlyMobileAndAddress = String.Format(Constants.FormatOnlyMobileAndAddress, FName, LName, MobileNum, Address);
string formatOnlyFaxAndEmail = String.Format(Constants.FormatOnlyFaxAndEmail, FName, LName, FaxNum, Email);
string formatOnlyFaxAndAddress = String.Format(Constants.FormatOnlyFaxAndAddress, FName, LName, FaxNum, Address);
string formatOnlyEmailAndAddress = String.Format(Constants.FormatOnlyEmailAndAddress, FName, LName, Email, Address);
string formatOnlyPhoneAndMobileAndFax = String.Format(Constants.FormatOnlyPhoneAndMobileAndFax, FName, LName, PhoneNum, MobileNum, FaxNum);
string formatOnlyPhoneAndMobileAndFaxAndEmail = String.Format(Constants.FormatOnlyPhoneAndMobileAndFaxAndEmail, FName, LName, PhoneNum, MobileNum, FaxNum, Email);
string formatOnlyPhoneAndMobileAndFaxAndAddress = String.Format(Constants.FormatOnlyPhoneAndMobileAndFaxAndAddress, FName, LName, PhoneNum, MobileNum, FaxNum, Address);
string formatOnlyPhoneAndMobileAndEmailAndAddress = String.Format(Constants.FormatOnlyPhoneAndMobileAndEmailAndAddress, FName, LName, PhoneNum, MobileNum, Email, Address);
string formatOnlyMobileAndFaxAndEmail = String.Format(Constants.FormatOnlyMobileAndFaxAndEmail, FName, LName, MobileNum, FaxNum, Email);
string formatOnlyMobileAndFaxAndEmailAndAddress = String.Format(Constants.FormatOnlyMobileAndFaxAndEmailAndAddress, FName, LName, MobileNum, FaxNum, Email, Address);
string formatOnlyFaxAndEmailAndAddress = String.Format(Constants.FormatOnlyFaxAndEmailAndAddress, FName, LName, FaxNum, Email, Address);
Console.WriteLine // *******can someone suggest me to reduce/optimize the code, I wanna print only the value that is not NULL or String.Empty**********
(
((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatAll
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobileAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndMobileAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndMobileAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobileAndFax
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobile
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndFax
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhone
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndFaxAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndFax
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyMobile
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyFaxAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyFaxAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyFaxAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyFax
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyEmail
: formatOnlyAddress
);
/// <summary>
/// Displays the entry menu
/// </summary>
public void DisplayCoverMenu()
Console.Write(Constants.DisplayCoverMenu);
Console.ReadKey();
Thread.Sleep(Constants.ConstIntArray[5]);
Console.Clear();
/// <summary>
/// Displays the emain menu
/// </summary>
/// <returns></returns>
public int DisplayMainMenu()
Thread.Sleep(Constants.ConstIntArray[4]);
Console.Clear();
Dictionary<int, string> menuItem = Constants.DisplayMainMenu03;
int dictKey;
Console.WriteLine(Constants.DisplayMainMenu01);
for (int i = 0; i < menuItem.Count; i++) Console.WriteLine(Constants.DisplayMainMenu02, i + 1, menuItem[i + 1]);
do
Console.Write(Constants.DisplayMainMenu04);
int.TryParse(Console.ReadLine(), out dictKey);
while (!menuItem.ContainsKey(dictKey));
return dictKey;
/// <summary>
/// Writes error messages to the log file, if no such file exists, then file is created
/// </summary>
/// <param name="logFileName"></param>
/// <param name="log"></param>
/// <exception cref="IOException"></exception>
public static void WriteLogFile(string logFileName, string log)
try
if (!File.Exists(logFileName)) File.CreateText(logFileName);
else File.AppendAllLines(logFileName, new string String.Format(Constants.ErrorLogFormat, DateTime.Now, log));
catch (IOException e)
Console.WriteLine(e.Message);
InputEngine.cs
/*Written by AJ*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace PhoneBook
class InputEngine
/// <summary>
/// Adds single quotes('') around every element of a string array
/// </summary>
/// <param name="dataArr"></param>
/// <returns></returns>
public string AddSingleQuote(string dataArr)
// another approach
//List<string> resList = new List<string>();
//foreach (string str in dataArr) resList.Add((str != String.Empty) ? String.Format("012", ''', str, ''') : "NULL");
//return resList.ToArray();
return dataArr.ToList().Select(str => (str != String.Empty) ? String.Format(Constants.AddSingleQuote01, Constants.AddSingleQuote02, str, Constants.AddSingleQuote02) : Constants.AddSingleQuote03).ToArray();
/// <summary>
/// Helper func: gets user input
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>
private static string UserInHelper(string prompt)
Console.Write(Constants.UserInHelper,prompt);
return Console.ReadLine() ?? String.Empty;
/// <summary>
/// returns a processed string array of user inputs
/// </summary>
/// <returns></returns>
public string UserInput()
List<string> userDataList = new List<string>();
while (userDataList.Count!=7)
string fNameIn;
do
Console.Clear();
Console.Write(Constants.UserInput01);
fNameIn = Console.ReadLine() ?? String.Empty;
while (fNameIn.Equals(String.Empty));
userDataList.Add(fNameIn);
string promptArr = Constants.UserInput02;
for (int i = 0; i < promptArr.Length; i++) userDataList.Add(UserInHelper(promptArr[i]));
return userDataList.ToArray();
/// <summary>
/// gets the search items from user
/// </summary>
/// <param name="keyword"></param>
/// <returns></returns>
public Tuple<string,string> SearchInit(string keyword)
Dictionary<int, string> searchKeyDict = Constants.SearchInit05;
string sKey, sVal;
int dictKey;
do
Console.Clear();
Console.Write(Constants.SearchInit01,keyword);
int.TryParse(Console.ReadLine(), out dictKey);
while (!searchKeyDict.ContainsKey(dictKey) && dictKey!=Constants.SearchInit06);
if (dictKey==Constants.SearchInit06)
Console.WriteLine(Constants.SearchInit02);
Thread.Sleep(Constants.ConstIntArray[3]);
Console.WriteLine(Constants.SearchInit03);
Thread.Sleep(Constants.ConstIntArray[4]);
Environment.Exit(exitCode: Constants.SuceessExitCode);
sKey = searchKeyDict[dictKey];
do
Console.WriteLine(Constants.SearchInit04,keyword);
sVal = Console.ReadLine() ?? String.Empty;
while (sVal.Equals(String.Empty));
return new Tuple<string, string> (sKey, sVal);
Constants.cs
/*Written by AJ*/
using System.Collections.Generic;
namespace PhoneBook
class Constants
//all formatOnly strings
public const string FormatAll = "Name: 0 1nPhone: 2nMoblie: 3nFax: 4nEmail: 5nAddress: 6";
public const string FormatOnlyPhone = "Name: 0 1nPhone: 2";
public const string FormatOnlyMobile = "Name: 0 1nMobile: 2";
public const string FormatOnlyFax = "Name: 0 1nFax: 2";
public const string FormatOnlyEmail = "Name: 0 1nEmail: 2";
public const string FormatOnlyAddress = "Name: 0 1nAddress: 2";
public const string FormatOnlyPhoneAndMobile = "Name: 0 1nPhone: 2nMobile: 3" ;
public const string FormatOnlyPhoneAndFax = "Name: 0 1nPhone: 2nFax: 3" ;
public const string FormatOnlyPhoneAndFaxAndEmail = "Name: 0 1nPhone: 2nFax: 3nEmail: 4";
public const string FormatOnlyPhoneAndEmailAndAddress = "Name: 0 1nPhone: 2nEmail: 3nAddress: 4";
public const string FormatOnlyPhoneAndFaxAndAddress = "Name: 0 1nPhone: 2nFax: 3nAddress: 4";
public const string FormatOnlyPhoneAndEmail = "Name: 0 1nPhone: 2nEmail: 3";
public const string FormatOnlyPhoneAndAddress = "Name: 0 1nPhone: 2nAddress 3";
public const string FormatOnlyMobileAndFax = "Name: 0 1nMobile: 2nFax: 3";
public const string FormatOnlyMobileAndEmail = "Name: 0 1nMobile: 2nEmail: 3";
public const string FormatOnlyMobileAndEmailAndAddress = "Name: 0 1nMobile: 2nEmail: 3nAddress: 4";
public const string FormatOnlyMobileAndFaxAndAddress = "Name: 0 1nMobile: 2nFax: 3nAddress: 4";
public const string FormatOnlyMobileAndAddress = "Name: 0 1nMobile: 2nAddress: 3";
public const string FormatOnlyFaxAndEmail = "Name: 0 1nFax: 2nEmail: 3";
public const string FormatOnlyFaxAndAddress = "Name: 0 1nFax: 2nAddress: 3";
public const string FormatOnlyEmailAndAddress = "Name: 0 1nEmail: 2nAddress: 3";
public const string FormatOnlyPhoneAndMobileAndFax = "Name: 0 1nPhone: 2nMobile: 3nFax: 4";
public const string FormatOnlyPhoneAndMobileAndFaxAndEmail = "Name: 0 1nPhone: 2nMobile: 3nFax: 4nEmail: 5";
public const string FormatOnlyPhoneAndMobileAndFaxAndAddress = "Name: 0 1nPhone: 2nMobile: 3nFax: 4nAddress: 5";
public const string FormatOnlyPhoneAndMobileAndEmailAndAddress = "Name: 0 1nPhone: 2nMobile: 3nEmail: 4nAddress: 5";
public const string FormatOnlyMobileAndFaxAndEmail = "Name: 0 1nMobile: 2nFax: 3nEmail: 4";
public const string FormatOnlyMobileAndFaxAndEmailAndAddress = "Name: 0 1nMobile: 2nFax: 3nEmail: 4nAdress: 5";
public const string FormatOnlyFaxAndEmailAndAddress = "Name: 0 1nFax: 2nEmail: 3nAddress: 4";
// functions const objects
public const string UserInHelper = "plese enter 0 >>> ";
public const string UserInput01 = "Please enter First Name >>> ";
public const string SearchInit01 = "Please Pressn1 => First Namen2 => Last Namen3 => Phone Numbern4 => Mobile Numbern5 =>" +
" Fax Numbern6 => Emailn7 => Addressnto select the 0 keywordnn***OR Press 8 => to cancel and exit***nn>>> ";
public const string SearchInit02 = "Canceling...";
public const string SearchInit03 = "Exiting...";
public const string SearchInit04 = "Please enter the 0 value";
public const int SearchInit06 = 8;
public const string AddSingleQuote01 = "012";
public const char AddSingleQuote02 = ''';
public const string AddSingleQuote03 = "NULL";
public const int SuceessExitCode = 0;
public const int FailedExitCore = 1;
public const string DisplayCoverMenu = "nnnnnnnnnntttWelcome to SharpContracts: A Contact Management System by AlexnntttPlease Press 'Enter' To Continue...nnnttt";
public const string DisplayMainMenu01 = "rnnttMAIN MENUn";
public const string DisplayMainMenu02 = "tt00 1nn";
public const string DisplayMainMenu04 = "nnttPlease select <1-5> to operate:tt";
public const string RecoredUpdatedText = "nntttRecord Updated!!!";
public const string WriteToDbServer01 = ", ";
public const string WriteToDbServer02 = ");";
public const string OceStr = "1";
public const string ExistInDbWrapper01 = "Searching...nn";
public const string ExistInDbWrapper02 = "Item doesn't exist in the server!";
public const string Run01 = "search";
public const string Run02 = "update";
public const string Run03 = "delete";
public const string Dbname = "App_db_phoneBook";
public const string TableName = "PhoneBookRecoder";
// function readonly objects
public static readonly string UserInput02 = new string "Last Name", "Phone Number", "Mobile Number", "Fax Number", "Email", "Address" ;
public static readonly Dictionary<int,string> SearchInit05 = new Dictionary<int, string> 1, "FName" , 2, "LName" , 3, "PhoneNum" , 4, "MobNum" , 5, "FaxNum" , 6, "Email" , 7, "Address" ;
public static readonly Dictionary<int, string> DisplayMainMenu03 = new Dictionary<int, string> 1, "CREATE NEW CONTACT" , 2, "SEARCH CONTACT" , 3, "MODIFY CONTACT" , 4, "DELETE CONTACT" , 5, "EXIT" ;
// miscellaneous objects
public static readonly int ConstIntArray = new int 0, 7, 1000, 1500, 2000, 3000 ;
public const string ErrorGlobalMessage = "Something went wrong!nContract System AdministratornShutting Down...";
public const string ErrorLogFormat = "Time: 0 Error details: 1";
public const string LogFIleName = "phone_book_errror_log.log"; // locates in the current dir
// function protected pbjects (sql commads)
protected const string DeleteCommText = "DELETE FROM PhoneBookRecoder WHERE 0='1';";
protected const string UpdateCommText = "UPDATE PhoneBookRecoder SET 0='1' WHERE 2='3';";
protected const string WriteCommText = "INSERT INTO PhoneBookRecoder VALUES (";
protected const string ReadCommText = "SELECT * FROM PhoneBookRecoder WHERE 0='1' ORDER BY FName;";
protected const string ExistsCommText = "SELECT CASE WHEN EXISTS(SELECT * FROM PhoneBookRecoder WHERE 0='1') THEN 1 ELSE 0 END";
protected const string ExistsDbInServerExistCommText = "IF DB_ID('0') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string ExistsTableInDbInServerExistCommText = "IF OBJECT_ID (N'0', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string ExistsBothDbAndTableExistCommText = "IF DB_ID('0') IS NOT NULL AND OBJECT_ID (N'1', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string CreateTableInDbServerCommText = "USE 0; CREATE TABLE 1 ( FName nvarchar(15) NOT NULL, LName nvarchar(15), PhoneNum nvarchar(15)," +
"MobNum nvarchar(15), FaxNum nvarchar(15), Email nvarchar(25), Address nvarchar(100) );";
protected const string CreateDbInServerCommText = "CREATE DATABASE 0";
protected const string DeleteDbInServerCommText = "DROP DATABASE 0";
protected const string ConnectionStringWithDbname = @"Data Source=[Machine Name][Db Server Name];Initial Catalog=App_db_phoneBook;Integrated Security=True;";
protected const string ConnectionString = @"Data Source=[Machine Name][Db Server Name];Integrated Security=True;";
Program.cs
/*Written by AJ*/
namespace PhoneBook
class Program
static void Main(string args)
PhoneBookAppCore appCore = new PhoneBookAppCore();
appCore.Run();
c# sql-server database
add a comment |Â
up vote
0
down vote
favorite
I wrote this simple contact book app. It helps the user to store and retrieve contact information. The app uses a SQL database server to store all the user data. One significant fact is that the db and its table are only created when the user uses the application for the first time. Moreover, this app can log error information in a local .log file(it's possible to send the log file to the developer as well, if required(though not implemented in this project)). I've tried to apply my limited understanding of different concepts of core C#. I'd appreciate if someone(an experienced c# developer, if possible) to point out the mistakes that I have made and suggest how I could optimize this app. A non-related Question: is it possible to write this project exactly in C++?
PhoneBookAppCore.cs
/*Written by AJ*/
using System;
using System.Threading;
namespace PhoneBook
class PhoneBookAppCore
private static readonly InputEngine _inputEngline = new InputEngine();
private static readonly SqlEngine _sqlEngine = new SqlEngine();
/// <summary>
/// Wrapper func: checks if an entry exists in the db table
/// </summary>
/// <param name="keyword"></param>
/// <param name="show"></param>
/// <returns></returns>
private static Tuple<string,string,bool> ExistInDbWrapper(string keyword, bool show=true)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
var searchTuple = _inputEngline.SearchInit(keyword);
bool exists = _sqlEngine.ExistInDbServer(searchTuple.Item1, searchTuple.Item2);
if (show is true) Console.WriteLine(exists ? Constants.ExistInDbWrapper01 : Constants.ExistInDbWrapper02);
Thread.Sleep(Constants.ConstIntArray[4]);
return new Tuple<string, string, bool>(searchTuple.Item1, searchTuple.Item2, exists);
/// <summary>
/// Wrapper func: checks if an entry exists in the db table
/// </summary>
/// <param name="searchKeyword"></param>
/// <param name="updateKeyword"></param>
/// <returns></returns>
private static Tuple<string, string,string,string, bool> ExistInDbWrapper(string searchKeyword, string updateKeyword)
var searchTuple = ExistInDbWrapper(searchKeyword);
if (searchTuple.Item3 is false) return new Tuple<string, string, string, string, bool>(null,null,null,null,searchTuple.Item3);
var updateTuple = ExistInDbWrapper(updateKeyword, show:false);
Thread.Sleep(Constants.ConstIntArray[4]);
return new Tuple<string, string, string,string,bool>(updateTuple.Item1,updateTuple.Item2,searchTuple.Item1,searchTuple.Item2,searchTuple.Item3);
/// <summary>
/// Use this to run this app
/// </summary>
public void Run()
try
Init(Constants.Dbname, Constants.TableName);
//Display cover menu
OutputEngine outputEngine = new OutputEngine();
outputEngine.DisplayCoverMenu();
bool continueProgram = true;
while (continueProgram)
//display main menu
int userChoice = outputEngine.DisplayMainMenu();
switch (userChoice)
case 1:
CreateNewContact();
break;
case 2:
var dataTuple = ExistInDbWrapper(Constants.Run01);
if (dataTuple.Item3 is false) break;
else SearchContact(dataTuple.Item1, dataTuple.Item2);
dataTuple = null;
break;
case 3:
var dataTupleUpdate = ExistInDbWrapper(Constants.Run01, Constants.Run02);
if (dataTupleUpdate.Item5 is false) break;
else ModifyContact(dataTupleUpdate.Item1, dataTupleUpdate.Item2, dataTupleUpdate.Item3, dataTupleUpdate.Item4);
dataTupleUpdate = null;
break;
case 4:
dataTuple = ExistInDbWrapper(Constants.Run03);
if (dataTuple.Item3 is false) break;
else DeleteContact(dataTuple.Item1, dataTuple.Item2);
dataTuple = null;
break;
case 5:
continueProgram = false;
break;
catch (Exception e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
finally
Console.Clear();
Console.WriteLine(Constants.ErrorGlobalMessage);
Thread.Sleep(Constants.ConstIntArray[5]);
Exit(Constants.FailedExitCore);
/// <summary>
/// Wrapper func: searches an entry and displays result
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
private static void SearchContact(string searchKey, string searchValue)
string dataArr = _sqlEngine.ReadFromDbServer(searchKey, searchValue);
OutputEngine outputEEngineForDisplay = new OutputEngine();
outputEEngineForDisplay.SetProperties(outputEEngineForDisplay, dataArr);
outputEEngineForDisplay.DisplayPhoneBook();
Console.ReadKey();
/// <summary>
/// Wrapper func: modifies an existing db entry
/// </summary>
/// <param name="updateKey"></param>
/// <param name="updateValue"></param>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
private static void ModifyContact(string updateKey, string updateValue, string searchKey, string searchValue)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.UpdateDbServer(updateKey, updateValue, searchKey, searchValue);
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Wrapper func: deletes an entry from db
/// </summary>
/// <param name="deleteKey"></param>
/// <param name="deleteValue"></param>
private static void DeleteContact(string deleteKey, string deleteValue)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.DeleteFromDbServer(deleteKey, deleteValue);
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Wrapper func: terminates an running app
/// </summary>
/// <param name="exitCode">S</param>
private static void Exit(int exitCode)
Environment.Exit(exitCode: exitCode);
/// <summary>
/// Wrapper func: creates new db table entries
/// </summary>
private static void CreateNewContact()
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.WriteToDbServer(_inputEngline.AddSingleQuote(_inputEngline.UserInput()));
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Checks if a db and db tables exists or not; if no db or tb table, then creates them in the server
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
private static void Init(string dbName, string tableName)
bool isDbExists = _sqlEngine.ExistsDbInServer(dbName);
bool isTabExists = _sqlEngine.ExistsTableInDbInServer(tableName);
if (isDbExists is false && isTabExists is false)
_sqlEngine.CreateDbInServer(dbName);
_sqlEngine.CreateTableInDbServer(dbName, tableName);
else return;
SqlEngine.cs
/*Written by AJ*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
namespace PhoneBook // Constants.(fildname) could be simplified to only fildname since class SqlEngine inherits from class Constants
class SqlEngine : Constants //this inheritance is to gain access to protected sql command texts
private string _connectionStringWithDbname = Constants.ConnectionStringWithDbname;
private string _connectionString = Constants.ConnectionString;
/// <summary>
/// Enables conn with a db in the sql server
/// </summary>
/// <param name="connStr"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
private SqlConnection CreteDbLink(string connStr)
SqlConnection conn = new SqlConnection(connStr);
return conn;
/// <summary>
/// Inserts entry values in the db table
/// </summary>
/// <param name="dataArr"></param>
/// <exception cref="SqlException"></exception>
public void WriteToDbServer(string dataArr)
VoidFuncHelper(Constants.WriteCommText + String.Join(Constants.WriteToDbServer01, dataArr) + Constants.WriteToDbServer02, this._connectionStringWithDbname); // this string consists of one protected const string and two public const string
/// <summary>
/// Updates value of an entry in the db table
/// </summary>
/// <param name="updateKey"></param>
/// <param name="updateValue"></param>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <exception cref="SqlException"></exception>
public void UpdateDbServer(string updateKey, string updateValue, string searchKey, string searchValue)
VoidFuncHelper(String.Format(Constants.UpdateCommText, updateKey, updateValue, searchKey, searchValue), this._connectionStringWithDbname);
/// <summary>
/// Retrieves string array of searched entry from db
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public string ReadFromDbServer(string searchKey, string searchValue)
string readCommStr = String.Format(Constants.ReadCommText, searchKey, searchValue);
List<string> rawDataList = new List<string>();
SqlConnection conn = CreteDbLink(this._connectionStringWithDbname);
using (conn)
conn.Open();
SqlCommand sqlCommand = new SqlCommand(readCommStr, conn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) foreach (int i in Enumerable.Range(Constants.ConstIntArray[0], Constants.ConstIntArray[1])) rawDataList.Add(reader.GetValue(i).ToString());
conn.Close();
return rawDataList.ToArray();
/// <summary>
/// Checks if an entry exists in db table
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistInDbServer(string searchKey, string searchValue)
return BoolFuncHelper(String.Format(Constants.ExistsCommText, searchKey, searchValue), this._connectionStringWithDbname);
/// <summary>
/// Deletes the value of a searched entry from db table
/// </summary>
/// <param name="deleteKey"></param>
/// <param name="deleteValue"></param>
/// <exception cref="SqlException"></exception>
public void DeleteFromDbServer(string deleteKey, string deleteValue)
VoidFuncHelper(String.Format(Constants.DeleteCommText, deleteKey, deleteValue), this._connectionStringWithDbname);
/// <summary>
/// Checks if a db exists in the server
/// </summary>
/// <param name="dbName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsDbInServer(string dbName)
return BoolFuncHelper(String.Format(Constants.ExistsDbInServerExistCommText, dbName), this._connectionString);//only db exists or not
/// <summary>
/// Checks if a table exists in the db server
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsTableInDbInServer(string tableName)
return BoolFuncHelper(String.Format(Constants.ExistsTableInDbInServerExistCommText, tableName), this._connectionString); //look out could be this._connectionStringWithDbname
/// <summary>
/// returns True if both db and table exist in the server
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsBothDbAndTable(string dbName, string tableName)
return BoolFuncHelper(String.Format(Constants.ExistsBothDbAndTableExistCommText, dbName, tableName), this._connectionStringWithDbname);
/// <summary>
/// Creates a db in the sql server
/// </summary>
/// <param name="dbName"></param>
/// <exception cref="SqlException"></exception>
public void CreateDbInServer(string dbName)
VoidFuncHelper(String.Format(Constants.CreateDbInServerCommText, dbName), this._connectionString);
/// <summary>
/// Deletes a db from the sql server
/// </summary>
/// <param name="dbName"></param>
/// <exception cref="SqlException"></exception>
public void DeleteDbInServer(string dbName)
VoidFuncHelper(String.Format(Constants.DeleteDbInServerCommText, dbName), this._connectionString);
/// <summary>
/// Creates a table in the specified db
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <exception cref="SqlException"></exception>
public void CreateTableInDbServer(string dbName, string tableName)
VoidFuncHelper(String.Format(Constants.CreateTableInDbServerCommText, dbName, tableName), this._connectionString); //look out could be this._connectionStringWithDbname
/// <summary>
/// Helper func : enables db conn
/// </summary>
/// <param name="commStr"></param>
/// <param name="connStr"></param>
/// <returns>bool value from the executed sql command</returns>
/// <exception cref="SqlException"></exception>
private bool BoolFuncHelper(string commStr, string connStr)
bool exist = false;
SqlConnection conn = CreteDbLink(connStr);
try
using (conn)
conn.Open();
SqlCommand sqlCommand = new SqlCommand(commStr, conn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) exist = (reader.GetValue(Constants.ConstIntArray[0]).ToString() == Constants.OceStr ? true : false);
conn.Close();
catch (SqlException e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
Environment.Exit(Constants.FailedExitCore);
return exist;
/// <summary>
/// Helper func : enables db connection and executes sql comm
/// </summary>
/// <param name="commStr"></param>
/// <param name="connStr"></param>
/// <exception cref="SqlException"></exception>
private void VoidFuncHelper(string commStr, string connStr)
try
using (SqlConnection conn = new SqlConnection(connStr))
conn.Open();
SqlCommand sqlCom = conn.CreateCommand();
sqlCom.CommandText = commStr;
sqlCom.ExecuteNonQuery();
conn.Close();
catch (SqlException e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
Environment.Exit(Constants.FailedExitCore);
OutputEngine.cs
/*Written by AJ*/
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;
using System.IO;
namespace PhoneBook
class OutputEngine
// list of default values of properties
private string _fName = String.Empty;
private string _lName = String.Empty;
private string _pNum = String.Empty;
private string _mNum = String.Empty;
private string _fNum = String.Empty;
private string _email = String.Empty;
private string _address = String.Empty;
// list of properties
public string FName get => this._fName; set => _fName = value;
public string LName get => this._lName; set => _lName = value;
public string PhoneNum get => this._pNum; set => _pNum = value;
public string MobileNum get => this._mNum; set => _mNum = value;
public string FaxNum get => this._fNum; set => _fNum = value;
public string Email get => this._email; set => _email = value;
public string Address get => this._address; set => _address = value;
/// <summary>
/// Assigns values to the properties of a class instance
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance"></param>
/// <param name="dataArr"></param>
public void SetProperties<T>(T instance, object dataArr) where T : class
Enumerable.Zip(instance.GetType().GetRuntimeProperties(), dataArr, Tuple.Create).ToList().ForEach((tup) => tup.Item1.SetValue(instance, tup.Item2, null));
/// <summary>
/// Displays phonebook entries
/// </summary>
public void DisplayPhoneBook() // can someone suggest me to reduce/optimize the code, I wanna print only the value that is not NULL or String.Empty
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
string formatAll = String.Format(Constants.FormatAll, FName, LName, PhoneNum, MobileNum, FaxNum, Email, Address);
string formatOnlyPhone = String.Format(Constants.FormatOnlyPhone, FName, LName, PhoneNum);
string formatOnlyMobile = String.Format(Constants.FormatOnlyMobile, FName, LName, MobileNum);
string formatOnlyFax = String.Format(Constants.FormatOnlyFax, FName, LName, FaxNum);
string formatOnlyEmail = String.Format(Constants.FormatOnlyEmail, FName, LName, Email);
string formatOnlyAddress = String.Format(Constants.FormatOnlyAddress, FName, LName, Address);
string formatOnlyPhoneAndMobile = String.Format(Constants.FormatOnlyPhoneAndMobile, FName, LName, PhoneNum, MobileNum);
string formatOnlyPhoneAndFax = String.Format(Constants.FormatOnlyPhoneAndFax, FName, LName, PhoneNum, FaxNum);
string formatOnlyPhoneAndFaxAndEmail = String.Format(Constants.FormatOnlyPhoneAndFaxAndEmail, FName, LName, PhoneNum, FaxNum, Email);
string formatOnlyPhoneAndEmailAndAddress = String.Format(Constants.FormatOnlyPhoneAndEmailAndAddress, FName, LName, PhoneNum, Email, Address);
string formatOnlyPhoneAndFaxAndAddress = String.Format(Constants.FormatOnlyPhoneAndFaxAndAddress, FName, LName, PhoneNum, FaxNum, Address);
string formatOnlyPhoneAndEmail = String.Format(Constants.FormatOnlyPhoneAndEmail, FName, LName, PhoneNum, Email);
string formatOnlyPhoneAndAddress = String.Format(Constants.FormatOnlyPhoneAndAddress, FName, LName, PhoneNum, Address);
string formatOnlyMobileAndFax = String.Format(Constants.FormatOnlyMobileAndFax, FName, LName, MobileNum, FaxNum);
string formatOnlyMobileAndEmail = String.Format(Constants.FormatOnlyMobileAndEmail, FName, LName, MobileNum, Email);
string formatOnlyMobileAndEmailAndAddress = String.Format(Constants.FormatOnlyMobileAndEmailAndAddress, FName, LName, MobileNum, Email, Address);
string formatOnlyMobileAndFaxAndAddress = String.Format(Constants.FormatOnlyMobileAndFaxAndAddress, FName, LName, MobileNum, FaxNum, Address);
string formatOnlyMobileAndAddress = String.Format(Constants.FormatOnlyMobileAndAddress, FName, LName, MobileNum, Address);
string formatOnlyFaxAndEmail = String.Format(Constants.FormatOnlyFaxAndEmail, FName, LName, FaxNum, Email);
string formatOnlyFaxAndAddress = String.Format(Constants.FormatOnlyFaxAndAddress, FName, LName, FaxNum, Address);
string formatOnlyEmailAndAddress = String.Format(Constants.FormatOnlyEmailAndAddress, FName, LName, Email, Address);
string formatOnlyPhoneAndMobileAndFax = String.Format(Constants.FormatOnlyPhoneAndMobileAndFax, FName, LName, PhoneNum, MobileNum, FaxNum);
string formatOnlyPhoneAndMobileAndFaxAndEmail = String.Format(Constants.FormatOnlyPhoneAndMobileAndFaxAndEmail, FName, LName, PhoneNum, MobileNum, FaxNum, Email);
string formatOnlyPhoneAndMobileAndFaxAndAddress = String.Format(Constants.FormatOnlyPhoneAndMobileAndFaxAndAddress, FName, LName, PhoneNum, MobileNum, FaxNum, Address);
string formatOnlyPhoneAndMobileAndEmailAndAddress = String.Format(Constants.FormatOnlyPhoneAndMobileAndEmailAndAddress, FName, LName, PhoneNum, MobileNum, Email, Address);
string formatOnlyMobileAndFaxAndEmail = String.Format(Constants.FormatOnlyMobileAndFaxAndEmail, FName, LName, MobileNum, FaxNum, Email);
string formatOnlyMobileAndFaxAndEmailAndAddress = String.Format(Constants.FormatOnlyMobileAndFaxAndEmailAndAddress, FName, LName, MobileNum, FaxNum, Email, Address);
string formatOnlyFaxAndEmailAndAddress = String.Format(Constants.FormatOnlyFaxAndEmailAndAddress, FName, LName, FaxNum, Email, Address);
Console.WriteLine // *******can someone suggest me to reduce/optimize the code, I wanna print only the value that is not NULL or String.Empty**********
(
((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatAll
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobileAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndMobileAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndMobileAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobileAndFax
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobile
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndFax
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhone
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndFaxAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndFax
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyMobile
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyFaxAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyFaxAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyFaxAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyFax
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyEmail
: formatOnlyAddress
);
/// <summary>
/// Displays the entry menu
/// </summary>
public void DisplayCoverMenu()
Console.Write(Constants.DisplayCoverMenu);
Console.ReadKey();
Thread.Sleep(Constants.ConstIntArray[5]);
Console.Clear();
/// <summary>
/// Displays the emain menu
/// </summary>
/// <returns></returns>
public int DisplayMainMenu()
Thread.Sleep(Constants.ConstIntArray[4]);
Console.Clear();
Dictionary<int, string> menuItem = Constants.DisplayMainMenu03;
int dictKey;
Console.WriteLine(Constants.DisplayMainMenu01);
for (int i = 0; i < menuItem.Count; i++) Console.WriteLine(Constants.DisplayMainMenu02, i + 1, menuItem[i + 1]);
do
Console.Write(Constants.DisplayMainMenu04);
int.TryParse(Console.ReadLine(), out dictKey);
while (!menuItem.ContainsKey(dictKey));
return dictKey;
/// <summary>
/// Writes error messages to the log file, if no such file exists, then file is created
/// </summary>
/// <param name="logFileName"></param>
/// <param name="log"></param>
/// <exception cref="IOException"></exception>
public static void WriteLogFile(string logFileName, string log)
try
if (!File.Exists(logFileName)) File.CreateText(logFileName);
else File.AppendAllLines(logFileName, new string String.Format(Constants.ErrorLogFormat, DateTime.Now, log));
catch (IOException e)
Console.WriteLine(e.Message);
InputEngine.cs
/*Written by AJ*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace PhoneBook
class InputEngine
/// <summary>
/// Adds single quotes('') around every element of a string array
/// </summary>
/// <param name="dataArr"></param>
/// <returns></returns>
public string AddSingleQuote(string dataArr)
// another approach
//List<string> resList = new List<string>();
//foreach (string str in dataArr) resList.Add((str != String.Empty) ? String.Format("012", ''', str, ''') : "NULL");
//return resList.ToArray();
return dataArr.ToList().Select(str => (str != String.Empty) ? String.Format(Constants.AddSingleQuote01, Constants.AddSingleQuote02, str, Constants.AddSingleQuote02) : Constants.AddSingleQuote03).ToArray();
/// <summary>
/// Helper func: gets user input
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>
private static string UserInHelper(string prompt)
Console.Write(Constants.UserInHelper,prompt);
return Console.ReadLine() ?? String.Empty;
/// <summary>
/// returns a processed string array of user inputs
/// </summary>
/// <returns></returns>
public string UserInput()
List<string> userDataList = new List<string>();
while (userDataList.Count!=7)
string fNameIn;
do
Console.Clear();
Console.Write(Constants.UserInput01);
fNameIn = Console.ReadLine() ?? String.Empty;
while (fNameIn.Equals(String.Empty));
userDataList.Add(fNameIn);
string promptArr = Constants.UserInput02;
for (int i = 0; i < promptArr.Length; i++) userDataList.Add(UserInHelper(promptArr[i]));
return userDataList.ToArray();
/// <summary>
/// gets the search items from user
/// </summary>
/// <param name="keyword"></param>
/// <returns></returns>
public Tuple<string,string> SearchInit(string keyword)
Dictionary<int, string> searchKeyDict = Constants.SearchInit05;
string sKey, sVal;
int dictKey;
do
Console.Clear();
Console.Write(Constants.SearchInit01,keyword);
int.TryParse(Console.ReadLine(), out dictKey);
while (!searchKeyDict.ContainsKey(dictKey) && dictKey!=Constants.SearchInit06);
if (dictKey==Constants.SearchInit06)
Console.WriteLine(Constants.SearchInit02);
Thread.Sleep(Constants.ConstIntArray[3]);
Console.WriteLine(Constants.SearchInit03);
Thread.Sleep(Constants.ConstIntArray[4]);
Environment.Exit(exitCode: Constants.SuceessExitCode);
sKey = searchKeyDict[dictKey];
do
Console.WriteLine(Constants.SearchInit04,keyword);
sVal = Console.ReadLine() ?? String.Empty;
while (sVal.Equals(String.Empty));
return new Tuple<string, string> (sKey, sVal);
Constants.cs
/*Written by AJ*/
using System.Collections.Generic;
namespace PhoneBook
class Constants
//all formatOnly strings
public const string FormatAll = "Name: 0 1nPhone: 2nMoblie: 3nFax: 4nEmail: 5nAddress: 6";
public const string FormatOnlyPhone = "Name: 0 1nPhone: 2";
public const string FormatOnlyMobile = "Name: 0 1nMobile: 2";
public const string FormatOnlyFax = "Name: 0 1nFax: 2";
public const string FormatOnlyEmail = "Name: 0 1nEmail: 2";
public const string FormatOnlyAddress = "Name: 0 1nAddress: 2";
public const string FormatOnlyPhoneAndMobile = "Name: 0 1nPhone: 2nMobile: 3" ;
public const string FormatOnlyPhoneAndFax = "Name: 0 1nPhone: 2nFax: 3" ;
public const string FormatOnlyPhoneAndFaxAndEmail = "Name: 0 1nPhone: 2nFax: 3nEmail: 4";
public const string FormatOnlyPhoneAndEmailAndAddress = "Name: 0 1nPhone: 2nEmail: 3nAddress: 4";
public const string FormatOnlyPhoneAndFaxAndAddress = "Name: 0 1nPhone: 2nFax: 3nAddress: 4";
public const string FormatOnlyPhoneAndEmail = "Name: 0 1nPhone: 2nEmail: 3";
public const string FormatOnlyPhoneAndAddress = "Name: 0 1nPhone: 2nAddress 3";
public const string FormatOnlyMobileAndFax = "Name: 0 1nMobile: 2nFax: 3";
public const string FormatOnlyMobileAndEmail = "Name: 0 1nMobile: 2nEmail: 3";
public const string FormatOnlyMobileAndEmailAndAddress = "Name: 0 1nMobile: 2nEmail: 3nAddress: 4";
public const string FormatOnlyMobileAndFaxAndAddress = "Name: 0 1nMobile: 2nFax: 3nAddress: 4";
public const string FormatOnlyMobileAndAddress = "Name: 0 1nMobile: 2nAddress: 3";
public const string FormatOnlyFaxAndEmail = "Name: 0 1nFax: 2nEmail: 3";
public const string FormatOnlyFaxAndAddress = "Name: 0 1nFax: 2nAddress: 3";
public const string FormatOnlyEmailAndAddress = "Name: 0 1nEmail: 2nAddress: 3";
public const string FormatOnlyPhoneAndMobileAndFax = "Name: 0 1nPhone: 2nMobile: 3nFax: 4";
public const string FormatOnlyPhoneAndMobileAndFaxAndEmail = "Name: 0 1nPhone: 2nMobile: 3nFax: 4nEmail: 5";
public const string FormatOnlyPhoneAndMobileAndFaxAndAddress = "Name: 0 1nPhone: 2nMobile: 3nFax: 4nAddress: 5";
public const string FormatOnlyPhoneAndMobileAndEmailAndAddress = "Name: 0 1nPhone: 2nMobile: 3nEmail: 4nAddress: 5";
public const string FormatOnlyMobileAndFaxAndEmail = "Name: 0 1nMobile: 2nFax: 3nEmail: 4";
public const string FormatOnlyMobileAndFaxAndEmailAndAddress = "Name: 0 1nMobile: 2nFax: 3nEmail: 4nAdress: 5";
public const string FormatOnlyFaxAndEmailAndAddress = "Name: 0 1nFax: 2nEmail: 3nAddress: 4";
// functions const objects
public const string UserInHelper = "plese enter 0 >>> ";
public const string UserInput01 = "Please enter First Name >>> ";
public const string SearchInit01 = "Please Pressn1 => First Namen2 => Last Namen3 => Phone Numbern4 => Mobile Numbern5 =>" +
" Fax Numbern6 => Emailn7 => Addressnto select the 0 keywordnn***OR Press 8 => to cancel and exit***nn>>> ";
public const string SearchInit02 = "Canceling...";
public const string SearchInit03 = "Exiting...";
public const string SearchInit04 = "Please enter the 0 value";
public const int SearchInit06 = 8;
public const string AddSingleQuote01 = "012";
public const char AddSingleQuote02 = ''';
public const string AddSingleQuote03 = "NULL";
public const int SuceessExitCode = 0;
public const int FailedExitCore = 1;
public const string DisplayCoverMenu = "nnnnnnnnnntttWelcome to SharpContracts: A Contact Management System by AlexnntttPlease Press 'Enter' To Continue...nnnttt";
public const string DisplayMainMenu01 = "rnnttMAIN MENUn";
public const string DisplayMainMenu02 = "tt00 1nn";
public const string DisplayMainMenu04 = "nnttPlease select <1-5> to operate:tt";
public const string RecoredUpdatedText = "nntttRecord Updated!!!";
public const string WriteToDbServer01 = ", ";
public const string WriteToDbServer02 = ");";
public const string OceStr = "1";
public const string ExistInDbWrapper01 = "Searching...nn";
public const string ExistInDbWrapper02 = "Item doesn't exist in the server!";
public const string Run01 = "search";
public const string Run02 = "update";
public const string Run03 = "delete";
public const string Dbname = "App_db_phoneBook";
public const string TableName = "PhoneBookRecoder";
// function readonly objects
public static readonly string UserInput02 = new string "Last Name", "Phone Number", "Mobile Number", "Fax Number", "Email", "Address" ;
public static readonly Dictionary<int,string> SearchInit05 = new Dictionary<int, string> 1, "FName" , 2, "LName" , 3, "PhoneNum" , 4, "MobNum" , 5, "FaxNum" , 6, "Email" , 7, "Address" ;
public static readonly Dictionary<int, string> DisplayMainMenu03 = new Dictionary<int, string> 1, "CREATE NEW CONTACT" , 2, "SEARCH CONTACT" , 3, "MODIFY CONTACT" , 4, "DELETE CONTACT" , 5, "EXIT" ;
// miscellaneous objects
public static readonly int ConstIntArray = new int 0, 7, 1000, 1500, 2000, 3000 ;
public const string ErrorGlobalMessage = "Something went wrong!nContract System AdministratornShutting Down...";
public const string ErrorLogFormat = "Time: 0 Error details: 1";
public const string LogFIleName = "phone_book_errror_log.log"; // locates in the current dir
// function protected pbjects (sql commads)
protected const string DeleteCommText = "DELETE FROM PhoneBookRecoder WHERE 0='1';";
protected const string UpdateCommText = "UPDATE PhoneBookRecoder SET 0='1' WHERE 2='3';";
protected const string WriteCommText = "INSERT INTO PhoneBookRecoder VALUES (";
protected const string ReadCommText = "SELECT * FROM PhoneBookRecoder WHERE 0='1' ORDER BY FName;";
protected const string ExistsCommText = "SELECT CASE WHEN EXISTS(SELECT * FROM PhoneBookRecoder WHERE 0='1') THEN 1 ELSE 0 END";
protected const string ExistsDbInServerExistCommText = "IF DB_ID('0') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string ExistsTableInDbInServerExistCommText = "IF OBJECT_ID (N'0', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string ExistsBothDbAndTableExistCommText = "IF DB_ID('0') IS NOT NULL AND OBJECT_ID (N'1', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string CreateTableInDbServerCommText = "USE 0; CREATE TABLE 1 ( FName nvarchar(15) NOT NULL, LName nvarchar(15), PhoneNum nvarchar(15)," +
"MobNum nvarchar(15), FaxNum nvarchar(15), Email nvarchar(25), Address nvarchar(100) );";
protected const string CreateDbInServerCommText = "CREATE DATABASE 0";
protected const string DeleteDbInServerCommText = "DROP DATABASE 0";
protected const string ConnectionStringWithDbname = @"Data Source=[Machine Name][Db Server Name];Initial Catalog=App_db_phoneBook;Integrated Security=True;";
protected const string ConnectionString = @"Data Source=[Machine Name][Db Server Name];Integrated Security=True;";
Program.cs
/*Written by AJ*/
namespace PhoneBook
class Program
static void Main(string args)
PhoneBookAppCore appCore = new PhoneBookAppCore();
appCore.Run();
c# sql-server database
Have you thought of using a DataTable? It would simplify quite a bit of your code.
â tinstaafl
Jul 11 at 17:05
@tinstaafl could u give me an example?
â A J
Jul 11 at 17:49
Here's a tutorial that should help you out.
â tinstaafl
Jul 11 at 21:38
add a comment |Â
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I wrote this simple contact book app. It helps the user to store and retrieve contact information. The app uses a SQL database server to store all the user data. One significant fact is that the db and its table are only created when the user uses the application for the first time. Moreover, this app can log error information in a local .log file(it's possible to send the log file to the developer as well, if required(though not implemented in this project)). I've tried to apply my limited understanding of different concepts of core C#. I'd appreciate if someone(an experienced c# developer, if possible) to point out the mistakes that I have made and suggest how I could optimize this app. A non-related Question: is it possible to write this project exactly in C++?
PhoneBookAppCore.cs
/*Written by AJ*/
using System;
using System.Threading;
namespace PhoneBook
class PhoneBookAppCore
private static readonly InputEngine _inputEngline = new InputEngine();
private static readonly SqlEngine _sqlEngine = new SqlEngine();
/// <summary>
/// Wrapper func: checks if an entry exists in the db table
/// </summary>
/// <param name="keyword"></param>
/// <param name="show"></param>
/// <returns></returns>
private static Tuple<string,string,bool> ExistInDbWrapper(string keyword, bool show=true)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
var searchTuple = _inputEngline.SearchInit(keyword);
bool exists = _sqlEngine.ExistInDbServer(searchTuple.Item1, searchTuple.Item2);
if (show is true) Console.WriteLine(exists ? Constants.ExistInDbWrapper01 : Constants.ExistInDbWrapper02);
Thread.Sleep(Constants.ConstIntArray[4]);
return new Tuple<string, string, bool>(searchTuple.Item1, searchTuple.Item2, exists);
/// <summary>
/// Wrapper func: checks if an entry exists in the db table
/// </summary>
/// <param name="searchKeyword"></param>
/// <param name="updateKeyword"></param>
/// <returns></returns>
private static Tuple<string, string,string,string, bool> ExistInDbWrapper(string searchKeyword, string updateKeyword)
var searchTuple = ExistInDbWrapper(searchKeyword);
if (searchTuple.Item3 is false) return new Tuple<string, string, string, string, bool>(null,null,null,null,searchTuple.Item3);
var updateTuple = ExistInDbWrapper(updateKeyword, show:false);
Thread.Sleep(Constants.ConstIntArray[4]);
return new Tuple<string, string, string,string,bool>(updateTuple.Item1,updateTuple.Item2,searchTuple.Item1,searchTuple.Item2,searchTuple.Item3);
/// <summary>
/// Use this to run this app
/// </summary>
public void Run()
try
Init(Constants.Dbname, Constants.TableName);
//Display cover menu
OutputEngine outputEngine = new OutputEngine();
outputEngine.DisplayCoverMenu();
bool continueProgram = true;
while (continueProgram)
//display main menu
int userChoice = outputEngine.DisplayMainMenu();
switch (userChoice)
case 1:
CreateNewContact();
break;
case 2:
var dataTuple = ExistInDbWrapper(Constants.Run01);
if (dataTuple.Item3 is false) break;
else SearchContact(dataTuple.Item1, dataTuple.Item2);
dataTuple = null;
break;
case 3:
var dataTupleUpdate = ExistInDbWrapper(Constants.Run01, Constants.Run02);
if (dataTupleUpdate.Item5 is false) break;
else ModifyContact(dataTupleUpdate.Item1, dataTupleUpdate.Item2, dataTupleUpdate.Item3, dataTupleUpdate.Item4);
dataTupleUpdate = null;
break;
case 4:
dataTuple = ExistInDbWrapper(Constants.Run03);
if (dataTuple.Item3 is false) break;
else DeleteContact(dataTuple.Item1, dataTuple.Item2);
dataTuple = null;
break;
case 5:
continueProgram = false;
break;
catch (Exception e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
finally
Console.Clear();
Console.WriteLine(Constants.ErrorGlobalMessage);
Thread.Sleep(Constants.ConstIntArray[5]);
Exit(Constants.FailedExitCore);
/// <summary>
/// Wrapper func: searches an entry and displays result
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
private static void SearchContact(string searchKey, string searchValue)
string dataArr = _sqlEngine.ReadFromDbServer(searchKey, searchValue);
OutputEngine outputEEngineForDisplay = new OutputEngine();
outputEEngineForDisplay.SetProperties(outputEEngineForDisplay, dataArr);
outputEEngineForDisplay.DisplayPhoneBook();
Console.ReadKey();
/// <summary>
/// Wrapper func: modifies an existing db entry
/// </summary>
/// <param name="updateKey"></param>
/// <param name="updateValue"></param>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
private static void ModifyContact(string updateKey, string updateValue, string searchKey, string searchValue)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.UpdateDbServer(updateKey, updateValue, searchKey, searchValue);
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Wrapper func: deletes an entry from db
/// </summary>
/// <param name="deleteKey"></param>
/// <param name="deleteValue"></param>
private static void DeleteContact(string deleteKey, string deleteValue)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.DeleteFromDbServer(deleteKey, deleteValue);
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Wrapper func: terminates an running app
/// </summary>
/// <param name="exitCode">S</param>
private static void Exit(int exitCode)
Environment.Exit(exitCode: exitCode);
/// <summary>
/// Wrapper func: creates new db table entries
/// </summary>
private static void CreateNewContact()
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.WriteToDbServer(_inputEngline.AddSingleQuote(_inputEngline.UserInput()));
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Checks if a db and db tables exists or not; if no db or tb table, then creates them in the server
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
private static void Init(string dbName, string tableName)
bool isDbExists = _sqlEngine.ExistsDbInServer(dbName);
bool isTabExists = _sqlEngine.ExistsTableInDbInServer(tableName);
if (isDbExists is false && isTabExists is false)
_sqlEngine.CreateDbInServer(dbName);
_sqlEngine.CreateTableInDbServer(dbName, tableName);
else return;
SqlEngine.cs
/*Written by AJ*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
namespace PhoneBook // Constants.(fildname) could be simplified to only fildname since class SqlEngine inherits from class Constants
class SqlEngine : Constants //this inheritance is to gain access to protected sql command texts
private string _connectionStringWithDbname = Constants.ConnectionStringWithDbname;
private string _connectionString = Constants.ConnectionString;
/// <summary>
/// Enables conn with a db in the sql server
/// </summary>
/// <param name="connStr"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
private SqlConnection CreteDbLink(string connStr)
SqlConnection conn = new SqlConnection(connStr);
return conn;
/// <summary>
/// Inserts entry values in the db table
/// </summary>
/// <param name="dataArr"></param>
/// <exception cref="SqlException"></exception>
public void WriteToDbServer(string dataArr)
VoidFuncHelper(Constants.WriteCommText + String.Join(Constants.WriteToDbServer01, dataArr) + Constants.WriteToDbServer02, this._connectionStringWithDbname); // this string consists of one protected const string and two public const string
/// <summary>
/// Updates value of an entry in the db table
/// </summary>
/// <param name="updateKey"></param>
/// <param name="updateValue"></param>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <exception cref="SqlException"></exception>
public void UpdateDbServer(string updateKey, string updateValue, string searchKey, string searchValue)
VoidFuncHelper(String.Format(Constants.UpdateCommText, updateKey, updateValue, searchKey, searchValue), this._connectionStringWithDbname);
/// <summary>
/// Retrieves string array of searched entry from db
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public string ReadFromDbServer(string searchKey, string searchValue)
string readCommStr = String.Format(Constants.ReadCommText, searchKey, searchValue);
List<string> rawDataList = new List<string>();
SqlConnection conn = CreteDbLink(this._connectionStringWithDbname);
using (conn)
conn.Open();
SqlCommand sqlCommand = new SqlCommand(readCommStr, conn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) foreach (int i in Enumerable.Range(Constants.ConstIntArray[0], Constants.ConstIntArray[1])) rawDataList.Add(reader.GetValue(i).ToString());
conn.Close();
return rawDataList.ToArray();
/// <summary>
/// Checks if an entry exists in db table
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistInDbServer(string searchKey, string searchValue)
return BoolFuncHelper(String.Format(Constants.ExistsCommText, searchKey, searchValue), this._connectionStringWithDbname);
/// <summary>
/// Deletes the value of a searched entry from db table
/// </summary>
/// <param name="deleteKey"></param>
/// <param name="deleteValue"></param>
/// <exception cref="SqlException"></exception>
public void DeleteFromDbServer(string deleteKey, string deleteValue)
VoidFuncHelper(String.Format(Constants.DeleteCommText, deleteKey, deleteValue), this._connectionStringWithDbname);
/// <summary>
/// Checks if a db exists in the server
/// </summary>
/// <param name="dbName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsDbInServer(string dbName)
return BoolFuncHelper(String.Format(Constants.ExistsDbInServerExistCommText, dbName), this._connectionString);//only db exists or not
/// <summary>
/// Checks if a table exists in the db server
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsTableInDbInServer(string tableName)
return BoolFuncHelper(String.Format(Constants.ExistsTableInDbInServerExistCommText, tableName), this._connectionString); //look out could be this._connectionStringWithDbname
/// <summary>
/// returns True if both db and table exist in the server
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsBothDbAndTable(string dbName, string tableName)
return BoolFuncHelper(String.Format(Constants.ExistsBothDbAndTableExistCommText, dbName, tableName), this._connectionStringWithDbname);
/// <summary>
/// Creates a db in the sql server
/// </summary>
/// <param name="dbName"></param>
/// <exception cref="SqlException"></exception>
public void CreateDbInServer(string dbName)
VoidFuncHelper(String.Format(Constants.CreateDbInServerCommText, dbName), this._connectionString);
/// <summary>
/// Deletes a db from the sql server
/// </summary>
/// <param name="dbName"></param>
/// <exception cref="SqlException"></exception>
public void DeleteDbInServer(string dbName)
VoidFuncHelper(String.Format(Constants.DeleteDbInServerCommText, dbName), this._connectionString);
/// <summary>
/// Creates a table in the specified db
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <exception cref="SqlException"></exception>
public void CreateTableInDbServer(string dbName, string tableName)
VoidFuncHelper(String.Format(Constants.CreateTableInDbServerCommText, dbName, tableName), this._connectionString); //look out could be this._connectionStringWithDbname
/// <summary>
/// Helper func : enables db conn
/// </summary>
/// <param name="commStr"></param>
/// <param name="connStr"></param>
/// <returns>bool value from the executed sql command</returns>
/// <exception cref="SqlException"></exception>
private bool BoolFuncHelper(string commStr, string connStr)
bool exist = false;
SqlConnection conn = CreteDbLink(connStr);
try
using (conn)
conn.Open();
SqlCommand sqlCommand = new SqlCommand(commStr, conn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) exist = (reader.GetValue(Constants.ConstIntArray[0]).ToString() == Constants.OceStr ? true : false);
conn.Close();
catch (SqlException e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
Environment.Exit(Constants.FailedExitCore);
return exist;
/// <summary>
/// Helper func : enables db connection and executes sql comm
/// </summary>
/// <param name="commStr"></param>
/// <param name="connStr"></param>
/// <exception cref="SqlException"></exception>
private void VoidFuncHelper(string commStr, string connStr)
try
using (SqlConnection conn = new SqlConnection(connStr))
conn.Open();
SqlCommand sqlCom = conn.CreateCommand();
sqlCom.CommandText = commStr;
sqlCom.ExecuteNonQuery();
conn.Close();
catch (SqlException e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
Environment.Exit(Constants.FailedExitCore);
OutputEngine.cs
/*Written by AJ*/
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;
using System.IO;
namespace PhoneBook
class OutputEngine
// list of default values of properties
private string _fName = String.Empty;
private string _lName = String.Empty;
private string _pNum = String.Empty;
private string _mNum = String.Empty;
private string _fNum = String.Empty;
private string _email = String.Empty;
private string _address = String.Empty;
// list of properties
public string FName get => this._fName; set => _fName = value;
public string LName get => this._lName; set => _lName = value;
public string PhoneNum get => this._pNum; set => _pNum = value;
public string MobileNum get => this._mNum; set => _mNum = value;
public string FaxNum get => this._fNum; set => _fNum = value;
public string Email get => this._email; set => _email = value;
public string Address get => this._address; set => _address = value;
/// <summary>
/// Assigns values to the properties of a class instance
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance"></param>
/// <param name="dataArr"></param>
public void SetProperties<T>(T instance, object dataArr) where T : class
Enumerable.Zip(instance.GetType().GetRuntimeProperties(), dataArr, Tuple.Create).ToList().ForEach((tup) => tup.Item1.SetValue(instance, tup.Item2, null));
/// <summary>
/// Displays phonebook entries
/// </summary>
public void DisplayPhoneBook() // can someone suggest me to reduce/optimize the code, I wanna print only the value that is not NULL or String.Empty
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
string formatAll = String.Format(Constants.FormatAll, FName, LName, PhoneNum, MobileNum, FaxNum, Email, Address);
string formatOnlyPhone = String.Format(Constants.FormatOnlyPhone, FName, LName, PhoneNum);
string formatOnlyMobile = String.Format(Constants.FormatOnlyMobile, FName, LName, MobileNum);
string formatOnlyFax = String.Format(Constants.FormatOnlyFax, FName, LName, FaxNum);
string formatOnlyEmail = String.Format(Constants.FormatOnlyEmail, FName, LName, Email);
string formatOnlyAddress = String.Format(Constants.FormatOnlyAddress, FName, LName, Address);
string formatOnlyPhoneAndMobile = String.Format(Constants.FormatOnlyPhoneAndMobile, FName, LName, PhoneNum, MobileNum);
string formatOnlyPhoneAndFax = String.Format(Constants.FormatOnlyPhoneAndFax, FName, LName, PhoneNum, FaxNum);
string formatOnlyPhoneAndFaxAndEmail = String.Format(Constants.FormatOnlyPhoneAndFaxAndEmail, FName, LName, PhoneNum, FaxNum, Email);
string formatOnlyPhoneAndEmailAndAddress = String.Format(Constants.FormatOnlyPhoneAndEmailAndAddress, FName, LName, PhoneNum, Email, Address);
string formatOnlyPhoneAndFaxAndAddress = String.Format(Constants.FormatOnlyPhoneAndFaxAndAddress, FName, LName, PhoneNum, FaxNum, Address);
string formatOnlyPhoneAndEmail = String.Format(Constants.FormatOnlyPhoneAndEmail, FName, LName, PhoneNum, Email);
string formatOnlyPhoneAndAddress = String.Format(Constants.FormatOnlyPhoneAndAddress, FName, LName, PhoneNum, Address);
string formatOnlyMobileAndFax = String.Format(Constants.FormatOnlyMobileAndFax, FName, LName, MobileNum, FaxNum);
string formatOnlyMobileAndEmail = String.Format(Constants.FormatOnlyMobileAndEmail, FName, LName, MobileNum, Email);
string formatOnlyMobileAndEmailAndAddress = String.Format(Constants.FormatOnlyMobileAndEmailAndAddress, FName, LName, MobileNum, Email, Address);
string formatOnlyMobileAndFaxAndAddress = String.Format(Constants.FormatOnlyMobileAndFaxAndAddress, FName, LName, MobileNum, FaxNum, Address);
string formatOnlyMobileAndAddress = String.Format(Constants.FormatOnlyMobileAndAddress, FName, LName, MobileNum, Address);
string formatOnlyFaxAndEmail = String.Format(Constants.FormatOnlyFaxAndEmail, FName, LName, FaxNum, Email);
string formatOnlyFaxAndAddress = String.Format(Constants.FormatOnlyFaxAndAddress, FName, LName, FaxNum, Address);
string formatOnlyEmailAndAddress = String.Format(Constants.FormatOnlyEmailAndAddress, FName, LName, Email, Address);
string formatOnlyPhoneAndMobileAndFax = String.Format(Constants.FormatOnlyPhoneAndMobileAndFax, FName, LName, PhoneNum, MobileNum, FaxNum);
string formatOnlyPhoneAndMobileAndFaxAndEmail = String.Format(Constants.FormatOnlyPhoneAndMobileAndFaxAndEmail, FName, LName, PhoneNum, MobileNum, FaxNum, Email);
string formatOnlyPhoneAndMobileAndFaxAndAddress = String.Format(Constants.FormatOnlyPhoneAndMobileAndFaxAndAddress, FName, LName, PhoneNum, MobileNum, FaxNum, Address);
string formatOnlyPhoneAndMobileAndEmailAndAddress = String.Format(Constants.FormatOnlyPhoneAndMobileAndEmailAndAddress, FName, LName, PhoneNum, MobileNum, Email, Address);
string formatOnlyMobileAndFaxAndEmail = String.Format(Constants.FormatOnlyMobileAndFaxAndEmail, FName, LName, MobileNum, FaxNum, Email);
string formatOnlyMobileAndFaxAndEmailAndAddress = String.Format(Constants.FormatOnlyMobileAndFaxAndEmailAndAddress, FName, LName, MobileNum, FaxNum, Email, Address);
string formatOnlyFaxAndEmailAndAddress = String.Format(Constants.FormatOnlyFaxAndEmailAndAddress, FName, LName, FaxNum, Email, Address);
Console.WriteLine // *******can someone suggest me to reduce/optimize the code, I wanna print only the value that is not NULL or String.Empty**********
(
((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatAll
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobileAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndMobileAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndMobileAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobileAndFax
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobile
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndFax
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhone
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndFaxAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndFax
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyMobile
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyFaxAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyFaxAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyFaxAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyFax
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyEmail
: formatOnlyAddress
);
/// <summary>
/// Displays the entry menu
/// </summary>
public void DisplayCoverMenu()
Console.Write(Constants.DisplayCoverMenu);
Console.ReadKey();
Thread.Sleep(Constants.ConstIntArray[5]);
Console.Clear();
/// <summary>
/// Displays the emain menu
/// </summary>
/// <returns></returns>
public int DisplayMainMenu()
Thread.Sleep(Constants.ConstIntArray[4]);
Console.Clear();
Dictionary<int, string> menuItem = Constants.DisplayMainMenu03;
int dictKey;
Console.WriteLine(Constants.DisplayMainMenu01);
for (int i = 0; i < menuItem.Count; i++) Console.WriteLine(Constants.DisplayMainMenu02, i + 1, menuItem[i + 1]);
do
Console.Write(Constants.DisplayMainMenu04);
int.TryParse(Console.ReadLine(), out dictKey);
while (!menuItem.ContainsKey(dictKey));
return dictKey;
/// <summary>
/// Writes error messages to the log file, if no such file exists, then file is created
/// </summary>
/// <param name="logFileName"></param>
/// <param name="log"></param>
/// <exception cref="IOException"></exception>
public static void WriteLogFile(string logFileName, string log)
try
if (!File.Exists(logFileName)) File.CreateText(logFileName);
else File.AppendAllLines(logFileName, new string String.Format(Constants.ErrorLogFormat, DateTime.Now, log));
catch (IOException e)
Console.WriteLine(e.Message);
InputEngine.cs
/*Written by AJ*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace PhoneBook
class InputEngine
/// <summary>
/// Adds single quotes('') around every element of a string array
/// </summary>
/// <param name="dataArr"></param>
/// <returns></returns>
public string AddSingleQuote(string dataArr)
// another approach
//List<string> resList = new List<string>();
//foreach (string str in dataArr) resList.Add((str != String.Empty) ? String.Format("012", ''', str, ''') : "NULL");
//return resList.ToArray();
return dataArr.ToList().Select(str => (str != String.Empty) ? String.Format(Constants.AddSingleQuote01, Constants.AddSingleQuote02, str, Constants.AddSingleQuote02) : Constants.AddSingleQuote03).ToArray();
/// <summary>
/// Helper func: gets user input
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>
private static string UserInHelper(string prompt)
Console.Write(Constants.UserInHelper,prompt);
return Console.ReadLine() ?? String.Empty;
/// <summary>
/// returns a processed string array of user inputs
/// </summary>
/// <returns></returns>
public string UserInput()
List<string> userDataList = new List<string>();
while (userDataList.Count!=7)
string fNameIn;
do
Console.Clear();
Console.Write(Constants.UserInput01);
fNameIn = Console.ReadLine() ?? String.Empty;
while (fNameIn.Equals(String.Empty));
userDataList.Add(fNameIn);
string promptArr = Constants.UserInput02;
for (int i = 0; i < promptArr.Length; i++) userDataList.Add(UserInHelper(promptArr[i]));
return userDataList.ToArray();
/// <summary>
/// gets the search items from user
/// </summary>
/// <param name="keyword"></param>
/// <returns></returns>
public Tuple<string,string> SearchInit(string keyword)
Dictionary<int, string> searchKeyDict = Constants.SearchInit05;
string sKey, sVal;
int dictKey;
do
Console.Clear();
Console.Write(Constants.SearchInit01,keyword);
int.TryParse(Console.ReadLine(), out dictKey);
while (!searchKeyDict.ContainsKey(dictKey) && dictKey!=Constants.SearchInit06);
if (dictKey==Constants.SearchInit06)
Console.WriteLine(Constants.SearchInit02);
Thread.Sleep(Constants.ConstIntArray[3]);
Console.WriteLine(Constants.SearchInit03);
Thread.Sleep(Constants.ConstIntArray[4]);
Environment.Exit(exitCode: Constants.SuceessExitCode);
sKey = searchKeyDict[dictKey];
do
Console.WriteLine(Constants.SearchInit04,keyword);
sVal = Console.ReadLine() ?? String.Empty;
while (sVal.Equals(String.Empty));
return new Tuple<string, string> (sKey, sVal);
Constants.cs
/*Written by AJ*/
using System.Collections.Generic;
namespace PhoneBook
class Constants
//all formatOnly strings
public const string FormatAll = "Name: 0 1nPhone: 2nMoblie: 3nFax: 4nEmail: 5nAddress: 6";
public const string FormatOnlyPhone = "Name: 0 1nPhone: 2";
public const string FormatOnlyMobile = "Name: 0 1nMobile: 2";
public const string FormatOnlyFax = "Name: 0 1nFax: 2";
public const string FormatOnlyEmail = "Name: 0 1nEmail: 2";
public const string FormatOnlyAddress = "Name: 0 1nAddress: 2";
public const string FormatOnlyPhoneAndMobile = "Name: 0 1nPhone: 2nMobile: 3" ;
public const string FormatOnlyPhoneAndFax = "Name: 0 1nPhone: 2nFax: 3" ;
public const string FormatOnlyPhoneAndFaxAndEmail = "Name: 0 1nPhone: 2nFax: 3nEmail: 4";
public const string FormatOnlyPhoneAndEmailAndAddress = "Name: 0 1nPhone: 2nEmail: 3nAddress: 4";
public const string FormatOnlyPhoneAndFaxAndAddress = "Name: 0 1nPhone: 2nFax: 3nAddress: 4";
public const string FormatOnlyPhoneAndEmail = "Name: 0 1nPhone: 2nEmail: 3";
public const string FormatOnlyPhoneAndAddress = "Name: 0 1nPhone: 2nAddress 3";
public const string FormatOnlyMobileAndFax = "Name: 0 1nMobile: 2nFax: 3";
public const string FormatOnlyMobileAndEmail = "Name: 0 1nMobile: 2nEmail: 3";
public const string FormatOnlyMobileAndEmailAndAddress = "Name: 0 1nMobile: 2nEmail: 3nAddress: 4";
public const string FormatOnlyMobileAndFaxAndAddress = "Name: 0 1nMobile: 2nFax: 3nAddress: 4";
public const string FormatOnlyMobileAndAddress = "Name: 0 1nMobile: 2nAddress: 3";
public const string FormatOnlyFaxAndEmail = "Name: 0 1nFax: 2nEmail: 3";
public const string FormatOnlyFaxAndAddress = "Name: 0 1nFax: 2nAddress: 3";
public const string FormatOnlyEmailAndAddress = "Name: 0 1nEmail: 2nAddress: 3";
public const string FormatOnlyPhoneAndMobileAndFax = "Name: 0 1nPhone: 2nMobile: 3nFax: 4";
public const string FormatOnlyPhoneAndMobileAndFaxAndEmail = "Name: 0 1nPhone: 2nMobile: 3nFax: 4nEmail: 5";
public const string FormatOnlyPhoneAndMobileAndFaxAndAddress = "Name: 0 1nPhone: 2nMobile: 3nFax: 4nAddress: 5";
public const string FormatOnlyPhoneAndMobileAndEmailAndAddress = "Name: 0 1nPhone: 2nMobile: 3nEmail: 4nAddress: 5";
public const string FormatOnlyMobileAndFaxAndEmail = "Name: 0 1nMobile: 2nFax: 3nEmail: 4";
public const string FormatOnlyMobileAndFaxAndEmailAndAddress = "Name: 0 1nMobile: 2nFax: 3nEmail: 4nAdress: 5";
public const string FormatOnlyFaxAndEmailAndAddress = "Name: 0 1nFax: 2nEmail: 3nAddress: 4";
// functions const objects
public const string UserInHelper = "plese enter 0 >>> ";
public const string UserInput01 = "Please enter First Name >>> ";
public const string SearchInit01 = "Please Pressn1 => First Namen2 => Last Namen3 => Phone Numbern4 => Mobile Numbern5 =>" +
" Fax Numbern6 => Emailn7 => Addressnto select the 0 keywordnn***OR Press 8 => to cancel and exit***nn>>> ";
public const string SearchInit02 = "Canceling...";
public const string SearchInit03 = "Exiting...";
public const string SearchInit04 = "Please enter the 0 value";
public const int SearchInit06 = 8;
public const string AddSingleQuote01 = "012";
public const char AddSingleQuote02 = ''';
public const string AddSingleQuote03 = "NULL";
public const int SuceessExitCode = 0;
public const int FailedExitCore = 1;
public const string DisplayCoverMenu = "nnnnnnnnnntttWelcome to SharpContracts: A Contact Management System by AlexnntttPlease Press 'Enter' To Continue...nnnttt";
public const string DisplayMainMenu01 = "rnnttMAIN MENUn";
public const string DisplayMainMenu02 = "tt00 1nn";
public const string DisplayMainMenu04 = "nnttPlease select <1-5> to operate:tt";
public const string RecoredUpdatedText = "nntttRecord Updated!!!";
public const string WriteToDbServer01 = ", ";
public const string WriteToDbServer02 = ");";
public const string OceStr = "1";
public const string ExistInDbWrapper01 = "Searching...nn";
public const string ExistInDbWrapper02 = "Item doesn't exist in the server!";
public const string Run01 = "search";
public const string Run02 = "update";
public const string Run03 = "delete";
public const string Dbname = "App_db_phoneBook";
public const string TableName = "PhoneBookRecoder";
// function readonly objects
public static readonly string UserInput02 = new string "Last Name", "Phone Number", "Mobile Number", "Fax Number", "Email", "Address" ;
public static readonly Dictionary<int,string> SearchInit05 = new Dictionary<int, string> 1, "FName" , 2, "LName" , 3, "PhoneNum" , 4, "MobNum" , 5, "FaxNum" , 6, "Email" , 7, "Address" ;
public static readonly Dictionary<int, string> DisplayMainMenu03 = new Dictionary<int, string> 1, "CREATE NEW CONTACT" , 2, "SEARCH CONTACT" , 3, "MODIFY CONTACT" , 4, "DELETE CONTACT" , 5, "EXIT" ;
// miscellaneous objects
public static readonly int ConstIntArray = new int 0, 7, 1000, 1500, 2000, 3000 ;
public const string ErrorGlobalMessage = "Something went wrong!nContract System AdministratornShutting Down...";
public const string ErrorLogFormat = "Time: 0 Error details: 1";
public const string LogFIleName = "phone_book_errror_log.log"; // locates in the current dir
// function protected pbjects (sql commads)
protected const string DeleteCommText = "DELETE FROM PhoneBookRecoder WHERE 0='1';";
protected const string UpdateCommText = "UPDATE PhoneBookRecoder SET 0='1' WHERE 2='3';";
protected const string WriteCommText = "INSERT INTO PhoneBookRecoder VALUES (";
protected const string ReadCommText = "SELECT * FROM PhoneBookRecoder WHERE 0='1' ORDER BY FName;";
protected const string ExistsCommText = "SELECT CASE WHEN EXISTS(SELECT * FROM PhoneBookRecoder WHERE 0='1') THEN 1 ELSE 0 END";
protected const string ExistsDbInServerExistCommText = "IF DB_ID('0') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string ExistsTableInDbInServerExistCommText = "IF OBJECT_ID (N'0', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string ExistsBothDbAndTableExistCommText = "IF DB_ID('0') IS NOT NULL AND OBJECT_ID (N'1', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string CreateTableInDbServerCommText = "USE 0; CREATE TABLE 1 ( FName nvarchar(15) NOT NULL, LName nvarchar(15), PhoneNum nvarchar(15)," +
"MobNum nvarchar(15), FaxNum nvarchar(15), Email nvarchar(25), Address nvarchar(100) );";
protected const string CreateDbInServerCommText = "CREATE DATABASE 0";
protected const string DeleteDbInServerCommText = "DROP DATABASE 0";
protected const string ConnectionStringWithDbname = @"Data Source=[Machine Name][Db Server Name];Initial Catalog=App_db_phoneBook;Integrated Security=True;";
protected const string ConnectionString = @"Data Source=[Machine Name][Db Server Name];Integrated Security=True;";
Program.cs
/*Written by AJ*/
namespace PhoneBook
class Program
static void Main(string args)
PhoneBookAppCore appCore = new PhoneBookAppCore();
appCore.Run();
c# sql-server database
I wrote this simple contact book app. It helps the user to store and retrieve contact information. The app uses a SQL database server to store all the user data. One significant fact is that the db and its table are only created when the user uses the application for the first time. Moreover, this app can log error information in a local .log file(it's possible to send the log file to the developer as well, if required(though not implemented in this project)). I've tried to apply my limited understanding of different concepts of core C#. I'd appreciate if someone(an experienced c# developer, if possible) to point out the mistakes that I have made and suggest how I could optimize this app. A non-related Question: is it possible to write this project exactly in C++?
PhoneBookAppCore.cs
/*Written by AJ*/
using System;
using System.Threading;
namespace PhoneBook
class PhoneBookAppCore
private static readonly InputEngine _inputEngline = new InputEngine();
private static readonly SqlEngine _sqlEngine = new SqlEngine();
/// <summary>
/// Wrapper func: checks if an entry exists in the db table
/// </summary>
/// <param name="keyword"></param>
/// <param name="show"></param>
/// <returns></returns>
private static Tuple<string,string,bool> ExistInDbWrapper(string keyword, bool show=true)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
var searchTuple = _inputEngline.SearchInit(keyword);
bool exists = _sqlEngine.ExistInDbServer(searchTuple.Item1, searchTuple.Item2);
if (show is true) Console.WriteLine(exists ? Constants.ExistInDbWrapper01 : Constants.ExistInDbWrapper02);
Thread.Sleep(Constants.ConstIntArray[4]);
return new Tuple<string, string, bool>(searchTuple.Item1, searchTuple.Item2, exists);
/// <summary>
/// Wrapper func: checks if an entry exists in the db table
/// </summary>
/// <param name="searchKeyword"></param>
/// <param name="updateKeyword"></param>
/// <returns></returns>
private static Tuple<string, string,string,string, bool> ExistInDbWrapper(string searchKeyword, string updateKeyword)
var searchTuple = ExistInDbWrapper(searchKeyword);
if (searchTuple.Item3 is false) return new Tuple<string, string, string, string, bool>(null,null,null,null,searchTuple.Item3);
var updateTuple = ExistInDbWrapper(updateKeyword, show:false);
Thread.Sleep(Constants.ConstIntArray[4]);
return new Tuple<string, string, string,string,bool>(updateTuple.Item1,updateTuple.Item2,searchTuple.Item1,searchTuple.Item2,searchTuple.Item3);
/// <summary>
/// Use this to run this app
/// </summary>
public void Run()
try
Init(Constants.Dbname, Constants.TableName);
//Display cover menu
OutputEngine outputEngine = new OutputEngine();
outputEngine.DisplayCoverMenu();
bool continueProgram = true;
while (continueProgram)
//display main menu
int userChoice = outputEngine.DisplayMainMenu();
switch (userChoice)
case 1:
CreateNewContact();
break;
case 2:
var dataTuple = ExistInDbWrapper(Constants.Run01);
if (dataTuple.Item3 is false) break;
else SearchContact(dataTuple.Item1, dataTuple.Item2);
dataTuple = null;
break;
case 3:
var dataTupleUpdate = ExistInDbWrapper(Constants.Run01, Constants.Run02);
if (dataTupleUpdate.Item5 is false) break;
else ModifyContact(dataTupleUpdate.Item1, dataTupleUpdate.Item2, dataTupleUpdate.Item3, dataTupleUpdate.Item4);
dataTupleUpdate = null;
break;
case 4:
dataTuple = ExistInDbWrapper(Constants.Run03);
if (dataTuple.Item3 is false) break;
else DeleteContact(dataTuple.Item1, dataTuple.Item2);
dataTuple = null;
break;
case 5:
continueProgram = false;
break;
catch (Exception e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
finally
Console.Clear();
Console.WriteLine(Constants.ErrorGlobalMessage);
Thread.Sleep(Constants.ConstIntArray[5]);
Exit(Constants.FailedExitCore);
/// <summary>
/// Wrapper func: searches an entry and displays result
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
private static void SearchContact(string searchKey, string searchValue)
string dataArr = _sqlEngine.ReadFromDbServer(searchKey, searchValue);
OutputEngine outputEEngineForDisplay = new OutputEngine();
outputEEngineForDisplay.SetProperties(outputEEngineForDisplay, dataArr);
outputEEngineForDisplay.DisplayPhoneBook();
Console.ReadKey();
/// <summary>
/// Wrapper func: modifies an existing db entry
/// </summary>
/// <param name="updateKey"></param>
/// <param name="updateValue"></param>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
private static void ModifyContact(string updateKey, string updateValue, string searchKey, string searchValue)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.UpdateDbServer(updateKey, updateValue, searchKey, searchValue);
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Wrapper func: deletes an entry from db
/// </summary>
/// <param name="deleteKey"></param>
/// <param name="deleteValue"></param>
private static void DeleteContact(string deleteKey, string deleteValue)
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.DeleteFromDbServer(deleteKey, deleteValue);
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Wrapper func: terminates an running app
/// </summary>
/// <param name="exitCode">S</param>
private static void Exit(int exitCode)
Environment.Exit(exitCode: exitCode);
/// <summary>
/// Wrapper func: creates new db table entries
/// </summary>
private static void CreateNewContact()
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
_sqlEngine.WriteToDbServer(_inputEngline.AddSingleQuote(_inputEngline.UserInput()));
Console.Write(Constants.RecoredUpdatedText);
Thread.Sleep(Constants.ConstIntArray[5]);
/// <summary>
/// Checks if a db and db tables exists or not; if no db or tb table, then creates them in the server
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
private static void Init(string dbName, string tableName)
bool isDbExists = _sqlEngine.ExistsDbInServer(dbName);
bool isTabExists = _sqlEngine.ExistsTableInDbInServer(tableName);
if (isDbExists is false && isTabExists is false)
_sqlEngine.CreateDbInServer(dbName);
_sqlEngine.CreateTableInDbServer(dbName, tableName);
else return;
SqlEngine.cs
/*Written by AJ*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
namespace PhoneBook // Constants.(fildname) could be simplified to only fildname since class SqlEngine inherits from class Constants
class SqlEngine : Constants //this inheritance is to gain access to protected sql command texts
private string _connectionStringWithDbname = Constants.ConnectionStringWithDbname;
private string _connectionString = Constants.ConnectionString;
/// <summary>
/// Enables conn with a db in the sql server
/// </summary>
/// <param name="connStr"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
private SqlConnection CreteDbLink(string connStr)
SqlConnection conn = new SqlConnection(connStr);
return conn;
/// <summary>
/// Inserts entry values in the db table
/// </summary>
/// <param name="dataArr"></param>
/// <exception cref="SqlException"></exception>
public void WriteToDbServer(string dataArr)
VoidFuncHelper(Constants.WriteCommText + String.Join(Constants.WriteToDbServer01, dataArr) + Constants.WriteToDbServer02, this._connectionStringWithDbname); // this string consists of one protected const string and two public const string
/// <summary>
/// Updates value of an entry in the db table
/// </summary>
/// <param name="updateKey"></param>
/// <param name="updateValue"></param>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <exception cref="SqlException"></exception>
public void UpdateDbServer(string updateKey, string updateValue, string searchKey, string searchValue)
VoidFuncHelper(String.Format(Constants.UpdateCommText, updateKey, updateValue, searchKey, searchValue), this._connectionStringWithDbname);
/// <summary>
/// Retrieves string array of searched entry from db
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public string ReadFromDbServer(string searchKey, string searchValue)
string readCommStr = String.Format(Constants.ReadCommText, searchKey, searchValue);
List<string> rawDataList = new List<string>();
SqlConnection conn = CreteDbLink(this._connectionStringWithDbname);
using (conn)
conn.Open();
SqlCommand sqlCommand = new SqlCommand(readCommStr, conn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) foreach (int i in Enumerable.Range(Constants.ConstIntArray[0], Constants.ConstIntArray[1])) rawDataList.Add(reader.GetValue(i).ToString());
conn.Close();
return rawDataList.ToArray();
/// <summary>
/// Checks if an entry exists in db table
/// </summary>
/// <param name="searchKey"></param>
/// <param name="searchValue"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistInDbServer(string searchKey, string searchValue)
return BoolFuncHelper(String.Format(Constants.ExistsCommText, searchKey, searchValue), this._connectionStringWithDbname);
/// <summary>
/// Deletes the value of a searched entry from db table
/// </summary>
/// <param name="deleteKey"></param>
/// <param name="deleteValue"></param>
/// <exception cref="SqlException"></exception>
public void DeleteFromDbServer(string deleteKey, string deleteValue)
VoidFuncHelper(String.Format(Constants.DeleteCommText, deleteKey, deleteValue), this._connectionStringWithDbname);
/// <summary>
/// Checks if a db exists in the server
/// </summary>
/// <param name="dbName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsDbInServer(string dbName)
return BoolFuncHelper(String.Format(Constants.ExistsDbInServerExistCommText, dbName), this._connectionString);//only db exists or not
/// <summary>
/// Checks if a table exists in the db server
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsTableInDbInServer(string tableName)
return BoolFuncHelper(String.Format(Constants.ExistsTableInDbInServerExistCommText, tableName), this._connectionString); //look out could be this._connectionStringWithDbname
/// <summary>
/// returns True if both db and table exist in the server
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <returns></returns>
/// <exception cref="SqlException"></exception>
public bool ExistsBothDbAndTable(string dbName, string tableName)
return BoolFuncHelper(String.Format(Constants.ExistsBothDbAndTableExistCommText, dbName, tableName), this._connectionStringWithDbname);
/// <summary>
/// Creates a db in the sql server
/// </summary>
/// <param name="dbName"></param>
/// <exception cref="SqlException"></exception>
public void CreateDbInServer(string dbName)
VoidFuncHelper(String.Format(Constants.CreateDbInServerCommText, dbName), this._connectionString);
/// <summary>
/// Deletes a db from the sql server
/// </summary>
/// <param name="dbName"></param>
/// <exception cref="SqlException"></exception>
public void DeleteDbInServer(string dbName)
VoidFuncHelper(String.Format(Constants.DeleteDbInServerCommText, dbName), this._connectionString);
/// <summary>
/// Creates a table in the specified db
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <exception cref="SqlException"></exception>
public void CreateTableInDbServer(string dbName, string tableName)
VoidFuncHelper(String.Format(Constants.CreateTableInDbServerCommText, dbName, tableName), this._connectionString); //look out could be this._connectionStringWithDbname
/// <summary>
/// Helper func : enables db conn
/// </summary>
/// <param name="commStr"></param>
/// <param name="connStr"></param>
/// <returns>bool value from the executed sql command</returns>
/// <exception cref="SqlException"></exception>
private bool BoolFuncHelper(string commStr, string connStr)
bool exist = false;
SqlConnection conn = CreteDbLink(connStr);
try
using (conn)
conn.Open();
SqlCommand sqlCommand = new SqlCommand(commStr, conn);
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) exist = (reader.GetValue(Constants.ConstIntArray[0]).ToString() == Constants.OceStr ? true : false);
conn.Close();
catch (SqlException e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
Environment.Exit(Constants.FailedExitCore);
return exist;
/// <summary>
/// Helper func : enables db connection and executes sql comm
/// </summary>
/// <param name="commStr"></param>
/// <param name="connStr"></param>
/// <exception cref="SqlException"></exception>
private void VoidFuncHelper(string commStr, string connStr)
try
using (SqlConnection conn = new SqlConnection(connStr))
conn.Open();
SqlCommand sqlCom = conn.CreateCommand();
sqlCom.CommandText = commStr;
sqlCom.ExecuteNonQuery();
conn.Close();
catch (SqlException e)
Console.WriteLine(e.Message);
OutputEngine.WriteLogFile(Constants.LogFIleName, e.Message);
Environment.Exit(Constants.FailedExitCore);
OutputEngine.cs
/*Written by AJ*/
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;
using System.IO;
namespace PhoneBook
class OutputEngine
// list of default values of properties
private string _fName = String.Empty;
private string _lName = String.Empty;
private string _pNum = String.Empty;
private string _mNum = String.Empty;
private string _fNum = String.Empty;
private string _email = String.Empty;
private string _address = String.Empty;
// list of properties
public string FName get => this._fName; set => _fName = value;
public string LName get => this._lName; set => _lName = value;
public string PhoneNum get => this._pNum; set => _pNum = value;
public string MobileNum get => this._mNum; set => _mNum = value;
public string FaxNum get => this._fNum; set => _fNum = value;
public string Email get => this._email; set => _email = value;
public string Address get => this._address; set => _address = value;
/// <summary>
/// Assigns values to the properties of a class instance
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance"></param>
/// <param name="dataArr"></param>
public void SetProperties<T>(T instance, object dataArr) where T : class
Enumerable.Zip(instance.GetType().GetRuntimeProperties(), dataArr, Tuple.Create).ToList().ForEach((tup) => tup.Item1.SetValue(instance, tup.Item2, null));
/// <summary>
/// Displays phonebook entries
/// </summary>
public void DisplayPhoneBook() // can someone suggest me to reduce/optimize the code, I wanna print only the value that is not NULL or String.Empty
Thread.Sleep(Constants.ConstIntArray[2]);
Console.Clear();
string formatAll = String.Format(Constants.FormatAll, FName, LName, PhoneNum, MobileNum, FaxNum, Email, Address);
string formatOnlyPhone = String.Format(Constants.FormatOnlyPhone, FName, LName, PhoneNum);
string formatOnlyMobile = String.Format(Constants.FormatOnlyMobile, FName, LName, MobileNum);
string formatOnlyFax = String.Format(Constants.FormatOnlyFax, FName, LName, FaxNum);
string formatOnlyEmail = String.Format(Constants.FormatOnlyEmail, FName, LName, Email);
string formatOnlyAddress = String.Format(Constants.FormatOnlyAddress, FName, LName, Address);
string formatOnlyPhoneAndMobile = String.Format(Constants.FormatOnlyPhoneAndMobile, FName, LName, PhoneNum, MobileNum);
string formatOnlyPhoneAndFax = String.Format(Constants.FormatOnlyPhoneAndFax, FName, LName, PhoneNum, FaxNum);
string formatOnlyPhoneAndFaxAndEmail = String.Format(Constants.FormatOnlyPhoneAndFaxAndEmail, FName, LName, PhoneNum, FaxNum, Email);
string formatOnlyPhoneAndEmailAndAddress = String.Format(Constants.FormatOnlyPhoneAndEmailAndAddress, FName, LName, PhoneNum, Email, Address);
string formatOnlyPhoneAndFaxAndAddress = String.Format(Constants.FormatOnlyPhoneAndFaxAndAddress, FName, LName, PhoneNum, FaxNum, Address);
string formatOnlyPhoneAndEmail = String.Format(Constants.FormatOnlyPhoneAndEmail, FName, LName, PhoneNum, Email);
string formatOnlyPhoneAndAddress = String.Format(Constants.FormatOnlyPhoneAndAddress, FName, LName, PhoneNum, Address);
string formatOnlyMobileAndFax = String.Format(Constants.FormatOnlyMobileAndFax, FName, LName, MobileNum, FaxNum);
string formatOnlyMobileAndEmail = String.Format(Constants.FormatOnlyMobileAndEmail, FName, LName, MobileNum, Email);
string formatOnlyMobileAndEmailAndAddress = String.Format(Constants.FormatOnlyMobileAndEmailAndAddress, FName, LName, MobileNum, Email, Address);
string formatOnlyMobileAndFaxAndAddress = String.Format(Constants.FormatOnlyMobileAndFaxAndAddress, FName, LName, MobileNum, FaxNum, Address);
string formatOnlyMobileAndAddress = String.Format(Constants.FormatOnlyMobileAndAddress, FName, LName, MobileNum, Address);
string formatOnlyFaxAndEmail = String.Format(Constants.FormatOnlyFaxAndEmail, FName, LName, FaxNum, Email);
string formatOnlyFaxAndAddress = String.Format(Constants.FormatOnlyFaxAndAddress, FName, LName, FaxNum, Address);
string formatOnlyEmailAndAddress = String.Format(Constants.FormatOnlyEmailAndAddress, FName, LName, Email, Address);
string formatOnlyPhoneAndMobileAndFax = String.Format(Constants.FormatOnlyPhoneAndMobileAndFax, FName, LName, PhoneNum, MobileNum, FaxNum);
string formatOnlyPhoneAndMobileAndFaxAndEmail = String.Format(Constants.FormatOnlyPhoneAndMobileAndFaxAndEmail, FName, LName, PhoneNum, MobileNum, FaxNum, Email);
string formatOnlyPhoneAndMobileAndFaxAndAddress = String.Format(Constants.FormatOnlyPhoneAndMobileAndFaxAndAddress, FName, LName, PhoneNum, MobileNum, FaxNum, Address);
string formatOnlyPhoneAndMobileAndEmailAndAddress = String.Format(Constants.FormatOnlyPhoneAndMobileAndEmailAndAddress, FName, LName, PhoneNum, MobileNum, Email, Address);
string formatOnlyMobileAndFaxAndEmail = String.Format(Constants.FormatOnlyMobileAndFaxAndEmail, FName, LName, MobileNum, FaxNum, Email);
string formatOnlyMobileAndFaxAndEmailAndAddress = String.Format(Constants.FormatOnlyMobileAndFaxAndEmailAndAddress, FName, LName, MobileNum, FaxNum, Email, Address);
string formatOnlyFaxAndEmailAndAddress = String.Format(Constants.FormatOnlyFaxAndEmailAndAddress, FName, LName, FaxNum, Email, Address);
Console.WriteLine // *******can someone suggest me to reduce/optimize the code, I wanna print only the value that is not NULL or String.Empty**********
(
((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatAll
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobileAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndMobileAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndMobileAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobileAndFax
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndMobile
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndFax
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyPhoneAndEmail
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyPhoneAndAddress
: ((FName != String.Empty) && (PhoneNum != String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyPhone
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndFaxAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndFaxAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndFaxAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndFax
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyMobileAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyMobileAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum != String.Empty) && (FaxNum == String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyMobile
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyFaxAndEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyFaxAndEmail
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address != String.Empty)) ? formatOnlyFaxAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum != String.Empty) && (Email == String.Empty) && (Address == String.Empty)) ? formatOnlyFax
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address != String.Empty)) ? formatOnlyEmailAndAddress
: ((FName != String.Empty) && (PhoneNum == String.Empty) && (MobileNum == String.Empty) && (FaxNum == String.Empty) && (Email != String.Empty) && (Address == String.Empty)) ? formatOnlyEmail
: formatOnlyAddress
);
/// <summary>
/// Displays the entry menu
/// </summary>
public void DisplayCoverMenu()
Console.Write(Constants.DisplayCoverMenu);
Console.ReadKey();
Thread.Sleep(Constants.ConstIntArray[5]);
Console.Clear();
/// <summary>
/// Displays the emain menu
/// </summary>
/// <returns></returns>
public int DisplayMainMenu()
Thread.Sleep(Constants.ConstIntArray[4]);
Console.Clear();
Dictionary<int, string> menuItem = Constants.DisplayMainMenu03;
int dictKey;
Console.WriteLine(Constants.DisplayMainMenu01);
for (int i = 0; i < menuItem.Count; i++) Console.WriteLine(Constants.DisplayMainMenu02, i + 1, menuItem[i + 1]);
do
Console.Write(Constants.DisplayMainMenu04);
int.TryParse(Console.ReadLine(), out dictKey);
while (!menuItem.ContainsKey(dictKey));
return dictKey;
/// <summary>
/// Writes error messages to the log file, if no such file exists, then file is created
/// </summary>
/// <param name="logFileName"></param>
/// <param name="log"></param>
/// <exception cref="IOException"></exception>
public static void WriteLogFile(string logFileName, string log)
try
if (!File.Exists(logFileName)) File.CreateText(logFileName);
else File.AppendAllLines(logFileName, new string String.Format(Constants.ErrorLogFormat, DateTime.Now, log));
catch (IOException e)
Console.WriteLine(e.Message);
InputEngine.cs
/*Written by AJ*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace PhoneBook
class InputEngine
/// <summary>
/// Adds single quotes('') around every element of a string array
/// </summary>
/// <param name="dataArr"></param>
/// <returns></returns>
public string AddSingleQuote(string dataArr)
// another approach
//List<string> resList = new List<string>();
//foreach (string str in dataArr) resList.Add((str != String.Empty) ? String.Format("012", ''', str, ''') : "NULL");
//return resList.ToArray();
return dataArr.ToList().Select(str => (str != String.Empty) ? String.Format(Constants.AddSingleQuote01, Constants.AddSingleQuote02, str, Constants.AddSingleQuote02) : Constants.AddSingleQuote03).ToArray();
/// <summary>
/// Helper func: gets user input
/// </summary>
/// <param name="prompt"></param>
/// <returns></returns>
private static string UserInHelper(string prompt)
Console.Write(Constants.UserInHelper,prompt);
return Console.ReadLine() ?? String.Empty;
/// <summary>
/// returns a processed string array of user inputs
/// </summary>
/// <returns></returns>
public string UserInput()
List<string> userDataList = new List<string>();
while (userDataList.Count!=7)
string fNameIn;
do
Console.Clear();
Console.Write(Constants.UserInput01);
fNameIn = Console.ReadLine() ?? String.Empty;
while (fNameIn.Equals(String.Empty));
userDataList.Add(fNameIn);
string promptArr = Constants.UserInput02;
for (int i = 0; i < promptArr.Length; i++) userDataList.Add(UserInHelper(promptArr[i]));
return userDataList.ToArray();
/// <summary>
/// gets the search items from user
/// </summary>
/// <param name="keyword"></param>
/// <returns></returns>
public Tuple<string,string> SearchInit(string keyword)
Dictionary<int, string> searchKeyDict = Constants.SearchInit05;
string sKey, sVal;
int dictKey;
do
Console.Clear();
Console.Write(Constants.SearchInit01,keyword);
int.TryParse(Console.ReadLine(), out dictKey);
while (!searchKeyDict.ContainsKey(dictKey) && dictKey!=Constants.SearchInit06);
if (dictKey==Constants.SearchInit06)
Console.WriteLine(Constants.SearchInit02);
Thread.Sleep(Constants.ConstIntArray[3]);
Console.WriteLine(Constants.SearchInit03);
Thread.Sleep(Constants.ConstIntArray[4]);
Environment.Exit(exitCode: Constants.SuceessExitCode);
sKey = searchKeyDict[dictKey];
do
Console.WriteLine(Constants.SearchInit04,keyword);
sVal = Console.ReadLine() ?? String.Empty;
while (sVal.Equals(String.Empty));
return new Tuple<string, string> (sKey, sVal);
Constants.cs
/*Written by AJ*/
using System.Collections.Generic;
namespace PhoneBook
class Constants
//all formatOnly strings
public const string FormatAll = "Name: 0 1nPhone: 2nMoblie: 3nFax: 4nEmail: 5nAddress: 6";
public const string FormatOnlyPhone = "Name: 0 1nPhone: 2";
public const string FormatOnlyMobile = "Name: 0 1nMobile: 2";
public const string FormatOnlyFax = "Name: 0 1nFax: 2";
public const string FormatOnlyEmail = "Name: 0 1nEmail: 2";
public const string FormatOnlyAddress = "Name: 0 1nAddress: 2";
public const string FormatOnlyPhoneAndMobile = "Name: 0 1nPhone: 2nMobile: 3" ;
public const string FormatOnlyPhoneAndFax = "Name: 0 1nPhone: 2nFax: 3" ;
public const string FormatOnlyPhoneAndFaxAndEmail = "Name: 0 1nPhone: 2nFax: 3nEmail: 4";
public const string FormatOnlyPhoneAndEmailAndAddress = "Name: 0 1nPhone: 2nEmail: 3nAddress: 4";
public const string FormatOnlyPhoneAndFaxAndAddress = "Name: 0 1nPhone: 2nFax: 3nAddress: 4";
public const string FormatOnlyPhoneAndEmail = "Name: 0 1nPhone: 2nEmail: 3";
public const string FormatOnlyPhoneAndAddress = "Name: 0 1nPhone: 2nAddress 3";
public const string FormatOnlyMobileAndFax = "Name: 0 1nMobile: 2nFax: 3";
public const string FormatOnlyMobileAndEmail = "Name: 0 1nMobile: 2nEmail: 3";
public const string FormatOnlyMobileAndEmailAndAddress = "Name: 0 1nMobile: 2nEmail: 3nAddress: 4";
public const string FormatOnlyMobileAndFaxAndAddress = "Name: 0 1nMobile: 2nFax: 3nAddress: 4";
public const string FormatOnlyMobileAndAddress = "Name: 0 1nMobile: 2nAddress: 3";
public const string FormatOnlyFaxAndEmail = "Name: 0 1nFax: 2nEmail: 3";
public const string FormatOnlyFaxAndAddress = "Name: 0 1nFax: 2nAddress: 3";
public const string FormatOnlyEmailAndAddress = "Name: 0 1nEmail: 2nAddress: 3";
public const string FormatOnlyPhoneAndMobileAndFax = "Name: 0 1nPhone: 2nMobile: 3nFax: 4";
public const string FormatOnlyPhoneAndMobileAndFaxAndEmail = "Name: 0 1nPhone: 2nMobile: 3nFax: 4nEmail: 5";
public const string FormatOnlyPhoneAndMobileAndFaxAndAddress = "Name: 0 1nPhone: 2nMobile: 3nFax: 4nAddress: 5";
public const string FormatOnlyPhoneAndMobileAndEmailAndAddress = "Name: 0 1nPhone: 2nMobile: 3nEmail: 4nAddress: 5";
public const string FormatOnlyMobileAndFaxAndEmail = "Name: 0 1nMobile: 2nFax: 3nEmail: 4";
public const string FormatOnlyMobileAndFaxAndEmailAndAddress = "Name: 0 1nMobile: 2nFax: 3nEmail: 4nAdress: 5";
public const string FormatOnlyFaxAndEmailAndAddress = "Name: 0 1nFax: 2nEmail: 3nAddress: 4";
// functions const objects
public const string UserInHelper = "plese enter 0 >>> ";
public const string UserInput01 = "Please enter First Name >>> ";
public const string SearchInit01 = "Please Pressn1 => First Namen2 => Last Namen3 => Phone Numbern4 => Mobile Numbern5 =>" +
" Fax Numbern6 => Emailn7 => Addressnto select the 0 keywordnn***OR Press 8 => to cancel and exit***nn>>> ";
public const string SearchInit02 = "Canceling...";
public const string SearchInit03 = "Exiting...";
public const string SearchInit04 = "Please enter the 0 value";
public const int SearchInit06 = 8;
public const string AddSingleQuote01 = "012";
public const char AddSingleQuote02 = ''';
public const string AddSingleQuote03 = "NULL";
public const int SuceessExitCode = 0;
public const int FailedExitCore = 1;
public const string DisplayCoverMenu = "nnnnnnnnnntttWelcome to SharpContracts: A Contact Management System by AlexnntttPlease Press 'Enter' To Continue...nnnttt";
public const string DisplayMainMenu01 = "rnnttMAIN MENUn";
public const string DisplayMainMenu02 = "tt00 1nn";
public const string DisplayMainMenu04 = "nnttPlease select <1-5> to operate:tt";
public const string RecoredUpdatedText = "nntttRecord Updated!!!";
public const string WriteToDbServer01 = ", ";
public const string WriteToDbServer02 = ");";
public const string OceStr = "1";
public const string ExistInDbWrapper01 = "Searching...nn";
public const string ExistInDbWrapper02 = "Item doesn't exist in the server!";
public const string Run01 = "search";
public const string Run02 = "update";
public const string Run03 = "delete";
public const string Dbname = "App_db_phoneBook";
public const string TableName = "PhoneBookRecoder";
// function readonly objects
public static readonly string UserInput02 = new string "Last Name", "Phone Number", "Mobile Number", "Fax Number", "Email", "Address" ;
public static readonly Dictionary<int,string> SearchInit05 = new Dictionary<int, string> 1, "FName" , 2, "LName" , 3, "PhoneNum" , 4, "MobNum" , 5, "FaxNum" , 6, "Email" , 7, "Address" ;
public static readonly Dictionary<int, string> DisplayMainMenu03 = new Dictionary<int, string> 1, "CREATE NEW CONTACT" , 2, "SEARCH CONTACT" , 3, "MODIFY CONTACT" , 4, "DELETE CONTACT" , 5, "EXIT" ;
// miscellaneous objects
public static readonly int ConstIntArray = new int 0, 7, 1000, 1500, 2000, 3000 ;
public const string ErrorGlobalMessage = "Something went wrong!nContract System AdministratornShutting Down...";
public const string ErrorLogFormat = "Time: 0 Error details: 1";
public const string LogFIleName = "phone_book_errror_log.log"; // locates in the current dir
// function protected pbjects (sql commads)
protected const string DeleteCommText = "DELETE FROM PhoneBookRecoder WHERE 0='1';";
protected const string UpdateCommText = "UPDATE PhoneBookRecoder SET 0='1' WHERE 2='3';";
protected const string WriteCommText = "INSERT INTO PhoneBookRecoder VALUES (";
protected const string ReadCommText = "SELECT * FROM PhoneBookRecoder WHERE 0='1' ORDER BY FName;";
protected const string ExistsCommText = "SELECT CASE WHEN EXISTS(SELECT * FROM PhoneBookRecoder WHERE 0='1') THEN 1 ELSE 0 END";
protected const string ExistsDbInServerExistCommText = "IF DB_ID('0') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string ExistsTableInDbInServerExistCommText = "IF OBJECT_ID (N'0', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string ExistsBothDbAndTableExistCommText = "IF DB_ID('0') IS NOT NULL AND OBJECT_ID (N'1', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res;";
protected const string CreateTableInDbServerCommText = "USE 0; CREATE TABLE 1 ( FName nvarchar(15) NOT NULL, LName nvarchar(15), PhoneNum nvarchar(15)," +
"MobNum nvarchar(15), FaxNum nvarchar(15), Email nvarchar(25), Address nvarchar(100) );";
protected const string CreateDbInServerCommText = "CREATE DATABASE 0";
protected const string DeleteDbInServerCommText = "DROP DATABASE 0";
protected const string ConnectionStringWithDbname = @"Data Source=[Machine Name][Db Server Name];Initial Catalog=App_db_phoneBook;Integrated Security=True;";
protected const string ConnectionString = @"Data Source=[Machine Name][Db Server Name];Integrated Security=True;";
Program.cs
/*Written by AJ*/
namespace PhoneBook
class Program
static void Main(string args)
PhoneBookAppCore appCore = new PhoneBookAppCore();
appCore.Run();
c# sql-server database
asked Jul 11 at 13:59
A J
1639
1639
Have you thought of using a DataTable? It would simplify quite a bit of your code.
â tinstaafl
Jul 11 at 17:05
@tinstaafl could u give me an example?
â A J
Jul 11 at 17:49
Here's a tutorial that should help you out.
â tinstaafl
Jul 11 at 21:38
add a comment |Â
Have you thought of using a DataTable? It would simplify quite a bit of your code.
â tinstaafl
Jul 11 at 17:05
@tinstaafl could u give me an example?
â A J
Jul 11 at 17:49
Here's a tutorial that should help you out.
â tinstaafl
Jul 11 at 21:38
Have you thought of using a DataTable? It would simplify quite a bit of your code.
â tinstaafl
Jul 11 at 17:05
Have you thought of using a DataTable? It would simplify quite a bit of your code.
â tinstaafl
Jul 11 at 17:05
@tinstaafl could u give me an example?
â A J
Jul 11 at 17:49
@tinstaafl could u give me an example?
â A J
Jul 11 at 17:49
Here's a tutorial that should help you out.
â tinstaafl
Jul 11 at 21:38
Here's a tutorial that should help you out.
â tinstaafl
Jul 11 at 21:38
add a comment |Â
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f198287%2fcontactbook-console-based-app%23new-answer', 'question_page');
);
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Have you thought of using a DataTable? It would simplify quite a bit of your code.
â tinstaafl
Jul 11 at 17:05
@tinstaafl could u give me an example?
â A J
Jul 11 at 17:49
Here's a tutorial that should help you out.
â tinstaafl
Jul 11 at 21:38