Esempio n. 1
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);
        }
        private static void SetFileService()
        {
            FileStream fileStream = new FileStream(Configurator.GetConstantString("DefaultFilesystemFileName"), FileMode.OpenOrCreate, FileAccess.ReadWrite);

            fileCabinetService = new FileCabinetFilesystemService(fileStream);
            Console.WriteLine(Configurator.GetConstantString("UseFile"));
        }
        /// <summary>
        /// Writes a record into current stream.
        /// </summary>
        /// <param name="record">Record to write.</param>
        /// <exception cref="ArgumentNullException">Thrown when given record is null.</exception>
        public void Write(FileCabinetRecord record)
        {
            if (record is null)
            {
                throw new ArgumentNullException(nameof(record), Configurator.GetConstantString("NullRecord"));
            }

            this.writer.WriteStartElement(Configurator.GetConstantString("XmlElementRecord"));
            this.writer.WriteAttributeString(Configurator.GetConstantString("XmlElementId"), record.Id.ToString(CultureInfo.InvariantCulture));
            this.writer.WriteStartElement(Configurator.GetConstantString("XmlElementName"));
            this.writer.WriteAttributeString(Configurator.GetConstantString("XmlElementFirst"), record.FirstName);
            this.writer.WriteAttributeString(Configurator.GetConstantString("XmlElementLast"), record.LastName);
            this.writer.WriteEndElement();
            this.writer.WriteStartElement(Configurator.GetConstantString("XmlElementDateOfBirth"));
            this.writer.WriteString(record.DateOfBirth.ToString(Configurator.GetConstantString("DateFormatDM"), CultureInfo.InvariantCulture));
            this.writer.WriteEndElement();
            this.writer.WriteStartElement(Configurator.GetConstantString("XmlElementHeight"));
            this.writer.WriteString(record.Height.ToString(CultureInfo.InvariantCulture));
            this.writer.WriteEndElement();
            this.writer.WriteStartElement(Configurator.GetConstantString("XmlElementIncome"));
            this.writer.WriteString(record.Income.ToString(CultureInfo.InvariantCulture));
            this.writer.WriteEndElement();
            this.writer.WriteStartElement(Configurator.GetConstantString("XmlElementPatronymicLetter"));
            this.writer.WriteString(record.PatronymicLetter.ToString(CultureInfo.InvariantCulture));
            this.writer.WriteEndElement();
            this.writer.WriteEndElement();
        }
        /// <summary>
        /// Point of entrance to program.
        /// </summary>
        /// <param name="args">Command prompt arguments.</param>
        public static void Main(string[] args)
        {
            Console.WriteLine(Configurator.GetConstantString("HelloMessage"));
            SetCommandLineSettings(args);
            Console.WriteLine(Configurator.GetConstantString("HintMessage"));
            Console.WriteLine();
            var commands = CreateCommandHandlers();

            do
            {
                Console.Write(Configurator.GetConstantString("CommandStartChar"));
                var       inputs        = Console.ReadLine().Trim().Split(' ', 2);
                const int commandIndex  = 0;
                const int argumentIndex = 1;
                var       command       = inputs[commandIndex].Trim();
                if (string.IsNullOrEmpty(command))
                {
                    Console.WriteLine(Configurator.GetConstantString("HintMessage"));
                    continue;
                }

                var parameters = inputs.Length > 1 ? inputs[argumentIndex].Trim() : string.Empty;
                commands.Handle(new AppCommandRequest(command, parameters));
            }while (isRunning);
        }
        private static IList <FileCabinetRecord> TransformFromXmlToBaseModel(List <FileCabinetRecordXmlModel> source)
        {
            List <FileCabinetRecord> list = new List <FileCabinetRecord>();

            foreach (FileCabinetRecordXmlModel xmlModel in source)
            {
                try
                {
                    FileCabinetRecord record = new FileCabinetRecord
                    {
                        Id               = xmlModel.Id,
                        FirstName        = xmlModel.Name.FirstName,
                        LastName         = xmlModel.Name.LastName,
                        PatronymicLetter = xmlModel.PatronymicLetter.ToUpperInvariant()[0],
                        Income           = xmlModel.Income,
                        Height           = xmlModel.Height,
                        DateOfBirth      = DateTime.ParseExact(xmlModel.DateOfBirth, Configurator.GetConstantString("DateFormatDM"), CultureInfo.InvariantCulture),
                    };
                    list.Add(record);
                }
                catch (FormatException)
                {
                    Console.WriteLine($"Invalid data in {xmlModel.Id}{xmlModel.Name.FirstName}{xmlModel.Name.LastName}{xmlModel.PatronymicLetter[0]}{xmlModel.Income}{xmlModel.Height}. Data was skipped.");
                }
                catch (ArgumentException)
                {
                    Console.WriteLine($"Invalid data in {xmlModel.Id}{xmlModel.Name.FirstName}{xmlModel.Name.LastName}{xmlModel.PatronymicLetter[0]}{xmlModel.Income}{xmlModel.Height}. Data was skipped.");
                }
            }

            return(list);
        }
Esempio n. 6
0
        /// <summary>
        /// Writes a record into current stream.
        /// </summary>
        /// <param name="record">Record to write.</param>
        /// <exception cref="ArgumentNullException">Thrown when given record is null.</exception>
        public void Write(FileCabinetRecord record)
        {
            if (record is null)
            {
                throw new ArgumentNullException(nameof(record), Configurator.GetConstantString("NullRecord"));
            }

            string writing = $"{record.Id},{record.FirstName},{record.PatronymicLetter},{record.LastName},{record.DateOfBirth.ToString(Configurator.GetConstantString("DateFormatMD"), CultureInfo.InvariantCulture)},{record.Height},{record.Income}";

            this.writer.WriteLine(writing);
        }
        /// <summary>
        /// Updates records.
        /// </summary>
        /// <param name="records">Records to update.</param>
        /// <param name="fieldsAndValuesToSet">Fields and values to set.</param>
        /// <returns>Amount of updated records.</returns>
        /// <exception cref="ArgumentNullException">Thrown when records or fields and values to set is null.</exception>
        /// <exception cref="ArgumentException">Thrown when data is invalid.</exception>
        public int Update(IEnumerable <FileCabinetRecord> records, IEnumerable <IEnumerable <string> > fieldsAndValuesToSet)
        {
            if (records is null)
            {
                throw new ArgumentNullException(nameof(records), Configurator.GetConstantString("NullRecordsSequence"));
            }

            if (fieldsAndValuesToSet is null)
            {
                throw new ArgumentNullException(nameof(fieldsAndValuesToSet), Configurator.GetConstantString("NullFieldsAndValues"));
            }

            int result = 0;

            foreach (var record in records)
            {
                for (int i = 0; i < this.list.Count; i++)
                {
                    if (record.Id == this.list[i].Id)
                    {
                        FileCabinetRecord temp = new FileCabinetRecord()
                        {
                            Id               = record.Id,
                            FirstName        = record.FirstName,
                            LastName         = record.LastName,
                            DateOfBirth      = record.DateOfBirth,
                            Height           = record.Height,
                            Income           = record.Income,
                            PatronymicLetter = record.PatronymicLetter,
                        };

                        try
                        {
                            this.UpdateRecord(record, fieldsAndValuesToSet);
                            result++;
                        }
                        catch (ArgumentException ex)
                        {
                            record.Id               = temp.Id;
                            record.FirstName        = temp.FirstName;
                            record.LastName         = temp.LastName;
                            record.DateOfBirth      = temp.DateOfBirth;
                            record.Income           = temp.Income;
                            record.Height           = temp.Height;
                            record.PatronymicLetter = temp.PatronymicLetter;
                            throw new ArgumentException(ex.Message);
                        }
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Converts string to short.
        /// </summary>
        /// <param name="input">String to convert.</param>
        /// <returns>Whether convertion was succesfull, reason of fail and result.</returns>
        public static Tuple <bool, string, short> ConvertStringToShort(string input)
        {
            bool isConverted = short.TryParse(input, out short height);

            if (isConverted)
            {
                return(new Tuple <bool, string, short>(isConverted, string.Empty, height));
            }
            else
            {
                return(new Tuple <bool, string, short>(isConverted, Configurator.GetConstantString("InvalidShort"), short.MinValue));
            }
        }
        /// <summary>
        /// Converts string to date.
        /// </summary>
        /// <param name="input">String to convert.</param>
        /// <returns>Whether convertion was succesfull, reason of fail and result.</returns>
        public static Tuple <bool, string, DateTime> ConvertStringToDateTime(string input)
        {
            bool isConverted = DateTime.TryParseExact(input, Configurator.GetConstantString("DateFormatMD"), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateOfBirth);

            if (isConverted)
            {
                return(new Tuple <bool, string, DateTime>(isConverted, string.Empty, dateOfBirth));
            }
            else
            {
                return(new Tuple <bool, string, DateTime>(isConverted, Configurator.GetConstantString("InvalidDate"), DateTime.MinValue));
            }
        }
        /// <summary>
        /// Gets records from xml.
        /// </summary>
        /// <param name="xmlReader">Xml reader to get records.</param>
        public void LoadFromXml(XmlReader xmlReader)
        {
            FileCabinetRecordXmlReader fileXmlReader = new FileCabinetRecordXmlReader(xmlReader);

            try
            {
                this.records = fileXmlReader.ReadAll().ToArray();
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidDeserialize"));
            }
        }
        /// <summary>
        /// Converts string to decimal.
        /// </summary>
        /// <param name="input">String to convert.</param>
        /// <returns>Whether convertion was succesfull, reason of fail and result.</returns>
        public static Tuple <bool, string, decimal> ConvertStringToDecimal(string input)
        {
            bool isConverted = decimal.TryParse(input, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal income);

            if (isConverted)
            {
                return(new Tuple <bool, string, decimal>(isConverted, string.Empty, income));
            }
            else
            {
                return(new Tuple <bool, string, decimal>(isConverted, Configurator.GetConstantString("InvalidDecimal"), decimal.MinValue));
            }
        }
        /// <summary>
        /// Deletes records.
        /// </summary>
        /// <param name="records">Records to delete.</param>
        /// <returns>IDs of deleted records.</returns>
        /// <exception cref="ArgumentNullException">Thrown when records is null.</exception>
        public IEnumerable <int> Delete(IEnumerable <FileCabinetRecord> records)
        {
            if (records is null)
            {
                throw new ArgumentNullException(nameof(records), Configurator.GetConstantString("NullRecordsSequence"));
            }

            foreach (FileCabinetRecord record in records)
            {
                this.Remove(record.Id);
                yield return(record.Id);
            }
        }
        /// <summary>
        /// Saves records to csv file.
        /// </summary>
        /// <param name="writer">Streamwriter to save records.</param>
        /// <exception cref="ArgumentNullException">Writer must be not null.</exception>
        public void SaveToCsv(StreamWriter writer)
        {
            if (writer is null)
            {
                throw new ArgumentNullException(nameof(writer), Configurator.GetConstantString("NullStream"));
            }

            using FileCabinetRecordCsvWriter csvWriter = new FileCabinetRecordCsvWriter(writer);
            foreach (var record in this.records)
            {
                csvWriter.Write(record);
            }
        }
        /// <summary>
        /// Converts string to int.
        /// </summary>
        /// <param name="input">String to convert.</param>
        /// <returns>Whether convertion was succesfull, reason of fail and result.</returns>
        public static Tuple <bool, string, int> ConvertStringToInt(string input)
        {
            bool isConverted = int.TryParse(input, out int id);

            if (isConverted)
            {
                return(new Tuple <bool, string, int>(isConverted, string.Empty, id));
            }
            else
            {
                return(new Tuple <bool, string, int>(isConverted, Configurator.GetConstantString("InvalidInt"), int.MinValue));
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Creates new records with given parameters.
        /// </summary>
        /// <param name="transfer">Object to transfer parameters of new record.</param>
        /// <returns>ID of created record.</returns>
        /// <exception cref="ArgumentNullException">Throw when transfer object is null.</exception>
        /// <exception cref="ArgumentException">Thrown when transfer data is invalid.</exception>
        public int CreateRecord(RecordParametersTransfer transfer)
        {
            if (transfer is null)
            {
                throw new ArgumentNullException(nameof(transfer), Configurator.GetConstantString("NullTransfer"));
            }

            var validationResult = this.recordValidator.ValidateParameters(transfer.RecordSimulation());

            if (!validationResult.Item1)
            {
                throw new ArgumentException(validationResult.Item2);
            }

            int id;

            if (this.dictionaryIdOffset.Count is 0)
            {
                id = 1;
            }
            else
            {
                id = this.dictionaryIdOffset.Keys.Max() + 1;
            }

            this.dictionaryIdOffset.Add(id, this.currentOffset);
            this.currentOffset += this.sizeOfShort;
            this.binaryWriter.Seek(this.currentOffset, 0);
            this.binaryWriter.Write(id);
            this.currentOffset += this.sizeOfInt;
            this.binaryWriter.Write(transfer.FirstName);
            this.currentOffset += this.sizeOfString;
            this.binaryWriter.Seek(this.currentOffset, 0);
            this.binaryWriter.Write(transfer.LastName);
            this.currentOffset += this.sizeOfString;
            this.binaryWriter.Seek(this.currentOffset, 0);
            this.binaryWriter.Write(transfer.DateOfBirth.Day);
            this.currentOffset += this.sizeOfInt;
            this.binaryWriter.Write(transfer.DateOfBirth.Month);
            this.currentOffset += this.sizeOfInt;
            this.binaryWriter.Write(transfer.DateOfBirth.Year);
            this.currentOffset += this.sizeOfInt;
            this.binaryWriter.Write(transfer.PatronymicLetter);
            this.currentOffset += this.sizeOfChar;
            this.binaryWriter.Write(transfer.Income);
            this.currentOffset += this.sizeOfDecimal;
            this.binaryWriter.Write(transfer.Height);
            this.currentOffset += this.sizeOfShort;
            return(id);
        }
        /// <summary>
        /// Saves records to xml file.
        /// </summary>
        /// <param name="writer">Streamwriter to save records.</param>
        /// <exception cref="ArgumentNullException">Writer must be not null.</exception>
        public void SaveToXml(XmlWriter writer)
        {
            if (writer is null)
            {
                throw new ArgumentNullException(nameof(writer), Configurator.GetConstantString("NullStream"));
            }

            writer.WriteStartElement(Configurator.GetConstantString("XmlElementRecords"));
            using FileCabinetRecordXmlWriter xmlWriter = new FileCabinetRecordXmlWriter(writer);
            foreach (var record in this.records)
            {
                xmlWriter.Write(record);
            }

            writer.WriteEndElement();
        }
        /// <summary>
        /// Converts string to char.
        /// </summary>
        /// <param name="input">String to convert.</param>
        /// <returns>Whether convertion was succesfull, reason of fail and result.</returns>
        public static Tuple <bool, string, char> ConvertStringToChar(string input)
        {
            if (input is null)
            {
                return(new Tuple <bool, string, char>(false, Configurator.GetConstantString("InvalidChar"), char.MinValue));
            }

            bool isConverted = char.TryParse(input.ToUpperInvariant(), out char patronymicLetter);

            if (isConverted)
            {
                return(new Tuple <bool, string, char>(isConverted, string.Empty, patronymicLetter));
            }
            else
            {
                return(new Tuple <bool, string, char>(isConverted, Configurator.GetConstantString("InvalidChar"), char.MinValue));
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Inserts new record.
        /// </summary>
        /// <param name="record">Record to insert.</param>
        /// <returns>Id of inserted record.</returns>
        /// <exception cref="ArgumentNullException">Thrown when record is null.</exception>
        /// <exception cref="ArgumentException">Thrown when records data is invalid or when record with given id is already exists.</exception>
        public int Insert(FileCabinetRecord record)
        {
            if (record is null)
            {
                throw new ArgumentNullException(nameof(record), Configurator.GetConstantString("NullRecord"));
            }

            var validationResult = this.recordValidator.ValidateParameters(record);

            if (!validationResult.Item1)
            {
                throw new ArgumentException(validationResult.Item2);
            }

            if (this.dictionaryIdOffset.Keys.Contains(record.Id))
            {
                throw new ArgumentException(Configurator.GetConstantString("RecordIdExist"), nameof(record));
            }

            this.dictionaryIdOffset.Add(record.Id, this.currentOffset);
            this.currentOffset += this.sizeOfShort;
            this.binaryWriter.Seek(this.currentOffset, 0);
            this.binaryWriter.Write(record.Id);
            this.currentOffset += this.sizeOfInt;
            this.binaryWriter.Write(record.FirstName);
            this.currentOffset += this.sizeOfString;
            this.binaryWriter.Seek(this.currentOffset, 0);
            this.binaryWriter.Write(record.LastName);
            this.currentOffset += this.sizeOfString;
            this.binaryWriter.Seek(this.currentOffset, 0);
            this.binaryWriter.Write(record.DateOfBirth.Day);
            this.currentOffset += this.sizeOfInt;
            this.binaryWriter.Write(record.DateOfBirth.Month);
            this.currentOffset += this.sizeOfInt;
            this.binaryWriter.Write(record.DateOfBirth.Year);
            this.currentOffset += this.sizeOfInt;
            this.binaryWriter.Write(record.PatronymicLetter);
            this.currentOffset += this.sizeOfChar;
            this.binaryWriter.Write(record.Income);
            this.currentOffset += this.sizeOfDecimal;
            this.binaryWriter.Write(record.Height);
            this.currentOffset += this.sizeOfShort;
            return(record.Id);
        }
        /// <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.ids.Contains(record.Id))
                {
                    var temp = this.list.Find(x => x.Id == record.Id);
                    temp.FirstName        = record.FirstName;
                    temp.LastName         = record.LastName;
                    temp.DateOfBirth      = record.DateOfBirth;
                    temp.Height           = record.Height;
                    temp.Income           = record.Income;
                    temp.PatronymicLetter = record.PatronymicLetter;
                    count++;
                }
                else
                {
                    this.list.Add(record);
                    this.ids.Add(record.Id);
                    count++;
                }
            }

            return(count);
        }
Esempio n. 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileCabinetFilesystemService"/> class.
        /// </summary>
        /// <param name="fileStream">Stream to work with file.</param>
        /// <exception cref="ArgumentNullException">Thrown when stream is null.</exception>
        public FileCabinetFilesystemService(FileStream fileStream)
        {
            if (fileStream is null)
            {
                throw new ArgumentNullException(nameof(fileStream), Configurator.GetConstantString("NullStream"));
            }

            this.fileStream   = fileStream;
            this.binaryWriter = new BinaryWriter(fileStream);
            this.binaryReader = new BinaryReader(fileStream);
            try
            {
                this.sizeOfChar    = int.Parse(Configurator.GetSetting("SizeOfChar"), CultureInfo.InvariantCulture);
                this.sizeOfShort   = int.Parse(Configurator.GetSetting("SizeOfShort"), CultureInfo.InvariantCulture);
                this.sizeOfInt     = int.Parse(Configurator.GetSetting("SizeOfInt"), CultureInfo.InvariantCulture);
                this.sizeOfDecimal = int.Parse(Configurator.GetSetting("SizeOfDecimal"), CultureInfo.InvariantCulture);
                this.sizeOfString  = int.Parse(Configurator.GetSetting("SizeOfString"), CultureInfo.InvariantCulture);
                this.sizeOfRecord  = int.Parse(Configurator.GetSetting("SizeOfRecord"), CultureInfo.InvariantCulture);
            }
            catch (ArgumentException)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidTypeSyzeData"));
                Console.WriteLine(Configurator.GetConstantString("ClosingProgram"));
                Environment.Exit(-1);
            }
            catch (FormatException)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidTypeSyzeData"));
                Console.WriteLine(Configurator.GetConstantString("ClosingProgram"));
                Environment.Exit(-1);
            }
            catch (OverflowException)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidTypeSyzeData"));
                Console.WriteLine(Configurator.GetConstantString("ClosingProgram"));
                Environment.Exit(-1);
            }
        }
        /// <summary>
        /// Inserts new record.
        /// </summary>
        /// <param name="record">Record to insert.</param>
        /// <returns>Id of inserted record.</returns>
        /// <exception cref="ArgumentNullException">Thrown when record is null.</exception>
        /// <exception cref="ArgumentException">Thrown when records data is invalid.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when record with given id is already exists.</exception>
        public int Insert(FileCabinetRecord record)
        {
            if (record is null)
            {
                throw new ArgumentNullException(nameof(record), Configurator.GetConstantString("NullRecord"));
            }

            var validationResult = this.recordValidator.ValidateParameters(record);

            if (!validationResult.Item1)
            {
                throw new ArgumentException(validationResult.Item2, nameof(record));
            }

            if (this.ids.Contains(record.Id))
            {
                throw new ArgumentOutOfRangeException(nameof(record), Configurator.GetConstantString("RecordIdExist"));
            }

            this.list.Add(record);
            this.ids.Add(record.Id);
            return(record.Id);
        }
        /// <summary>
        /// Creates new records with given parameters.
        /// </summary>
        /// <param name="transfer">Object to transfer parameters of new record.</param>
        /// <returns>ID of created record.</returns>
        /// <exception cref="ArgumentNullException">Throw when transfer object is null.</exception>
        /// <exception cref="ArgumentException">Thrown when transfer data is invalid.</exception>
        public int CreateRecord(RecordParametersTransfer transfer)
        {
            if (transfer is null)
            {
                throw new ArgumentNullException(nameof(transfer), Configurator.GetConstantString("NullTransfer"));
            }

            var validationResult = this.recordValidator.ValidateParameters(transfer.RecordSimulation());

            if (!validationResult.Item1)
            {
                throw new ArgumentException(validationResult.Item2);
            }

            var record = new FileCabinetRecord
            {
                FirstName        = transfer.FirstName,
                LastName         = transfer.LastName,
                DateOfBirth      = transfer.DateOfBirth,
                Height           = transfer.Height,
                Income           = transfer.Income,
                PatronymicLetter = transfer.PatronymicLetter,
            };

            if (this.list.Count is 0)
            {
                record.Id = 1;
            }
            else
            {
                record.Id = this.ids.Max() + 1;
            }

            this.list.Add(record);
            this.ids.Add(record.Id);
            return(record.Id);
        }
        private static void SetCommandLineSettings(string[] args)
        {
            IConfigurationRoot validationRules = null;

            try
            {
                validationRules = new ConfigurationBuilder()
                                  .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                                  .AddJsonFile(Configurator.GetSetting("ValidationRulesFileName"))
                                  .Build();
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine($"{Configurator.GetConstantString("MissingValidation")} {Configurator.GetSetting("ConstantStringsFileName")}");
                Console.WriteLine(Configurator.GetConstantString("ClosingProgram"));
                Environment.Exit(-1);
            }
            catch (FormatException)
            {
                Console.WriteLine(Configurator.GetConstantString("InvalidValidationFile"));
                Console.WriteLine(Configurator.GetConstantString("ClosingProgram"));
                Environment.Exit(-1);
            }

            Options options = GetCommandLineArguments(args);

            if (options.Storage.Equals(Configurator.GetConstantString("FileStorage"), StringComparison.InvariantCultureIgnoreCase))
            {
                SetFileService();
            }
            else if (options.Storage.Equals(Configurator.GetConstantString("MemoryStorage"), StringComparison.InvariantCultureIgnoreCase))
            {
                SetMemoryService();
            }
            else
            {
                Console.WriteLine($"Wrong command line argument {options.Storage}.");
                Environment.Exit(-1);
            }

            if (options.Rule.Equals(Configurator.GetConstantString("CustomRule"), StringComparison.InvariantCultureIgnoreCase))
            {
                SetCustomService(validationRules);
            }
            else if (options.Rule.Equals(Configurator.GetConstantString("DefaultRule"), StringComparison.InvariantCultureIgnoreCase))
            {
                SetDefaultService(validationRules);
            }
            else
            {
                Console.WriteLine($"Wrong command line argument {options.Rule}.");
                Environment.Exit(-1);
            }

            if (fileCabinetService is FileCabinetFilesystemService)
            {
                try
                {
                    fileCabinetService.Restore(fileCabinetService.MakeSnapshot());
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    Console.WriteLine(Configurator.GetConstantString("InvalidFile"));
                    Console.WriteLine(Configurator.GetConstantString("ClosingProgram"));
                    Environment.Exit(-1);
                }
            }

            if (options.Logger)
            {
                SetLogger();
            }

            if (options.Stopwatch)
            {
                SetStopwatch();
            }
        }
        private static Options GetCommandLineArguments(string[] args)
        {
            List <string> singleParams       = new List <string>();
            List <string> doubleParams       = new List <string>();
            List <string> doubleParamsValues = new List <string>();

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].Substring(0, 2) == Configurator.GetConstantString("DoubleHyphen"))
                {
                    singleParams.Add(args[i]);
                    continue;
                }
                else if (args[i].Substring(0, 1) == Configurator.GetConstantString("Hyphen"))
                {
                    if (i == (args.Length - 1))
                    {
                        Console.WriteLine($"Invalid command line parameter '{args[i]}'.");
                        Environment.Exit(-1);
                    }

                    doubleParams.Add(args[i]);
                    doubleParamsValues.Add(args[i + 1]);
                    i++;
                    continue;
                }
                else
                {
                    Console.WriteLine($"Invalid command line parameter '{args[i]}'.");
                    Environment.Exit(-1);
                }
            }

            Options options = new Options();

            foreach (string param in singleParams)
            {
                string[] keyValuePair = param.Split('=');
                if (keyValuePair.Length == 1)
                {
                    if (keyValuePair[0] == Configurator.GetConstantString("StopwatchCommandLineParameter"))
                    {
                        options.Stopwatch = true;
                    }
                    else if (keyValuePair[0] == Configurator.GetConstantString("LoggerCommandLineParameter"))
                    {
                        options.Logger = true;
                    }
                    else
                    {
                        Console.WriteLine($"Invalid command line parameter '{param}'.");
                        Environment.Exit(-1);
                    }
                }
                else if (keyValuePair.Length == 2)
                {
                    if (keyValuePair[0] == Configurator.GetConstantString("ValidationRuleCommandLineParameter"))
                    {
                        options.Rule = keyValuePair[1];
                    }
                    else if (keyValuePair[0] == "--storage")
                    {
                        options.Storage = keyValuePair[1];
                    }
                    else
                    {
                        Console.WriteLine($"Invalid command line parameter '{param}'.");
                        Environment.Exit(-1);
                    }
                }
                else
                {
                    Console.WriteLine($"Invalid command line parameter '{param}'.");
                    Environment.Exit(-1);
                }
            }

            for (int i = 0; i < doubleParams.Count; i++)
            {
                if (doubleParams[i] == Configurator.GetConstantString("ShortValidationRuleCommandLineParameter"))
                {
                    options.Rule = doubleParamsValues[i];
                }
                else if (doubleParams[i] == Configurator.GetConstantString("ShortStorageCommandLineParameter"))
                {
                    options.Storage = doubleParamsValues[i];
                }
                else
                {
                    Console.WriteLine($"Invalid command line parameter '{doubleParams[i]}'.");
                    Environment.Exit(-1);
                }
            }

            return(options);
        }
 /// <summary>
 /// Defragments file.
 /// </summary>
 /// <returns>Amount of purged records.</returns>
 /// <exception cref="InvalidOperationException">Thrown always, because can't purge in memory service.</exception>
 public int Purge()
 {
     throw new InvalidOperationException(Configurator.GetConstantString("PurgeInMemory"));
 }
 private static void SetLogger()
 {
     fileCabinetService = new ServiceLogger(fileCabinetService);
     Console.WriteLine(Configurator.GetConstantString("UseLogger"));
 }
 private static void SetStopwatch()
 {
     fileCabinetService = new ServiceMeter(fileCabinetService);
     Console.WriteLine(Configurator.GetConstantString("UseStopwatch"));
 }
 private static void SetCustomService(IConfigurationRoot configuration)
 {
     fileCabinetService.SetRecordValidator(new ValidatorBuilder().CreateValidator(configuration.GetSection("custom")));
     Console.WriteLine(Configurator.GetConstantString("UseCustomRules"));
 }
        private void UpdateRecord(FileCabinetRecord record, IEnumerable <IEnumerable <string> > fieldsAndValuesToSet)
        {
            foreach (var keyValuePair in fieldsAndValuesToSet)
            {
                var key   = keyValuePair.First();
                var value = keyValuePair.Last();
                if (key.Equals(Configurator.GetConstantString("ParameterId"), StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new ArgumentException(Configurator.GetConstantString("IdChange"), nameof(fieldsAndValuesToSet));
                }

                if (key.Equals(Configurator.GetConstantString("ParameterFirstName"), StringComparison.InvariantCultureIgnoreCase))
                {
                    var legacy = record.FirstName;
                    record.FirstName = value;
                    var validationResult = this.recordValidator.ValidateParameters(record);
                    if (!validationResult.Item1)
                    {
                        record.FirstName = legacy;
                        throw new ArgumentException(validationResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    continue;
                }

                if (key.Equals(Configurator.GetConstantString("ParameterLastName"), StringComparison.InvariantCultureIgnoreCase))
                {
                    var legacy = record.LastName;
                    record.LastName = value;
                    var validationResult = this.recordValidator.ValidateParameters(record);
                    if (!validationResult.Item1)
                    {
                        record.LastName = legacy;
                        throw new ArgumentException(validationResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    continue;
                }

                if (key.Equals(Configurator.GetConstantString("ParameterDateOfBirth"), StringComparison.InvariantCultureIgnoreCase))
                {
                    var conversionResult = Converter.ConvertStringToDateTime(value);
                    if (!conversionResult.Item1)
                    {
                        throw new ArgumentException(conversionResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    var legacy = record.DateOfBirth;
                    record.DateOfBirth = conversionResult.Item3;
                    var validationResult = this.recordValidator.ValidateParameters(record);
                    if (!validationResult.Item1)
                    {
                        record.DateOfBirth = legacy;
                        throw new ArgumentException(validationResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    continue;
                }

                if (key.Equals(Configurator.GetConstantString("ParameterPatronymicLetter"), StringComparison.InvariantCultureIgnoreCase))
                {
                    var conversionResult = Converter.ConvertStringToChar(value);
                    if (!conversionResult.Item1)
                    {
                        throw new ArgumentException(conversionResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    var legacy = record.PatronymicLetter;
                    record.PatronymicLetter = conversionResult.Item3;
                    var validationResult = this.recordValidator.ValidateParameters(record);
                    if (!validationResult.Item1)
                    {
                        record.PatronymicLetter = legacy;
                        throw new ArgumentException(validationResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    continue;
                }

                if (key.Equals(Configurator.GetConstantString("ParameterIncome"), StringComparison.InvariantCultureIgnoreCase))
                {
                    var conversionResult = Converter.ConvertStringToDecimal(value);
                    if (!conversionResult.Item1)
                    {
                        throw new ArgumentException(conversionResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    var legacy = record.Income;
                    record.Income = conversionResult.Item3;
                    var validationResult = this.recordValidator.ValidateParameters(record);
                    if (!validationResult.Item1)
                    {
                        record.Income = legacy;
                        throw new ArgumentException(validationResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    continue;
                }

                if (key.Equals(Configurator.GetConstantString("ParameterHeight"), StringComparison.InvariantCultureIgnoreCase))
                {
                    var conversionResult = Converter.ConvertStringToShort(value);
                    if (!conversionResult.Item1)
                    {
                        throw new ArgumentException(conversionResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    var legacy = record.Height;
                    record.Height = conversionResult.Item3;
                    var validationResult = this.recordValidator.ValidateParameters(record);
                    if (!validationResult.Item1)
                    {
                        record.Height = legacy;
                        throw new ArgumentException(validationResult.Item2, nameof(fieldsAndValuesToSet));
                    }

                    continue;
                }

                throw new ArgumentException(Configurator.GetConstantString("KeyNotExist"), nameof(fieldsAndValuesToSet));
            }
        }
 private static void SetMemoryService()
 {
     fileCabinetService = new FileCabinetMemoryService();
     Console.WriteLine(Configurator.GetConstantString("UseMemory"));
 }