/// <summary>
        /// Validates the parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <exception cref="ArgumentNullException">DateOfBirth is null.</exception>
        /// <exception cref="ArgumentException">DateOfBirth - The {nameof(parameters.DateOfBirth)} can't be less than {this.from.ToShortDateString()} and larger than {this.to.ToShortDateString()}.</exception>
        public void ValidateParameters(RecordParameters parameters)
        {
            if (parameters.DateOfBirth == null)
            {
                throw new ArgumentNullException($"{parameters.DateOfBirth} cannot be null.", nameof(parameters.DateOfBirth));
            }

            if (parameters.DateOfBirth > this.to || parameters.DateOfBirth < this.from)
            {
                throw new ArgumentException(
                          nameof(parameters.DateOfBirth),
                          $"The {nameof(parameters.DateOfBirth)} can't be less than {this.from.ToShortDateString()} and larger than {this.to.ToShortDateString()}.");
            }
        }
Пример #2
0
        /// <summary>
        /// Inserts the record.
        /// </summary>
        /// <param name="record">The record.</param>
        /// <param name="id">The identifier.</param>
        /// <exception cref="ArgumentNullException">record is null.</exception>
        public void InsertRecord(RecordParameters record, int id)
        {
            if (record == null)
            {
                throw new ArgumentNullException(nameof(record));
            }

            this.logger.Info($"{DateTime.Now.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)} - " +
                             $"Calling Insert() with Id = '{id}', FirstName = '{record.FirstName}', " +
                             $"LastName = '{record.LastName}', DateOfBirth = '{record.DateOfBirth.ToShortDateString()}', " +
                             $"Gender = '{record.Gender}', Office = '{record.Office}', Salary = '{record.Salary}'");
            this.service.InsertRecord(record, id);
            this.logger.Info($"{DateTime.Now.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)} - " +
                             $"Insert() inserted record");
        }
        /// <summary>
        /// Validates the parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <exception cref="ArgumentNullException">LastName is null.</exception>
        /// <exception cref="ArgumentException">LastName.</exception>
        public void ValidateParameters(RecordParameters parameters)
        {
            var lastname = parameters.LastName;

            if (lastname is null)
            {
                throw new ArgumentNullException($"{parameters.LastName} cannot be null.", nameof(parameters.LastName));
            }

            if ((lastname.Length < this.minLength) ||
                (lastname.Length >= this.maxLength) ||
                string.IsNullOrWhiteSpace(lastname))
            {
                throw new ArgumentException(nameof(parameters.LastName));
            }
        }
Пример #4
0
        /// <summary>
        /// Creates the record.
        /// </summary>
        /// <param name="recordParameters">The record parameters.</param>
        /// <param name="id">The identifier.</param>
        public void InsertRecord(RecordParameters recordParameters, int id)
        {
            if (recordParameters == null)
            {
                throw new ArgumentNullException(nameof(recordParameters));
            }

            this.stopWatch.Reset();
            this.stopWatch.Start();
            this.service.InsertRecord(recordParameters, id);

            this.stopWatch.Stop();
            this.ticks = this.stopWatch.ElapsedTicks;

            this.write($"Insert method execution duration is {this.ticks} ticks.");
        }
Пример #5
0
        /// <summary>
        /// Creates the record.
        /// </summary>
        /// <param name="record">The record.</param>
        /// <returns>Id of new file cabinet record.</returns>
        public int CreateRecord(RecordParameters record)
        {
            if (record == null)
            {
                throw new ArgumentNullException(nameof(record));
            }

            this.stopWatch.Reset();
            this.stopWatch.Start();
            var result = this.service.CreateRecord(record);

            this.stopWatch.Stop();
            this.ticks = this.stopWatch.ElapsedTicks;

            this.write($"Create method execution duration is {this.ticks} ticks.");
            return(result);
        }
        private void EditRecord(int id, RecordParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (id <= 0)
            {
                throw new ArgumentException($"The {nameof(id)} have to be larger than zero.", nameof(id));
            }

            if (!this.IsThereARecordWithThisId(id, out long position))
            {
                throw new ArgumentException($"Record #{nameof(id)} doesn't exist.", nameof(id));
            }

            this.validator.ValidateParameters(parameters);

            this.RemoveFromDictionaries(id);

            var byteFirstName = System.Text.UnicodeEncoding.Unicode.GetBytes(parameters.FirstName.PadRight(60));
            var byteLastName  = System.Text.UnicodeEncoding.Unicode.GetBytes(parameters.LastName.PadRight(60));
            var byteYear      = BitConverter.GetBytes(parameters.DateOfBirth.Year);
            var byteMonth     = BitConverter.GetBytes(parameters.DateOfBirth.Month);
            var byteDay       = BitConverter.GetBytes(parameters.DateOfBirth.Day);
            var byteGender    = BitConverter.GetBytes(parameters.Gender);
            var byteOffice    = BitConverter.GetBytes(parameters.Office);
            var byteSalary    = GetBytes(parameters.Salary);

            this.fileStream.Seek(position + FirstNamePosition, SeekOrigin.Begin);

            using (BinaryWriter writeBinay = new BinaryWriter(this.fileStream, Encoding.Unicode, true))
            {
                writeBinay.Write(byteFirstName, 0, byteFirstName.Length);
                writeBinay.Write(byteLastName, 0, byteLastName.Length);
                writeBinay.Write(byteYear, 0, byteYear.Length);
                writeBinay.Write(byteMonth, 0, byteMonth.Length);
                writeBinay.Write(byteDay, 0, byteDay.Length);
                writeBinay.Write(byteGender, 0, byteGender.Length);
                writeBinay.Write(byteOffice, 0, byteOffice.Length);
                writeBinay.Write(byteSalary, 0, byteSalary.Length);
            }

            this.AddToDictionaries(parameters, position);
        }
Пример #7
0
        /// <summary>
        /// Creates the record.
        /// </summary>
        /// <param name="record">The record.</param>
        /// <returns>
        /// Id of new file cabinet record.
        /// </returns>
        /// <exception cref="ArgumentNullException">record is null.</exception>
        public int CreateRecord(RecordParameters record)
        {
            if (record == null)
            {
                throw new ArgumentNullException(nameof(record));
            }

            this.logger.Info($"{DateTime.Now.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)} - " +
                             $"Calling Create() with FirstName = '{record.FirstName}', " +
                             $"LastName = '{record.LastName}', DateOfBirth = '{record.DateOfBirth.ToShortDateString()}', " +
                             $"Gender = '{record.Gender}', Office = '{record.Office}', Salary = '{record.Salary}'");
            var result = this.service.CreateRecord(record);

            this.logger.Info($"{DateTime.Now.ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)} - " +
                             $"Create() returned '{result}'");
            return(result);
        }
        /// <summary>
        /// Gets the record parameters.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="fileStream">The file stream.</param>
        /// <returns>Records parameters.</returns>
        /// <exception cref="ArgumentNullException">
        /// reader
        /// or
        /// fileStream.
        /// </exception>
        public static RecordParameters GetRecordParameters(this BinaryReader reader, FileStream fileStream)
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            if (fileStream == null)
            {
                throw new ArgumentNullException(nameof(fileStream));
            }

            RecordParameters recordParameters = GetRecordParametersFromFile(reader, fileStream);

            fileStream.Seek(-RecordInBytesLength, SeekOrigin.Current);

            return(recordParameters);
        }
        private void CreateFileCabinetRecord(RecordParameters rec, int id)
        {
            this.validator.ValidateParameters(rec);
            var record = new FileCabinetRecord
            {
                Id          = id,
                FirstName   = rec.FirstName,
                LastName    = rec.LastName,
                DateOfBirth = rec.DateOfBirth,
                Gender      = rec.Gender,
                Office      = rec.Office,
                Salary      = rec.Salary,
            };

            this.WriteToTheBinaryFile(record);
            long recordPosition = this.fileStream.Position - RecordInBytesLength;

            this.idpositionPairs.Add(record.Id, recordPosition);
            this.AddToDictionaries(rec, recordPosition);
        }
        private void AddToDictionaries(RecordParameters parameters, long recordPosition)
        {
            if (!this.firstNameDictionary.ContainsKey(parameters.FirstName))
            {
                this.firstNameDictionary.Add(parameters.FirstName, new List <long>());
            }

            if (!this.lastNameDictionary.ContainsKey(parameters.LastName))
            {
                this.lastNameDictionary.Add(parameters.LastName, new List <long>());
            }

            if (!this.dateOfBirthDictionary.ContainsKey(parameters.DateOfBirth))
            {
                this.dateOfBirthDictionary.Add(parameters.DateOfBirth, new List <long>());
            }

            this.firstNameDictionary[parameters.FirstName].Add(recordPosition);
            this.lastNameDictionary[parameters.LastName].Add(recordPosition);
            this.dateOfBirthDictionary[parameters.DateOfBirth].Add(recordPosition);
        }
        private void Create()
        {
            var(firstName, lastName, dateOfBirth, gender, office, salary) = this.ParameterEntry();

            int recordId = 0;

            try
            {
                RecordParameters record = new RecordParameters(firstName, lastName, dateOfBirth, gender, office, salary);
                recordId = this.Service.CreateRecord(record);
                write($"Record #{recordId} is created.");
            }
            catch (ArgumentNullException anex)
            {
                write($"Record wasn't created. {anex.Message}");
                write(HintMessage);
            }
            catch (ArgumentException aex)
            {
                write($"Record wasn't created. {aex.Message}");
                write(HintMessage);
            }
        }
        /// <summary>
        /// Inserts the record.
        /// </summary>
        /// <param name="rec">The record.</param>
        /// <param name="id">The identifier.</param>
        /// <exception cref="ArgumentNullException">rec is null.</exception>
        /// <exception cref="ArgumentException">The '{nameof(id)}' can not be less than one.</exception>
        public void InsertRecord(RecordParameters rec, int id)
        {
            if (rec == null)
            {
                throw new ArgumentNullException(nameof(rec));
            }

            if (id < 1)
            {
                throw new ArgumentException($"The '{nameof(id)}' can not be less than one.", nameof(id));
            }

            this.validator.ValidateParameters(rec);
            if (!this.IsThereARecordWithThisId(id))
            {
                this.fileStream.Seek(0, SeekOrigin.End);
                this.CreateFileCabinetRecord(rec, id);
            }
            else
            {
                throw new ArgumentException($"The record #{id} is already exist.", nameof(id));
            }
        }
Пример #13
0
        /// <summary>
        /// Validates the parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <exception cref="ArgumentException">gender - The {nameof(gender)} can be only {exc}.</exception>
        public void ValidateParameters(RecordParameters parameters)
        {
            bool flag = true;

            foreach (var g in this.gender)
            {
                if (g == parameters.Gender)
                {
                    flag = false;
                }
            }

            if (flag)
            {
                StringBuilder exc = new StringBuilder();
                foreach (var g in this.gender)
                {
                    exc.Append(g + " ");
                }

                throw new ArgumentException(nameof(parameters.Gender), $"The {nameof(parameters.Gender)} can be only {exc.ToString()}.");
            }
        }
        private void GetRecordWithNewParameters(RecordParameters recordParameters, out int id, long position, out RecordParameters newRecordParameters)
        {
            string   pfirstname   = null;
            string   plastname    = null;
            DateTime pdateofbirth = default(DateTime);
            char     pgender      = default(char);
            short    poffice      = -1;
            decimal  psalary      = -1;

            using (BinaryReader reader = new BinaryReader(this.fileStream, Encoding.Unicode, true))
                using (BinaryWriter writeBinay = new BinaryWriter(this.fileStream, Encoding.Unicode, true))
                {
                    this.fileStream.Seek(position, SeekOrigin.Begin);
                    var existRecordsParameters = reader.GetRecordParameters(this.fileStream);
                    id = reader.GetId(this.fileStream);

                    pfirstname   = recordParameters.FirstName ?? existRecordsParameters.FirstName;
                    plastname    = recordParameters.LastName ?? existRecordsParameters.LastName;
                    pdateofbirth = recordParameters.DateOfBirth != default(DateTime) ? recordParameters.DateOfBirth : existRecordsParameters.DateOfBirth;
                    pgender      = recordParameters.Gender != default(char) ? recordParameters.Gender : existRecordsParameters.Gender;
                    poffice      = recordParameters.Office != -1 ? recordParameters.Office : existRecordsParameters.Office;
                    psalary      = recordParameters.Salary != -1 ? recordParameters.Salary : existRecordsParameters.Salary;
                }

            newRecordParameters = new RecordParameters(pfirstname, plastname, pdateofbirth, pgender, poffice, psalary);
        }
        /// <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));
            }

            long position;

            exceptions = new Dictionary <int, string>();
            var recordsFromFile = snapshot.FileCabinetRecords.ToList();

            using (BinaryReader binaryReader = new BinaryReader(this.fileStream, Encoding.Unicode, true))
            {
                this.FillAllDictionaries();

                bool flag    = false;
                int  existId = -1;
                foreach (var record in recordsFromFile)
                {
                    flag = false;
                    foreach (var idkey in this.idpositionPairs.Keys)
                    {
                        if (record.Id == idkey)
                        {
                            flag    = true;
                            existId = idkey;
                            break;
                        }
                    }

                    if (flag)
                    {
                        long existRecordPosition = this.idpositionPairs[existId];
                        this.fileStream.Seek(existRecordPosition, SeekOrigin.Begin);
                    }
                    else
                    {
                        this.fileStream.Seek(0, SeekOrigin.End);
                    }

                    try
                    {
                        if (record.Id <= 0)
                        {
                            throw new ArgumentException(nameof(record.Id));
                        }

                        var recordParameters = new RecordParameters(
                            record.FirstName, record.LastName, record.DateOfBirth, record.Gender, record.Office, record.Salary);
                        this.validator.ValidateParameters(recordParameters);
                        if (this.idpositionPairs.ContainsKey(record.Id))
                        {
                            this.RemoveFromDictionaries(record.Id);
                            this.idpositionPairs.Remove(record.Id);
                        }

                        if (!this.idpositionPairs.ContainsKey(record.Id))
                        {
                            position = this.fileStream.Position;
                            this.idpositionPairs.Add(record.Id, position);
                            this.AddToDictionaries(recordParameters, position);
                        }

                        this.WriteToTheBinaryFile(record);
                    }
                    catch (ArgumentException ex)
                    {
                        exceptions.Add(record.Id, ex.Message);
                    }
                }
            }
        }
Пример #16
0
        private void Update(string parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (!parameters.Contains("set", StringComparison.InvariantCulture) ||
                !parameters.Contains("where", StringComparison.InvariantCulture))
            {
                throw new ArgumentException(
                          "Invalid command. Example: update set firstname = 'John', lastname = 'Doe' , dateofbirth = '5/18/1986' where id = '1'",
                          nameof(parameters));
            }

            if (parameters.Contains("or", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException(
                          "This method supports only AND condition. Example: update set DateOfBirth = '5/18/1986' where FirstName='Stan' and LastName='Smith'",
                          nameof(parameters));
            }

            var words = parameters
                        .Split(this.Separator.ToArray())
                        .Where(s => s.Length > 0)
                        .ToList();
            string   firstname   = null;
            string   lastname    = null;
            DateTime dateofbirth = default(DateTime);
            char     gender      = default(char);
            short    office      = -1;
            decimal  salary      = -1;
            string   key;
            string   value;
            var      keyValuePairs = new List <KeyValuePair <string, string> >();

            if (words[0].Equals("set", StringComparison.InvariantCultureIgnoreCase))
            {
                int i = 1;
                do
                {
                    key   = words[i].ToUpperInvariant();
                    value = words[i + 1];
                    switch (key)
                    {
                    case "FIRSTNAME":
                        firstname = value;
                        break;

                    case "LASTNAME":
                        lastname = value;
                        break;

                    case "DATEOFBIRTH":
                        if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date))
                        {
                            dateofbirth = date;
                        }

                        break;

                    case "GENDER":
                        gender = char.Parse(value);
                        break;

                    case "OFFICE":
                        office = short.Parse(value, CultureInfo.InvariantCulture);
                        break;

                    case "SALARY":
                        salary = decimal.Parse(value, CultureInfo.InvariantCulture);
                        break;

                    default:
                        throw new ArgumentException(nameof(key), $"The parameter '{words[i]}' does not supported.");
                    }

                    i += 2;
                }while (!words[i].Equals("where", StringComparison.InvariantCultureIgnoreCase));
                RecordParameters setRecord = new RecordParameters(firstname, lastname, dateofbirth, gender, office, salary);

                while (++i < words.Count)
                {
                    keyValuePairs.Add(new KeyValuePair <string, string>(words[i].ToUpperInvariant(), words[i + 1]));
                    i += 2;
                }

                List <int> ids = this.Service.Update(this.Service.GetRecords().Where(keyValuePairs, SearchCondition.And), setRecord, keyValuePairs);
                Print(ids);
            }
            else
            {
                throw new ArgumentException("Request is not valid. " +
                                            "Example: update set firstname = 'John', lastname = 'Doe' , dateofbirth = '5/18/1986' where id = '1'");
            }
        }