/* * Method Name: writeCompToJsonFile * Purpose: Converts the inputed data to a JSON file and also calls the validation method * Arguments: CompanyInventory Object * Output: Void */ private static void writeCompToJsonFile(CompanyInventory compInv) { //Serlialization string json = JsonConvert.SerializeObject(compInv); string data = json; string Schema = ""; ReadFile("Schema.json", out Schema); IList <string> messages; if (ValidateEnteredData(data, Schema, out messages)) // Note: messages parameter is optional { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine($"\nData file is valid.\n"); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; File.WriteAllText("CompanyInfo.json", json); } else { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine($"\nERROR:\tData file is invalid.\n"); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; // Report validation error messages foreach (string msg in messages) { Console.WriteLine($"\t{msg}"); } } }
/// <summary> /// Save each row from the uploaded file in the CompanyInventory db table /// </summary> /// <param name="item">The item to be saved in the CompanyInventory db table</param> public int SaveInventoryItem(CompanyInventory item) { try { db.Save(item); } catch (Exception ex) { return(-1); } return(item.Id); }
//Main Method static void Main(string[] args) { //Start of the Program Console.WriteLine("\n PASSWORD-MANAGER PREPARED BY SANDY - Copyright 2019\n"); //Global Variables string temp; int value; bool restart = false; //bools used in while loops string Schema; /* * Note: It creates the JSON File in teh Debug Folder */ var fileInfo = new FileInfo("CompanyInfo.json"); //If it doesn't exist create new one or if it is empty proceed from here if (!fileInfo.Exists || fileInfo.Length == 0) { /* * Introduction to the program */ Console.WriteLine("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine("| Account Entries |"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); Console.WriteLine("\nEMPTY! Please add Some Accounts"); var myFile = File.Create("CompanyInfo.json"); //Create if empty myFile.Close(); Console.WriteLine("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine("| Menu |"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.Write("|Press A to add the Account |"); Console.Write("\n|Press Q to Quit the Application |"); Console.WriteLine("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); bool f = false; //To check for the valid input while (f == false) { Console.Write("Enter Here: "); temp = Console.ReadLine(); f = true; if (temp.Equals("a") || temp.Equals("A")) //If the user wants to add the account information { CompanyInventory companyDb = new CompanyInventory(); //New company Database object, which will store the Accounts bool complete; //To add as many accounts in the file do { Company comp = new Company(); // New Company object Console.WriteLine("\n\nPlease enter the following information...\n"); bool okay = false; Console.Write("Decription: "); while (okay == false) { okay = true; comp.name = Console.ReadLine(); if (comp.name == "") { //Validation Console.WriteLine("\nDescription is required!!\n"); Console.Write("Description: "); okay = false; } } Account acc = new Account(); Console.Write("UserID: "); bool flag = false; while (flag == false) { flag = true; acc.userId = Console.ReadLine(); if (acc.userId == "") { //Validation Console.WriteLine("\nUserID is required!!\n"); Console.Write("UserID:"); flag = false; } } Password pass = new Password(); //New Password Object to store the password properties bool good = false; while (good == false) { good = true; Console.Write("Password: "******"ERROR: Invalid password format"); good = false; } catch (InvalidOperationException) { Console.WriteLine("Password is required!!!"); good = false; } } Console.Write("LoginUrl: "); acc.loginUrl = Console.ReadLine(); //string pattern = "(\\http[s] ?:\\/\\/)?([^\\/\\s] +\\/)(.*)"; Console.Write("Account#: "); acc.AccountNum = Console.ReadLine(); DateTime dateNow = DateTime.Now; pass.LastReset = dateNow.ToShortDateString(); acc.addPass(pass); comp.addAcc(acc); companyDb.addComp(comp); Console.Write("\nAdd another Account? (y/n): "); complete = Console.ReadKey().KeyChar != 'y'; if (complete.Equals(true)) { Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; Console.WriteLine("\n***Please restart the application***\n"); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; } } while (!complete); writeCompToJsonFile(companyDb); } else if (temp.Equals("q") || temp.Equals("Q")) { Console.WriteLine("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine("| Thank you for using my Application! |"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.Environment.Exit(1); } else { Console.WriteLine("***Please enter Valid Input***"); f = false; } } } else { while (restart == false) //used to repeat the process if user make mistake { restart.Equals(true); CompanyInventory readDb = new CompanyInventory(); //New Company DB to store the info readDb = ReadJsonFile(); //Intro Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine("| Account Entries |"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); if (readDb.db.Count == 0) { Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; Console.WriteLine("\nEMPTY! Please add Some Accounts\n"); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; } int num = 1; //If data exists, Show the Account Decription (Name) foreach (Company company in readDb.db) { Console.Write((num) + $". {company.name}"); Console.WriteLine(); num = num + 1; } Console.WriteLine("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine("| Menu |"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.Write("|Press A to add the Account |"); Console.WriteLine("\n|Press # corresponding to the entry to read or update the Account Info |"); Console.WriteLine("|Press Q to Quit the Application |"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); Console.Write("Enter Here: "); temp = Console.ReadLine(); if (int.TryParse(temp, out value) || temp.Equals("Q") || temp.Equals("q") || temp.Equals("a") || temp.Equals("A")) { } else { //ERROR Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; Console.WriteLine("\n***Please enter valid input!!***\n"); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; } //If user wants to add if (temp.Equals("a") || temp.Equals("A")) { bool complete2; do { Company comp = new Company(); Console.WriteLine("\n\nPlease enter the following information...\n"); bool okay = false; bool flag = false; bool good = false; Console.Write("Decription: "); while (okay == false) { okay = true; comp.name = Console.ReadLine(); if (comp.name == "") { Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; Console.WriteLine("\n***Description is required!!***\n"); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.Write("Description: "); okay = false; } } Account acc = new Account(); Console.Write("UserID: "); while (flag == false) { flag = true; acc.userId = Console.ReadLine(); if (acc.userId == "") { //ERROR Message Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; Console.WriteLine("\nUserID is required!!\n"); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.Write("UserID:"); flag = false; } } Password pass = new Password(); while (good == false) { good = true; Console.Write("Password: "******"\nERROR: Invalid password format\n"); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; good = false; } catch (InvalidOperationException) { //ERROR Message Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("\nPassword is required!!!"); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; good = false; } } Console.Write("LoginUrl: "); acc.loginUrl = Console.ReadLine(); Console.Write("Account#: "); acc.AccountNum = Console.ReadLine(); DateTime dateNow = DateTime.Now; pass.LastReset = dateNow.ToShortDateString(); acc.addPass(pass); comp.addAcc(acc); readDb.addComp(comp); Console.Write("\nAdd another item? (y/n): "); complete2 = Console.ReadKey().KeyChar != 'y'; } while (!complete2); //Write the entered data to a JSON File writeCompToJsonFile(readDb); restart.Equals(false); } //if number(int) is entered, It will try to parse- If successful then will show the output and if not displays the error message else if (int.TryParse(temp, out value)) { int EntryNum = value - 1; try { //Accessing the information based on the user input Console.WriteLine("\n" + value + $". {readDb.db[EntryNum].name}"); Console.WriteLine(); foreach (Account account in readDb.db[EntryNum].Inventory) { string readpassword = ""; string readLabel = ""; ushort readNum = 0; string readDate = ""; Console.WriteLine($"UserID: {account.userId}"); foreach (Password password in readDb.db[EntryNum].Inventory[0].passDb) { readpassword = password.value; readLabel = password.StrengthText; readNum = password.StrengthNum; readDate = password.LastReset; } Console.WriteLine($"Password: {readpassword}"); Console.WriteLine($"Password Strength: {readLabel} ({readNum})%"); Console.WriteLine($"Password Reset Date: {readDate}"); Console.WriteLine($"LoginUrl: {account.loginUrl}"); Console.WriteLine($"Account #: {account.AccountNum}"); } //Second Menu Console.WriteLine("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine("| Press M to for Main Menu |"); Console.WriteLine("| Press P to update the password |"); Console.WriteLine("| Press D to delete the Account Info |"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); Console.Write("Enter Here: "); temp = Console.ReadLine(); //For Main Menu if (temp.Equals("M") || temp.Equals("m")) { restart.Equals(false); } //For Password Change Request else if (temp.Equals("P") || temp.Equals("p")) { Console.Write("\nNew Password: "******"***Password Changed***"); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; restart.Equals(false); } //To Delete the Account Information else if (temp.Equals("D") || temp.Equals("d")) { try { Console.Write("Delete?(Y/N): "); temp = Console.ReadLine(); if (temp.Equals("Y") || temp.Equals("y")) { readDb.db.RemoveAt(EntryNum); writeCompToJsonFile(readDb); restart.Equals(false); } else if (temp.Equals("N") || temp.Equals("n")) { restart.Equals(false); } else { throw new IndexOutOfRangeException(); //Throws exception to handle the wrong input } } catch (Exception e) //Catches all the exceptions { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("\n***Please enter a valid input!!***\n"); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; } } else { throw new IndexOutOfRangeException();//Throws exception to handle the wrong input } } catch (Exception e) //Catches all the exceptions { Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("\n***Please enter valid number!!***\n"); Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; restart.Equals(false); } } //IF wants to quit else if (temp.Equals("q") || temp.Equals("Q")) { Console.WriteLine("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine("| Thank you for using my Application! |"); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); System.Environment.Exit(1); } } } }
public async Task <HttpResponseMessage> SaveData() { Umbraco.Core.Services.IContentService _contentService = ApplicationContext.Current.Services.ContentService; UmbracoHelper umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var httpCurrentUser = HttpContext.Current.Request.Form.AllKeys.Count() > 0 ? HttpContext.Current.Request.Form["CurrentUserId"] : "0"; var httpCurrentUserName = HttpContext.Current.Request.Form.AllKeys.Count() > 0 ? HttpContext.Current.Request.Form["CurrentUserName"] : "******"; var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"]; if (httpPostedFile != null) { int lastPos = httpPostedFile.FileName.LastIndexOf('\\'); string[] fileName = httpPostedFile.FileName.Substring(++lastPos).Split(new char[] { '.' }); string name = fileName[0]; string extension = fileName[1]; if (extension != "xls" && extension != "xlsx") { log.Info(string.Format("The Provided File is not an xls file.")); return(Request.CreateResponse(HttpStatusCode.BadRequest, "The Provided File is not an xls file.", "application/json")); } // Get the complete file path var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/UploadedFiles"), httpPostedFile.FileName); // Save the uploaded file to "UploadedFiles" folder if (!System.IO.File.Exists(fileSavePath)) { httpPostedFile.SaveAs(fileSavePath); } FileStream stream = File.Open(fileSavePath, FileMode.Open, FileAccess.Read); IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream); DataSet result = excelReader.AsDataSet(); excelReader.Close(); int row_no = 1; //delete all old Company records var deletedRecords = dbService.DeleteOldCompanyInvetoryItems(); if (deletedRecords == -1) { log.Info(string.Format("There is a problem deleting the records")); } else { log.Info(string.Format("The number of deleted records is {0}", deletedRecords)); } var saveAuditImportReport = dbService.SaveCompanyInvetoryAuditItem(new CompanyInvetoryAudit { ImportedDate = DateTime.Now.ToString(), UserId = int.Parse(httpCurrentUser), UserName = httpCurrentUserName }); var recordsCount = 0; var allRecordsCount = 0; if (saveAuditImportReport != -1) { while (row_no < result.Tables[0].Rows.Count) { #region date convertion var _dateOfIncorporation = string.Empty; if (!string.IsNullOrEmpty(result.Tables[0].Rows[row_no][6].ToString())) { double DateOfIncorporation; if (double.TryParse(result.Tables[0].Rows[row_no][6].ToString(), out DateOfIncorporation)) { _dateOfIncorporation = string.Format("{0}/{1}/{2}", DateTime.FromOADate(DateOfIncorporation).Day, DateTime.FromOADate(DateOfIncorporation).Month, DateTime.FromOADate(DateOfIncorporation).Year); } } var _month = string.Empty; if (!string.IsNullOrEmpty(result.Tables[0].Rows[row_no][7].ToString())) { double Month; if (double.TryParse(result.Tables[0].Rows[row_no][7].ToString(), out Month)) { _month = string.Format("{0}/{1}/{2}", DateTime.FromOADate(Month).Day, DateTime.FromOADate(Month).Month, DateTime.FromOADate(Month).Year); } } var _potentialStrikeOffDate = string.Empty; if (!string.IsNullOrEmpty(result.Tables[0].Rows[row_no][9].ToString())) { double PotentialStrikeOffDate; if (double.TryParse(result.Tables[0].Rows[row_no][9].ToString(), out PotentialStrikeOffDate)) { _potentialStrikeOffDate = string.Format("{0}/{1}/{2}", DateTime.FromOADate(PotentialStrikeOffDate).Day, DateTime.FromOADate(PotentialStrikeOffDate).Month, DateTime.FromOADate(PotentialStrikeOffDate).Year); } } var _reservedDate = string.Empty; if (!string.IsNullOrEmpty(result.Tables[0].Rows[row_no][10].ToString())) { double ReservedDate; if (double.TryParse(result.Tables[0].Rows[row_no][10].ToString(), out ReservedDate)) { _reservedDate = string.Format("{0}/{1}/{2}", DateTime.FromOADate(ReservedDate).Day, DateTime.FromOADate(ReservedDate).Month, DateTime.FromOADate(ReservedDate).Year); } } var _soldDate = string.Empty; if (!string.IsNullOrEmpty(result.Tables[0].Rows[row_no][12].ToString())) { double SoldDate; if (double.TryParse(result.Tables[0].Rows[row_no][12].ToString(), out SoldDate)) { _soldDate = string.Format("{0}/{1}/{2}", DateTime.FromOADate(SoldDate).Day, DateTime.FromOADate(SoldDate).Month, DateTime.FromOADate(SoldDate).Year); } } var _companyStruckOffDate = string.Empty; if (!string.IsNullOrEmpty(result.Tables[0].Rows[row_no][14].ToString())) { double CompanyStruckOffDate; if (double.TryParse(result.Tables[0].Rows[row_no][14].ToString(), out CompanyStruckOffDate)) { _companyStruckOffDate = string.Format("{0}/{1}/{2}", DateTime.FromOADate(CompanyStruckOffDate).Day, DateTime.FromOADate(CompanyStruckOffDate).Month, DateTime.FromOADate(CompanyStruckOffDate).Year); } } #endregion date convertion var inventoryItem = new CompanyInventory(); inventoryItem.CompanyClient = result.Tables[0].Rows[row_no][0].ToString(); inventoryItem.CompanyName = result.Tables[0].Rows[row_no][1].ToString(); inventoryItem.IsOn = result.Tables[0].Rows[row_no][2].ToString(); inventoryItem.BC = result.Tables[0].Rows[row_no][3].ToString(); inventoryItem.Availability = result.Tables[0].Rows[row_no][4].ToString(); inventoryItem.CorporationStatus = result.Tables[0].Rows[row_no][5].ToString(); inventoryItem.DateOfIncorporation = _dateOfIncorporation; inventoryItem.Month = _month; inventoryItem.FirstOrSecondHalf = !string.IsNullOrEmpty(result.Tables[0].Rows[row_no][8].ToString()) ? int.Parse(result.Tables[0].Rows[row_no][8].ToString()) : 1; inventoryItem.PotentialStrikeOffDate = _potentialStrikeOffDate; inventoryItem.ReservedDate = _reservedDate; inventoryItem.ReservedBy = result.Tables[0].Rows[row_no][11].ToString(); inventoryItem.SoldDate = _soldDate; inventoryItem.SoldBy = result.Tables[0].Rows[row_no][13].ToString(); inventoryItem.CompanyStruckOffDate = _companyStruckOffDate; inventoryItem.Note = result.Tables[0].Rows[row_no][15].ToString(); inventoryItem.AuditId = saveAuditImportReport; var saveShelfCompany = -1; try { saveShelfCompany = dbService.SaveInventoryItem(inventoryItem); } catch (Exception ex) { log.Info(ex.Message); } recordsCount++; allRecordsCount++; if (saveShelfCompany == -1) { log.Info(string.Format("The Company {0} was not added to the DB", inventoryItem.CompanyName)); recordsCount--; } row_no++; } var updateAuditWithRecordsCount = dbService.UpdateCompanyInvetoryAuditItem(saveAuditImportReport, recordsCount); if (!updateAuditWithRecordsCount) { log.Info(string.Format("The Audit with Id={0} was not updated with the Company records count.", saveAuditImportReport)); } } else { log.Info(string.Format("The Audit table was not updated with the information with the upload")); } log.Info(string.Format("Company Record imported {1}, Total Company Records {0}", allRecordsCount, recordsCount)); //close the file after all is read stream.Close(); return(Request.CreateResponse(HttpStatusCode.OK, string.Format("Successfully uploaded {0} records from {1} rows!", recordsCount, allRecordsCount), "application/json")); } else { log.Info(string.Format("No File was posted!")); return(Request.CreateResponse(HttpStatusCode.NotFound, "There is no file posted!", "application/json")); } }