Пример #1
0
 /// <inheritdoc/>
 public int Restore(FileCabinetServiceSnapshot snapshot)
 {
     return(this.CallMethod(
                $"Calling Restore().",
                $"Restore() restores {0} records.",
                () => this.service.Restore(snapshot)));
 }
        /// <summary>
        /// Restore date from snapshot and print tick that it took.
        /// </summary>
        /// <param name="snapshot">Snapshot.</param>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot is null)
            {
                this.LogWriter($"{DateTime.Now} - Calling Restore() with Snapshot = 'null'");
                this.LogWriter($"{DateTime.Now} - Restore() throw Snapshot can't be null");
                throw new ArgumentNullException(nameof(snapshot), "Snapshot can't be null");
            }
            else
            {
                this.LogWriter($"{DateTime.Now} - Calling Restore() with Snapshot: ");
            }

            foreach (var r in snapshot.Records)
            {
                this.LogWriter($"Id = '{r.Id}', FirstName = '{r.FirstName}', " +
                               $"LastName = '{r.LastName}', DateOfBirth = '{r.DateOfBirth.ToString("yyyy - MMM - dd", Culture)}', " +
                               $"Gender = '{r.Gender}', PassportId = '{r.PassportId}', " +
                               $"Salary = '{r.Salary}'");
            }

            try
            {
                this.service.Restore(snapshot);
                this.LogWriter($"{DateTime.Now} - Restore() finished.");
            }
            catch (Exception ex)
            {
                this.LogWriter($"{DateTime.Now} - Restore() throw {ex.Message}");
                throw;
            }
        }
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot is null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            if (snapshot.Records is null)
            {
                throw new ArgumentException("Snapshot hasn't FileCabinetRecords.", nameof(snapshot));
            }

            foreach (var item in snapshot.Records)
            {
                FileCabinetRecord oldRecord = this.FindById(item.Id);
                long position = this.FindPosition(item.Id);
                if (oldRecord != null)
                {
                    this.RemoveRecordFromDictionaries(oldRecord, position);
                }

                this.AddRecordToDictionaries(item, position);
                byte[] data = ConvertRecordToBytes(item);
                this.fileStream.Position = position;
                this.fileStream.Write(data, 0, data.Length);
            }
        }
        /// <summary>
        /// Метод производящий добавление в список импортируемых записей.
        /// </summary>
        /// <param name="snap">Импортированные записи.</param>
        public void Restore(FileCabinetServiceSnapshot snap)
        {
            if (snap == null)
            {
                throw new Exception();
            }

            foreach (FileCabinetRecord record in snap.Records)
            {
                int t;
                if (this.GetStat() == 0)
                {
                    t = 0;
                }
                else
                {
                    t = this.GetRecords().Last().Id;
                }

                if (record.Id <= this.GetStat() || record.Id <= t)
                {
                    this.EditRecord(record);
                }
                else
                {
                    this.CreateRecord(record);
                }
            }
        }
Пример #5
0
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot is null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            if (snapshot.Records is null)
            {
                throw new ArgumentException("Snapshot hasn't FileCabinetRecords.", nameof(snapshot));
            }

            foreach (var item in snapshot.Records)
            {
                int index = this.records.FindIndex(0, this.records.Count, x => x.Id == item.Id);
                if (index != -1)
                {
                    this.records[index] = item;
                }
                else
                {
                    this.records.Add(item);
                }
            }
        }
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot is null)
            {
                throw new ArgumentNullException($"{nameof(snapshot)} cannot be null");
            }

            foreach (var record in snapshot.Records)
            {
                var data = DataHelper.CreateValidateData(record);

                try
                {
                    if (this.GetRecords().Any(x => x.Id == record.Id))
                    {
                        this.EditRecord(record.Id, data);
                    }
                    else
                    {
                        this.CreateRecord(record.Id, data);
                    }
                }
                catch (ArgumentException exeption)
                {
                    snapshot.Logger.Add($"{exeption.Message}. Exeption in record #{record.Id}.");
                }
                catch (InvalidOperationException exeption)
                {
                    snapshot.Logger.Add($"{exeption.Message}. Error in record #{record.Id}.");
                }
            }
        }
Пример #7
0
        /// <summary>
        /// Restores statement from snapshot.
        /// </summary>
        /// <param name="snapshot">Snapshot that represent statement to restore.</param>
        /// <returns>Amount of new records added.</returns>
        /// <exception cref="ArgumentNullException">Thrown when snapshot is null.</exception>
        public int Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot is null)
            {
                throw new ArgumentNullException(nameof(snapshot), Configurator.GetConstantString("NullSnapshot"));
            }

            int count = 0;

            foreach (FileCabinetRecord record in snapshot.GetRecords)
            {
                var validationResult = this.recordValidator.ValidateParameters(record);
                if (!validationResult.Item1)
                {
                    Console.WriteLine($"Invalid values in #{record.Id} record. {validationResult.Item2}");
                    continue;
                }

                if (this.dictionaryIdOffset.ContainsKey(record.Id))
                {
                    this.WriteToFile(record, this.dictionaryIdOffset[record.Id]);
                    count++;
                }
                else
                {
                    this.dictionaryIdOffset.Add(record.Id, this.currentOffset);
                    this.WriteToFile(record, this.currentOffset);
                    this.currentOffset += this.sizeOfRecord;
                    count++;
                }
            }

            return(count);
        }
Пример #8
0
 /// <inheritdoc/>
 public void Restore(FileCabinetServiceSnapshot snapshot)
 {
     this.stopwatch.Restart();
     this.fileCabinetService.Restore(snapshot ?? throw new ArgumentNullException(nameof(snapshot)));
     this.stopwatch.Stop();
     Print(nameof(this.Restore), this.stopwatch.ElapsedTicks);
 }
 /// <summary>Restores the FileCabinet with specified snapshot.</summary>
 /// <param name="snapshot">The snapshot.</param>
 public void Restore(FileCabinetServiceSnapshot snapshot)
 {
     if (snapshot != null)
     {
         this.list = new List <FileCabinetRecord>(snapshot.Records);
     }
 }
        /// <summary>
        /// Restores the specified snapshot.
        /// </summary>
        /// <param name="snapshot">The snapshot.</param>
        /// <exception cref="ArgumentNullException">Throws when snampshot is null.</exception>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot is null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            foreach (FileCabinetRecord record in snapshot.Records)
            {
                try
                {
                    if (!this.dictionaryId.ContainsKey(record.Id))
                    {
                        this.validator.ValidateCabinetRecord(RecordToParams(record));
                        this.list.Add(record);
                        this.dictionaryId.Add(record.Id, record);
                        AddToDictionary <string, FileCabinetRecord>(this.firstNameDictionary, record.FirstName.ToUpperInvariant(), record);
                        AddToDictionary <string, FileCabinetRecord>(this.lastNameDictionary, record.LastName.ToUpperInvariant(), record);
                        AddToDictionary <DateTime, FileCabinetRecord>(this.dateOfBirthDictionary, record.DateOfBirth, record);

                        this.id = Math.Max(this.id, record.Id);
                    }
                    else
                    {
                        this.EditRecord(record.Id, RecordToParams(record));
                    }
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine("{0}:{1}", record.Id, e.Message);
                }
            }
        }
Пример #11
0
 /// <summary>
 /// Restore data.
 /// Displays the run time of the method.
 /// </summary>
 /// <param name="snapshot">Input object to retrieve a list of records.</param>
 public void Restore(FileCabinetServiceSnapshot snapshot)
 {
     this.stopwatch.Reset();
     this.stopwatch.Start();
     this.service.Restore(snapshot);
     this.stopwatch.Stop();
     Console.WriteLine($"{nameof(this.service.Restore)} method execution duration is {this.stopwatch.ElapsedTicks} ticks.");
 }
        /// <summary>
        /// Restore date from snapshot and print tick that it took.
        /// </summary>
        /// <param name="snapshot">Snapshot.</param>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            this.service.Restore(snapshot);
            stopWatch.Stop();
            Console.WriteLine($"Restore method execution duration is {stopWatch.ElapsedTicks} ticks.");
        }
Пример #13
0
 /// <summary>
 /// Restore data and writes the execution result to the log.
 /// </summary>
 /// <param name="snapshot">Input object to retrieve a list of records.</param>
 public void Restore(FileCabinetServiceSnapshot snapshot)
 {
     using (TextWriter writer = File.AppendText(this.path))
     {
         writer.WriteLine($"{DateTime.Now.ToString("dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture)} - Calling {nameof(this.service.Restore)}()");
         this.service.Restore(snapshot);
         writer.WriteLine($"{DateTime.Now.ToString("dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture)} - {nameof(this.service.Restore)}() all records were added to existing records ");
     }
 }
Пример #14
0
        /// <summary>Restores the specified snapshot.</summary>
        /// <param name="snapshot">Snapshot.</param>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            var timer = new Stopwatch();

            timer.Start();
            this.service.Restore(snapshot);
            timer.Stop();
            Console.WriteLine($"Restore method execution duration is {timer.ElapsedMilliseconds} ticks.");
        }
Пример #15
0
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            using (StreamWriter sw = new StreamWriter("logs.txt", true))
            {
                sw.WriteLine($"{DateTime.Now.ToString("MM/dd/yyyy hh:mm tt", new CultureInfo("en-US"))} - Calling Import() with DateOfBirth");
            }

            this.fileCabinetService.Restore(snapshot);
        }
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            var  record         = snapshot.Records;
            var  recordFromFile = snapshot.ListFromFile;
            bool isFind         = false;

            for (int i = 0; i < recordFromFile.Count; i++)
            {
                try
                {
                    fileCabinetServiceContext.FirstName   = recordFromFile[i].FirstName;
                    fileCabinetServiceContext.LastName    = recordFromFile[i].LastName;
                    fileCabinetServiceContext.DateOfBirth = recordFromFile[i].DateOfBirth;
                    fileCabinetServiceContext.Age         = recordFromFile[i].Age;
                    fileCabinetServiceContext.Gender      = recordFromFile[i].Gender;
                    fileCabinetServiceContext.Salary      = recordFromFile[i].Salary;
                    this.contextStrategy.ValidateParameters(fileCabinetServiceContext);
                    for (int j = 0; j < record.Count; j++)
                    {
                        if (record[j].Id == recordFromFile[i].Id)
                        {
                            this.EditRecord(recordFromFile[i].Id, fileCabinetServiceContext);
                            isFind = true;
                            break;
                        }
                    }

                    if (!isFind)
                    {
                        this.recordId = recordFromFile[i].Id;
                        var fileCabinetRecord = new FileCabinetRecord
                        {
                            Id          = recordFromFile[i].Id,
                            Age         = fileCabinetServiceContext.Age,
                            Salary      = fileCabinetServiceContext.Salary,
                            Gender      = fileCabinetServiceContext.Gender,
                            FirstName   = fileCabinetServiceContext.FirstName,
                            LastName    = fileCabinetServiceContext.LastName,
                            DateOfBirth = fileCabinetServiceContext.DateOfBirth,
                        };
                        this.AddRecordInAllDictionary(fileCabinetRecord, ((int)this.fileStream.Length / RecordSize) + 1);
                        this.FileCabinetRecordToBytes(fileCabinetRecord);
                    }

                    isFind = false;
                }
                catch (Exception ex) when(ex is ArgumentException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException)
                {
                    Console.WriteLine($"{recordFromFile[i].Id} : {ex.Message}");
                }
            }
        }
Пример #17
0
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            this.stopwatch = Stopwatch.StartNew();

            this.fileCabinetService.Restore(snapshot);

            this.stopwatch.Stop();
            Console.WriteLine($"Restore method execution is {this.stopwatch.ElapsedTicks} ticks.");
        }
Пример #18
0
 /// <summary>
 /// Makes a snapshot of an list and writes the execution result to the log.
 /// </summary>
 /// <returns>New cloned object type of <see cref="FileCabinetServiceSnapshot"/> as an array.</returns>
 public FileCabinetServiceSnapshot MakeSnapshot()
 {
     using (TextWriter writer = File.AppendText(this.path))
     {
         writer.WriteLine($"{DateTime.Now.ToString("dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture)} - Calling {nameof(this.service.MakeSnapshot)}()");
         FileCabinetServiceSnapshot snapshot = this.service.MakeSnapshot();
         writer.WriteLine($"{DateTime.Now.ToString("dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture)} - {nameof(this.service.MakeSnapshot)}() made snapshot list of the records ");
         return(snapshot);
     }
 }
Пример #19
0
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot is null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            this.Print(nameof(this.Restore), $"snapshot wich contains {snapshot?.Records.Count} elemetns.");
            this.fileCabinetService.Restore(snapshot);
        }
Пример #20
0
        /// <summary>
        /// Restores the specified snapshot.
        /// </summary>
        /// <param name="snapshot">The snapshot.</param>
        /// <param name="exceptions">The exceptions.</param>
        /// <exception cref="ArgumentNullException">Snapshot is null.</exception>
        public void Restore(FileCabinetServiceSnapshot snapshot, out Dictionary <int, string> exceptions)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            var recordsFromFile = snapshot.FileCabinetRecords.ToList();
            List <FileCabinetRecord> newArray = this.GenerateNewListWithExistAndRestoreRecords(recordsFromFile, out exceptions);

            this.list = newArray;
        }
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            foreach (var record in snapshot.Records)
            {
                this.CreateRecord(record);
            }
        }
 /// <summary>Restores the FileCabinet using specified snapshot.</summary>
 /// <param name="snapshot">The snapshot.</param>
 public void Restore(FileCabinetServiceSnapshot snapshot)
 {
     this.fileStream.Position = 0;
     if (snapshot != null)
     {
         foreach (var element in snapshot.Records)
         {
             this.count = element.Id--;
             this.CreateRecord(new RecordData(element.FirstName, element.LastName, element.Code, element.Letter, element.Balance, element.DateOfBirth));
         }
     }
 }
Пример #23
0
        /// <summary>Restores the specified snapshot.</summary>
        /// <param name="snapshot">Snapshot.</param>
        /// <exception cref="ArgumentNullException">Thrown when snapshot
        /// is null.</exception>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            using var writer = new StreamWriter(LogFileName, true, Encoding.UTF8);
            if (snapshot == null)
            {
                writer.WriteLine($"{DateTime.Now.ToString(LogDateFormat, Culture)} - Restore() threw an exception: {nameof(snapshot)} is null");
                throw new ArgumentNullException(nameof(snapshot));
            }

            writer.WriteLine($"{DateTime.Now.ToString(LogDateFormat, Culture)} - Calling Restore() with snapshot with {snapshot.Records.Count} record(s)");
            this.service.Restore(snapshot);
            writer.WriteLine($"{DateTime.Now.ToString(LogDateFormat, Culture)} - Restore() executed successfully");
        }
        /// <summary>
        /// Adds timing count for Restore method.
        /// </summary>
        /// <param name="snapshot">A snapshot of records to restore.</param>
        /// <returns>count records.</returns>
        public int Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            this.watch = Stopwatch.StartNew();
            this.service.Restore(snapshot);
            this.watch.Stop();
            Console.WriteLine($"Restore method execution duration is " + this.watch.ElapsedTicks + " ticks.");

            return(snapshot.Records.Count);
        }
Пример #25
0
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            var  record         = snapshot.Records;
            var  recordFromFile = snapshot.ListFromFile;
            bool isFind         = false;

            for (int i = 0; i < recordFromFile.Count; i++)
            {
                try
                {
                    fileCabinetServiceContext.FirstName   = recordFromFile[i].FirstName;
                    fileCabinetServiceContext.LastName    = recordFromFile[i].LastName;
                    fileCabinetServiceContext.DateOfBirth = recordFromFile[i].DateOfBirth;
                    fileCabinetServiceContext.Age         = recordFromFile[i].Age;
                    fileCabinetServiceContext.Gender      = recordFromFile[i].Gender;
                    fileCabinetServiceContext.Salary      = recordFromFile[i].Salary;
                    this.contextStrategy.ValidateParameters(fileCabinetServiceContext);

                    for (int j = 0; j < record.Count; j++)
                    {
                        if (record[j].Id == recordFromFile[i].Id)
                        {
                            this.RemoveRecordInAllDictionary(this.list[i]);
                            this.list[i] = recordFromFile[j];
                            this.AddRecordInAllDictionary(this.list[i]);
                            isFind = true;
                            break;
                        }
                    }

                    if (!isFind)
                    {
                        this.list.Add(recordFromFile[i]);
                        this.AddRecordInAllDictionary(recordFromFile[i]);
                    }

                    isFind = false;
                }
                catch (Exception ex) when(ex is ArgumentException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException)
                {
                    Console.WriteLine($"{recordFromFile[i].Id}: {ex.Message}");
                }
            }
        }
        /// <summary>
        /// This method load records from file.
        /// </summary>
        /// <param name="snapshot">It is copy data.</param>
        /// <returns>records count.</returns>
        public int Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            var records = snapshot.Records;

            if (this.GetRecords().Count == 0)
            {
                foreach (var recordImport in records)
                {
                    try
                    {
                        this.validator.Validate(recordImport);

                        this.list.Add(recordImport);
                        this.AddRecordInAllDictionary(recordImport);
                    }
                    catch (ArgumentException ex)
                    {
                        Console.WriteLine(recordImport.Id + ex.Message);
                    }
                }
            }
            else
            {
                foreach (var recordImport in records)
                {
                    this.validator.Validate(recordImport);

                    var recordById = this.list.Find(x => x.Id == recordImport.Id);

                    if (recordById != null)
                    {
                        this.EditRecord(recordImport);
                    }
                    else
                    {
                        this.list.Add(recordImport);
                        this.AddRecordInAllDictionary(recordImport);
                    }
                }
            }

            return(this.list.Count);
        }
Пример #27
0
        private void ImportFromFormat(string format, string path)
        {
            string message = string.Empty;

            if (!File.Exists(path))
            {
                message = $"Import error: file {path} does not exist.";
            }

            FileStream fileStream = default;

            try
            {
                fileStream = new FileStream(path, FileMode.Open);
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine(ex.Message);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine($"Export failed: can't open file {path}.");
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (fileStream != null)
            {
                using var stream = new StreamReader(fileStream);
                var snapshot = new FileCabinetServiceSnapshot(Array.Empty <FileCabinetRecord>());

                if (format.Equals(CsvString, StringComparison.InvariantCultureIgnoreCase))
                {
                    using var reader = new FileCabinetRecordCsvReader(stream);
                    message          = this.LoadFrom(reader, path, snapshot);
                }

                if (format.Equals(XmlString, StringComparison.InvariantCultureIgnoreCase))
                {
                    using var reader = new FileCabinetRecordXmlReader(stream);
                    message          = this.LoadFrom(reader, path, snapshot);
                }
            }

            Console.WriteLine(message);
        }
        /// <summary>
        /// Adds logs about Restore method in the textfile.
        /// </summary>
        /// <param name="snapshot">Snapshot to restore by.</param>
        /// <returns>count records.</returns>
        public int Restore(FileCabinetServiceSnapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException(nameof(snapshot));
            }

            string toWrite = DateTime.Now.ToString("MM/dd/yyyy hh:mm", CultureInfo.InvariantCulture) + " Calling Restore()\n";

            this.writer.Write(toWrite);

            this.service.Restore(snapshot);

            toWrite = DateTime.Now.ToString("MM/dd/yyyy hh:mm", CultureInfo.InvariantCulture) + " Restore() imported " + snapshot.Records.Count + "records\n";
            this.writer.Write(toWrite);

            return(snapshot.Records.Count);
        }
        /// <inheritdoc/>
        public void Restore(FileCabinetServiceSnapshot snapshot)
        {
            string log;

            if (snapshot is null)
            {
                log = $"Calling {nameof(this.Restore)} {nameof(ArgumentNullException)} {nameof(snapshot)} is null";
                this.WriteLog(log);
                throw new ArgumentNullException(nameof(snapshot));
            }

            log = $"Calling {nameof(this.Restore)} with {nameof(snapshot)} = '{snapshot.Records.Count}'";
            this.WriteLog(log);

            this.service.Restore(snapshot);

            log = $"{nameof(this.Restore)}";
            this.WriteLog(log);
        }
Пример #30
0
        private string LoadFrom(IFileCabinetReader reader, string path, FileCabinetServiceSnapshot snapshot)
        {
            try
            {
                snapshot.LoadFrom(reader);
                this.Service.Restore(snapshot);
            }
            catch (ArgumentException ex)
            {
                return($"Import failed: {ex.Message}");
            }

            var builder = new StringBuilder();

            foreach (var item in snapshot.Logger)
            {
                builder.AppendLine(item);
            }

            builder.Append($"{snapshot?.Records.Count - snapshot.Logger.Count - 1} records were imported from {path}.");
            return(builder.ToString());
        }