private void ImportFromCSVFile(string filePath) { FileCabinetServiceSnapshot snapshot = new FileCabinetServiceSnapshot(); Dictionary <int, string> exceptions = new Dictionary <int, string>(); List <string> lineExceptions = new List <string>(); int recordsCount = 0; using (StreamReader reader = new StreamReader(filePath)) { snapshot.LoadFromCSV(reader, out recordsCount, out lineExceptions); this.Service.Restore(snapshot, out exceptions); } foreach (var lex in lineExceptions) { write(lex); } foreach (var ex in exceptions) { write($"Record #{ex.Key} was not imported."); } write($"{recordsCount - exceptions.Count} records were imported from {filePath}."); }
/// <summary> /// Restores the records from the snapshot. /// </summary> /// <param name="snapshot">A snapshot to restore.</param> /// <returns>Number of imported records.</returns> public int Restore(FileCabinetServiceSnapshot snapshot) { if (snapshot == null) { throw new ArgumentNullException($"Snapshot is invalid."); } int recordsImported = 0; foreach (var record in snapshot.Records) { this.validator.Validate(record); if (this.idlist.Contains(record.Id)) { this.EditRecord(record); recordsImported++; } else { this.AddRecord(record); recordsImported++; } } return(recordsImported); }
/// <summary> /// Recovers saved snapshot recordings. /// </summary> /// <param name="snapshot">Snapshot.</param> public void Restore(FileCabinetServiceSnapshot snapshot) { this.stopwatch.Restart(); this.service.Restore(snapshot); this.stopwatch.Stop(); this.Information(nameof(this.service.Restore), this.stopwatch.ElapsedTicks); }
/// <summary>Restores the FileCabinet with specified snapshot.</summary> /// <param name="snapshot">The snapshot.</param> public void Restore(FileCabinetServiceSnapshot snapshot) { this.stopwatch.Start(); this.service.Restore(snapshot); this.stopwatch.Stop(); Console.WriteLine($"Restore method execution duration is {this.stopwatch.Elapsed.Ticks} ticks."); this.stopwatch.Reset(); }
/// <inheritdoc/> public int Restore(FileCabinetServiceSnapshot snapshot) { this.writer.WriteLine(Source.Resource.GetString("restoreLog", CultureInfo.InvariantCulture), DateTime.Now); var result = this.service.Restore(snapshot); this.writer.WriteLine(Source.Resource.GetString("restoreResultLog", CultureInfo.InvariantCulture), DateTime.Now); return(result); }
/// <summary>Makes the snapshot.</summary> /// <returns>Returns the snapshot of current FileCabinet.</returns> public FileCabinetServiceSnapshot MakeSnapshot() { this.stopwatch.Start(); FileCabinetServiceSnapshot snapshot = this.service.MakeSnapshot(); this.stopwatch.Stop(); Console.WriteLine($"MakeSnapshot method execution duration is {this.stopwatch.Elapsed.Ticks} ticks."); this.stopwatch.Reset(); return(snapshot); }
private static void Export(Action <StreamWriter, FileCabinetServiceSnapshot> exportMethod) { FileCabinetServiceSnapshot snapshot = fileCabinetService.MakeSnapshot(); using (StreamWriter writer = new StreamWriter(SettingsApp.FilePath)) { exportMethod(writer, snapshot); } Console.WriteLine($"{SettingsApp.RecordsAmount} records were written to {SettingsApp.FilePath}"); }
private void Import(string parameters) { if (!CommandHandlersExtensions.ImportExportParametersSpliter(parameters, out var fileFormat, out var path, "import")) { return; } try { using (StreamReader stream = new StreamReader(path)) { if (fileFormat == "csv") { this.snapshot = this.CabinetService.MakeSnapshot(); this.snapshot.LoadFromCsv(stream, RecordValidator, Converter, this.modelWriter); int count = this.CabinetService.Restore(this.snapshot); this.modelWriter.LineWriter.Invoke($"{count} records were imported from {path}"); } else if (fileFormat == "xml") { this.snapshot = this.CabinetService.MakeSnapshot(); this.xmlValidator.ValidateXml(this.xsdValidatorFile, path); this.snapshot.LoadFromXml(stream, RecordValidator, this.modelWriter); int count = this.CabinetService.Restore(this.snapshot); this.modelWriter.LineWriter.Invoke($"{count} records were imported from {path}"); } else { this.modelWriter.LineWriter.Invoke($"{fileFormat} writer is not found"); } } } catch (IOException ex) { this.modelWriter.LineWriter.Invoke(ex.Message); this.modelWriter.LineWriter.Invoke("File wasn't imported"); } catch (UnauthorizedAccessException ex) { this.modelWriter.LineWriter.Invoke(ex.Message); this.modelWriter.LineWriter.Invoke("File wasn't imported"); } catch (ArgumentException ex) { this.modelWriter.LineWriter.Invoke(ex.Message); this.modelWriter.LineWriter.Invoke("File wasn't imported"); } catch (XmlException ex) { this.modelWriter.LineWriter.Invoke(ex.Message); this.modelWriter.LineWriter.Invoke("File wasn't imported"); } }
/// <summary>Restores the FileCabinet with specified snapshot.</summary> /// <param name="snapshot">The snapshot.</param> public void Restore(FileCabinetServiceSnapshot snapshot) { try { this.writer = new StreamWriter(new FileStream("log.txt", FileMode.Append)); this.writer.WriteLine($"{DateTime.Now} - Calling Restore() with Snapshot = '{snapshot}'."); this.service.Restore(snapshot); this.writer.WriteLine($"{DateTime.Now} - Restore() was executed."); } finally { this.writer.Close(); } }
/// <inheritdoc/> protected override void Make(AppCommandRequest commandRequest) { (string format, string fileName) = CommandHandleBase.SplitParam(commandRequest.Parameters); if (File.Exists(fileName)) { Console.Write($"File is exist - rewrite {fileName}? [Y/n] "); char output = char.ToUpper(Console.ReadLine()[0]); if (output != 'Y') { return; } } FileCabinetServiceSnapshot snapshot = this.Service.MakeSnapshot(); try { using (StreamWriter writer = new (fileName)) { switch (format) { case "csv": snapshot.SaveToCSV(new FileCabinetRecordCsvWriter(writer)); break; case "xml": { using FileCabinetRecordXmlWriter fileCabinetRecordXmlWriter = new (writer); snapshot.SaveToXML(fileCabinetRecordXmlWriter); break; } default: Console.WriteLine("Format is not supported."); break; } } Console.WriteLine($"All records are exported to file {fileName}."); } catch (IOException) { Console.WriteLine($"Export failed: can't open file {fileName}."); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary>Handles the specified request.</summary> /// <param name="request">The request.</param> public override void Handle(AppCommandRequest request) { if (request != null && !request.Command.Equals("import", StringComparison.InvariantCultureIgnoreCase)) { this.NextHandler.Handle(request); return; } if (request != null) { string[] parametersArray = request.Parameters.Split(' '); string formatName = parametersArray[0]; string path = parametersArray[1]; try { if (formatName.Equals("csv", StringComparison.InvariantCultureIgnoreCase)) { using (StreamReader sr = new StreamReader(new FileStream(path, FileMode.Open))) { FileCabinetServiceSnapshot snapshot = this.service.MakeSnapshot(); snapshot.LoadFromCsv(sr); this.service.Restore(snapshot); sr.Close(); } Console.WriteLine("All records were imported."); } if (formatName.Equals("xml", StringComparison.InvariantCultureIgnoreCase)) { using (FileStream fs = new FileStream(path, FileMode.Open)) { FileCabinetServiceSnapshot snapshot = this.service.MakeSnapshot(); snapshot.LoadFromXml(fs); this.service.Restore(snapshot); fs.Close(); } Console.WriteLine("All records were imported."); } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { Console.WriteLine("Import failed: " + ex.Message); } } }
/// <summary>Makes the snapshot.</summary> /// <returns>Returns the snapshot of current FileCabinet.</returns> public FileCabinetServiceSnapshot MakeSnapshot() { try { this.writer = new StreamWriter(new FileStream("log.txt", FileMode.Append)); this.writer.WriteLine($"{DateTime.Now} - Calling MakeSnapshot()."); FileCabinetServiceSnapshot snapshot = this.service.MakeSnapshot(); this.writer.WriteLine($"{DateTime.Now} - MakeSnapshot() returned {snapshot}."); return(snapshot); } finally { this.writer.Close(); } }
private void Import(string parameters) { if (parameters.Split(' ').Length < 2) { Console.WriteLine("Type type and path to export file."); return; } string[] values = parameters.Split(' ', 2); string pathDirectory = string.Empty; if (values[0].Equals("csv", StringComparison.InvariantCultureIgnoreCase)) { if (File.Exists(values[1])) { using (FileStream fs = new FileStream(values[1], FileMode.Open)) { List <FileCabinetRecord> list = new List <FileCabinetRecord>(); FileCabinetServiceSnapshot snap = new FileCabinetServiceSnapshot(list); snap.LoadFromCsv(fs); this.service.Restore(snap); Console.WriteLine($"Notes has been imported from {values[1]}."); } } else { Console.WriteLine("File not exists"); } } else if (values[0].Equals("xml", StringComparison.InvariantCultureIgnoreCase)) { if (File.Exists(values[1])) { using (FileStream fs = new FileStream(values[1], FileMode.Open)) { List <FileCabinetRecord> list = new List <FileCabinetRecord>(); FileCabinetServiceSnapshot snap = new FileCabinetServiceSnapshot(list); snap.LoadFromXml(fs); this.service.Restore(snap); Console.WriteLine($"Notes has been imported from {values[1]}."); } } else { Console.WriteLine("File not exists"); } } }
private void Import(string parametrs) { const string formatCsv = "csv"; const string formatXml = "xml"; string[] parameters = parametrs.Split(' ', 2); string path = parameters[1]; var snapshot = new FileCabinetServiceSnapshot(this.Service.GetRecords()); if (File.Exists(path)) { using (FileStream fileStream = File.OpenRead(path)) { StreamReader streamReader = new StreamReader(fileStream); IList <FileCabinetRecord> records; if (parameters[0].Equals(formatCsv, StringComparison.InvariantCultureIgnoreCase)) { records = snapshot.LoadFromCsv(streamReader); snapshot = new FileCabinetServiceSnapshot(records); this.Service.Restore(snapshot); } else if (parameters[0].Equals(formatXml, StringComparison.InvariantCultureIgnoreCase)) { records = snapshot.LoadFromXml(streamReader); snapshot = new FileCabinetServiceSnapshot(records); this.Service.Restore(snapshot); } Console.WriteLine(snapshot.Records.Count + " records were imported from " + path); streamReader.Dispose(); } } else { Console.WriteLine("Import error: file " + path + " is not exist."); return; } }
/// <summary> /// Imports the records from csv or xml file. /// </summary> /// <param name="parameters">Format to write in and path to write to.</param> private void Import(string parameters) { string[] args = parameters.Split(); if (args == null || args.Length < 2) { Console.WriteLine("Incorrect parameters."); return; } string format = args[0].ToLower(); string path = args[1]; if (!File.Exists(path)) { Console.WriteLine("Import error: " + path + " does not exist"); return; } using (StreamReader reader = new StreamReader(path)) { int importedRecords = 0; IList <FileCabinetRecord> records; IFileCabinetServiceSnapshot snapshot = new FileCabinetServiceSnapshot(); switch (format) { case "csv": records = snapshot.LoadFromCsv(reader); snapshot = new FileCabinetServiceSnapshot(records); importedRecords = this.Service.Restore(snapshot); break; case "xml": records = snapshot.LoadFromXml(reader); snapshot = new FileCabinetServiceSnapshot(records); importedRecords = this.Service.Restore(snapshot); break; default: Console.WriteLine("Incorrect format: can be xml or csv."); return; } Console.WriteLine(importedRecords + " records were imported from " + path + "."); } }
private static void ImportFromXml(string path) { try { using (StreamReader reader = new StreamReader(path)) { FileCabinetServiceSnapshot snapshot = new FileCabinetServiceSnapshot(); snapshot.LoadFromXml(reader); fileCabinetService.Restore(snapshot); } } catch (Exception ex) when( ex is ArgumentException || ex is NotSupportedException || ex is FileNotFoundException || ex is IOException || ex is System.Security.SecurityException || ex is DirectoryNotFoundException || ex is UnauthorizedAccessException || ex is PathTooLongException) { Console.WriteLine($"Import failed: can't open file {path}."); } }
/// <inheritdoc/> protected override void Make(AppCommandRequest commandRequest) { (string format, string fileName) = CommandHandleBase.SplitParam(commandRequest.Parameters); if (!File.Exists(fileName)) { Console.WriteLine($"File \"{fileName}\"is not exist."); return; } FileStream fileStream; try { fileStream = File.OpenRead(fileName); } catch (Exception) { Console.WriteLine("Can't open file"); return; } int count = 0; var snapshot = new FileCabinetServiceSnapshot(); switch (format) { case "csv": snapshot.LoadFromCSV(fileStream); count = this.Service.Restore(snapshot); break; case "xml": snapshot.LoadFromXml(fileStream); count = this.Service.Restore(snapshot); break; default: Console.WriteLine("Format is not supported."); break; } Console.WriteLine($"{count} records were imported from {fileName}."); }
private void Import(string parameters) { string[] parametersArr = parameters.Split(' ', 2); if (parametersArr.Length < 2) { Console.WriteLine(Configurator.GetConstantString("InvalidInput")); Console.WriteLine(Configurator.GetConstantString("CommandPatthern")); Console.WriteLine(Configurator.GetConstantString("ImportPatthern")); return; } const int importTypeIndex = 0; const int filePathIndex = 1; if (!File.Exists(parametersArr[filePathIndex])) { Console.WriteLine($"File {parametersArr[filePathIndex]} isn't exist."); return; } FileCabinetServiceSnapshot snapshot = new FileCabinetServiceSnapshot(); if (parametersArr[importTypeIndex].Equals(Configurator.GetConstantString("CsvType"), StringComparison.OrdinalIgnoreCase)) { using StreamReader fileStream = new StreamReader(parametersArr[filePathIndex]); snapshot.LoadFromCsv(fileStream); int numberOfImported = this.Service.Restore(snapshot); Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} records were imported from {1}", numberOfImported, parametersArr[filePathIndex])); } else if (parametersArr[importTypeIndex].Equals(Configurator.GetConstantString("XmlType"), StringComparison.OrdinalIgnoreCase)) { using StreamReader fileStream = new StreamReader(parametersArr[filePathIndex]); using XmlReader xmlReader = XmlReader.Create(fileStream); snapshot.LoadFromXml(xmlReader); int numberOfImported = this.Service.Restore(snapshot); Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} records were imported from {1}", numberOfImported, parametersArr[filePathIndex])); } else { Console.WriteLine(Configurator.GetConstantString("InvalidFormatType")); } }
/// <summary> /// Exports data in file. /// </summary> /// <param name="command">Parameters command.</param> public override void Handle(AppCommandRequest command) { if (this.GoToNextCommand(command)) { return; } string[] splitParameters = command.Parameters.Split(' '); if (splitParameters.Length != 2) { return; } Action <StreamWriter, FileCabinetServiceSnapshot> executeCommand = splitParameters[0] switch { "csv" => ExportToCsv, "xml" => ExportToXml, _ => ExportToCsv }; try { if (!CheckFile(splitParameters[1])) { return; } FileCabinetServiceSnapshot snapshot = this.service.MakeSnapshot(); using (StreamWriter writer = new StreamWriter(splitParameters[1], false)) { executeCommand(writer, snapshot); Console.WriteLine($"All records are exported to file {splitParameters[1]}."); } } catch (Exception ex) when( ex is ArgumentException || ex is NotSupportedException || ex is FileNotFoundException || ex is IOException || ex is System.Security.SecurityException || ex is DirectoryNotFoundException || ex is UnauthorizedAccessException || ex is PathTooLongException) { Console.WriteLine($"Export failed: can't open file {splitParameters[1]}."); } }
private void ImportXml(string path) { var snapshot = new FileCabinetServiceSnapshot(Array.Empty <FileCabinetRecord>()); try { using (var stream = File.Open(@path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var st = new StreamReader(stream)) { snapshot.LoadFromXml(st); } } catch (FileNotFoundException) { Console.WriteLine($"Import error: file {path} not exist"); } int completed = this.fileCabinetService.Restore(snapshot); Console.WriteLine($"{completed} recordses were imported from {path}"); }
private void Export(string parameters) { if (!CommandHandlersExtensions.ImportExportParametersSpliter(parameters, out var fileFormat, out var path, "export")) { return; } try { using (StreamWriter stream = new StreamWriter(path)) { if (fileFormat == "csv") { this.snapshot = this.CabinetService.MakeSnapshot(); this.snapshot.SaveToCsv(stream); } else if (fileFormat == "xml") { this.snapshot = this.CabinetService.MakeSnapshot(); this.snapshot.SaveToXml(stream); } else { this.modelWriter.LineWriter.Invoke($"{fileFormat} writer is not found"); return; } } this.modelWriter.LineWriter.Invoke($"File {path} was successfully exported"); } catch (IOException ex) { this.modelWriter.LineWriter.Invoke(ex.Message); } catch (UnauthorizedAccessException ex) { this.modelWriter.LineWriter.Invoke(ex.Message); } }
private void Export(string parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } string[] commands = parameters.Split(' '); if (commands.Length != 2) { throw new ArgumentException("Wrong command format. Example: export csv d:/records.csv", nameof(parameters)); } string format = commands[FormatPosition]; string path = commands[PathPosition]; const string yesAnswer = "y"; const string csvFileType = "csv"; const string xmlFileType = "xml"; if (File.Exists(path)) { write($"File is exist - rewrite {path}? [Y/n] "); if (char.TryParse(Console.ReadLine(), out char answer)) { if (answer.ToString(CultureInfo.InvariantCulture).Equals(yesAnswer, StringComparison.InvariantCultureIgnoreCase)) { File.Delete(path); Write(path); } else { return; } } } else { try { Write(path); } catch (FileLoadException ex) { throw new ArgumentException($"Export failed: can't open file {path}.", ex.Message); } } void Write(string p) { using (StreamWriter streamWriter = new StreamWriter(p)) { FileCabinetServiceSnapshot snapshot = this.Service.MakeSnapshot(); if (format == csvFileType) { snapshot.SaveToCSV(streamWriter); } else if (commands[FormatPosition] == xmlFileType) { snapshot.SaveToXML(streamWriter); } else { write($"There is no {commands[FormatPosition]} command."); return; } write($"All records are exported to file {p}."); } } }
private void Export(string parameters) { bool rewrite = false; var noRewrite = 'n'; const string xml = "xml"; const string csv = "csv"; try { snapshot = this.service.MakeSnapshot(); var parameterArray = parameters.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parameterArray.Length != 2) { throw new ArgumentException("You did not specify the type of file to export or the path to export"); } var fullPath = parameterArray.Last(); var nameFile = Path.GetFileName(fullPath); var typeFile = parameterArray.First(); var extensionFile = Path.GetExtension(nameFile).TrimStart('.'); if (typeFile != extensionFile) { throw new ArgumentException($"You want to export data to a {nameFile}, but you specified the type {typeFile}"); } if (File.Exists(fullPath)) { Console.Write($"File is exist - rewrite {nameFile}?[Y / n] "); var rewriteOrNo = ReadInput(RewriteConverter, RewriteValidator); char.ToLower(rewriteOrNo, CultureInfo.InvariantCulture); if (char.Equals(rewriteOrNo, noRewrite)) { rewrite = true; } } try { if (string.Equals(csv, typeFile, StringComparison.OrdinalIgnoreCase)) { using (var sw = new StreamWriter(fullPath, rewrite)) { snapshot.SaveToCsv(sw); Console.WriteLine($"All records are exported to file {nameFile}"); } } else if (string.Equals(xml, typeFile, StringComparison.OrdinalIgnoreCase)) { using (var sw = new StreamWriter(fullPath, rewrite)) { snapshot.SaveToXml(sw); Console.WriteLine($"All records are exported to file {nameFile}"); } } } catch (DirectoryNotFoundException) { Console.WriteLine($"Export failed: can't open file {fullPath}"); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } } catch (IndexOutOfRangeException) { Console.WriteLine("Enter the file extension and his name or path"); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } }
private void Import(string parameters) { const string xml = "xml"; const string csv = "csv"; try { var parameterArray = parameters.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parameterArray.Length != 2) { throw new ArgumentException("You did not specify the type of file to export or the path to export"); } var fullPath = parameterArray.Last(); var nameFile = Path.GetFileName(fullPath); var extensionFile = Path.GetExtension(nameFile).TrimStart('.'); var typeFile = parameterArray.First(); if (!string.Equals(typeFile, xml, StringComparison.OrdinalIgnoreCase) && !string.Equals(typeFile, csv, StringComparison.OrdinalIgnoreCase)) { bool rezult = false; do { Console.Write("Please, input correct type of file: "); typeFile = Console.ReadLine(); rezult = string.Equals(typeFile, xml, StringComparison.OrdinalIgnoreCase) || string.Equals(typeFile, csv, StringComparison.OrdinalIgnoreCase); }while (rezult == false); } if (typeFile != extensionFile) { throw new ArgumentException($"You want to import data from a {nameFile}, but you specified the type {typeFile}"); } if (File.Exists(fullPath)) { snapshot = this.service.MakeSnapshot(); if (string.Equals(csv, typeFile, StringComparison.OrdinalIgnoreCase)) { using (var fileStream = File.Open(nameFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { snapshot.LoadFromCsv(fileStream); Console.WriteLine($"{snapshot.ListFromFile.Count} records were imported from {fullPath}"); this.service.Restore(snapshot); } } else if (string.Equals(xml, typeFile, StringComparison.OrdinalIgnoreCase)) { using (var fileStream = File.Open(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { snapshot.LoadFromXml(fileStream); Console.WriteLine($"{snapshot.ListFromFile.Count} records were imported from {fullPath}"); this.service.Restore(snapshot); } } } else { Console.WriteLine($"Import error: {fullPath} is not exist."); } } catch (IndexOutOfRangeException) { Console.WriteLine("Enter the file extension and his name or path"); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } }
private void Import(string parameters) { if (string.IsNullOrWhiteSpace(parameters)) { Console.WriteLine("Enter export parameters."); return; } var splittedParameters = parameters.Split(SpaceSymbol, NumberOfParameters, StringSplitOptions.RemoveEmptyEntries); string typeOfFile; string filePath; try { typeOfFile = splittedParameters[FirstElementIndex]; filePath = splittedParameters[SecondElementIndex].Trim(QuoteSymbol); } catch (IndexOutOfRangeException) { Console.WriteLine("Invalid number of parameters."); return; } if (!File.Exists(filePath)) { Console.WriteLine($"Import error: file {filePath} is not exist."); return; } if (typeOfFile.Equals(CsvFileExtension, StringComparison.InvariantCultureIgnoreCase)) { using var reader = new StreamReader(filePath, Encoding.Unicode); var snapshot = new FileCabinetServiceSnapshot(); try { snapshot.LoadFromCsv(reader, this.fileCabinetService.Validator); } catch (FormatException) { Console.WriteLine("One of the record's properties has invalid format."); return; } catch (IndexOutOfRangeException) { Console.WriteLine("One of the record's has invalid number of properties."); return; } foreach (var record in snapshot.InvalidRecords) { Console.WriteLine($"Record #{record.Item1.Id} was skipped: {record.Item2}"); } this.fileCabinetService.Restore(snapshot); Console.WriteLine($"{snapshot.Records.Count} records were imported."); } else if (typeOfFile.Equals(XmlFileExtension, StringComparison.InvariantCultureIgnoreCase)) { using var reader = XmlReader.Create(filePath); var snapshot = new FileCabinetServiceSnapshot(); try { snapshot.LoadFromXml(reader, this.fileCabinetService.Validator); } catch (InvalidOperationException) { Console.WriteLine("One of the record's properties has invalid format."); return; } foreach (var record in snapshot.InvalidRecords) { Console.WriteLine($"Record #{record.Item1.Id} was skipped: {record.Item2}"); } this.fileCabinetService.Restore(snapshot); Console.WriteLine($"{snapshot.Records.Count} records were imported."); } else { Console.WriteLine("Invalid type of file."); return; } }
/// <summary> /// Saves data to xml file. /// </summary> /// <param name="writer">Provider for writing.</param> /// <param name="snapshot">The state to be saved.</param> private static void ExportToXml(StreamWriter writer, FileCabinetServiceSnapshot snapshot) { snapshot.SaveToXml(writer); }
/// <summary> /// Restores the specified snapshot. /// </summary> /// <param name="snapshot">The snapshot.</param> /// <returns> /// count of restored records. /// </returns> public int Restore(FileCabinetServiceSnapshot snapshot) { return(this.MethodMeter(this.service.Restore, snapshot, "restore")); }
/// <summary> /// Recovers saved snapshot recordings. /// </summary> /// <param name="snapshot">Snapshot.</param> public void Restore(FileCabinetServiceSnapshot snapshot) { this.service.Restore(snapshot); this.WriteLogInFile(nameof(this.service.Restore), string.Empty); }
private void Export(string parameters) { string[] parametersArr = parameters.Split(' ', 2); if (parametersArr.Length < 2) { Console.WriteLine(Configurator.GetConstantString("InvalidInput")); Console.WriteLine(Configurator.GetConstantString("CommandPatthern")); Console.WriteLine(Configurator.GetConstantString("ExportPatthern")); return; } const int exportTypeIndex = 0; const int filePathIndex = 1; if (File.Exists(parametersArr[filePathIndex])) { Console.WriteLine($"File is exist - rewrite {parametersArr[filePathIndex]}? [Y/n]"); string answer = Console.ReadLine(); if (answer.Equals(Configurator.GetConstantString("PositiveAnswer"), StringComparison.OrdinalIgnoreCase)) { File.Delete(parametersArr[filePathIndex]); } else { return; } } FileCabinetServiceSnapshot snapshot = this.Service.MakeSnapshot(); if (parametersArr[exportTypeIndex].Equals(Configurator.GetConstantString("CsvType"), StringComparison.OrdinalIgnoreCase)) { try { using StreamWriter streamWriter = new StreamWriter(parametersArr[filePathIndex]); streamWriter.WriteLine(Configurator.GetConstantString("CsvHeader")); snapshot.SaveToCsv(streamWriter); Console.WriteLine($"All records are exported to file {parametersArr[filePathIndex]}"); } catch (DirectoryNotFoundException) { Console.WriteLine(Configurator.GetConstantString("DirectoryNotExist")); } } else if (parametersArr[exportTypeIndex].Equals(Configurator.GetConstantString("XmlType"), StringComparison.OrdinalIgnoreCase)) { XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = "\t", }; try { using XmlWriter xmlWriter = XmlWriter.Create(parametersArr[filePathIndex], settings); snapshot.SaveToXml(xmlWriter); Console.WriteLine($"All records are exported to file {parametersArr[filePathIndex]}"); } catch (DirectoryNotFoundException) { Console.WriteLine(Configurator.GetConstantString("DirectoryNotExist")); } } else { Console.WriteLine(Configurator.GetConstantString("InvalidFormatType")); } }
/// <summary> /// Handles the specified command request. /// </summary> /// <param name="commandRequest">The command request.</param> /// <exception cref="ArgumentNullException">Throws when commandRequest is null.</exception> public override void Handle(AppCommandRequest commandRequest) { if (commandRequest is null) { throw new ArgumentNullException(nameof(commandRequest)); } if (commandRequest.Command.ToUpperInvariant() != "IMPORT") { this.NextHandler.Handle(commandRequest); return; } string[] param = commandRequest.Parameters.Split(' '); if (param.Length != 2) { Console.WriteLine("Invalid number of parameters"); return; } if (string.IsNullOrWhiteSpace(param[0]) || string.IsNullOrWhiteSpace(param[1])) { Console.WriteLine("Invalid parameters"); return; } FileStream fileStream = null; try { fileStream = new FileStream(param[1], FileMode.Open); } catch (IOException) { fileStream?.Close(); Console.WriteLine("Import failed: can't open file {0}", param[1]); return; } catch (UnauthorizedAccessException) { return; } FileCabinetServiceSnapshot serviceSnapshot = new FileCabinetServiceSnapshot(); try { if (param[0].ToUpperInvariant() == "CSV") { serviceSnapshot.LoadFromCsv(new StreamReader(fileStream, leaveOpen: true)); this.Service.Restore(serviceSnapshot); Console.WriteLine("records were imported from {0}", param[1]); } if (param[0].ToUpperInvariant() == "XML") { serviceSnapshot.LoadFromXml(new StreamReader(fileStream, leaveOpen: true)); this.Service.Restore(serviceSnapshot); Console.WriteLine("records were imported from {0}", param[1]); } this.Service.MemEntity.Clear(); } catch (FormatException) { Console.WriteLine("Not correct format."); } catch (InvalidOperationException) { Console.WriteLine("Not correct format."); } fileStream.Close(); }