コード例 #1
0
        private FileCabinetRecord GetRecord(int offset)
        {
            int tempOffset = offset + this.sizeOfShort;

            this.binaryReader.BaseStream.Seek(tempOffset, 0);
            FileCabinetRecord tempRecord = new FileCabinetRecord
            {
                Id = this.binaryReader.ReadInt32(),
            };

            tempOffset          += this.sizeOfInt;
            tempRecord.FirstName = this.binaryReader.ReadString();
            this.binaryReader.BaseStream.Seek(tempOffset + this.sizeOfString, 0);
            tempRecord.LastName = this.binaryReader.ReadString();
            tempOffset         += this.sizeOfString;
            this.binaryReader.BaseStream.Seek(tempOffset + this.sizeOfString, 0);
            int day   = this.binaryReader.ReadInt32();
            int month = this.binaryReader.ReadInt32();
            int year  = this.binaryReader.ReadInt32();

            tempRecord.DateOfBirth      = tempRecord.DateOfBirth.AddDays(day - 1);
            tempRecord.DateOfBirth      = tempRecord.DateOfBirth.AddMonths(month - 1);
            tempRecord.DateOfBirth      = tempRecord.DateOfBirth.AddYears(year - 1);
            tempRecord.PatronymicLetter = this.binaryReader.ReadChar();
            tempRecord.Income           = this.binaryReader.ReadDecimal();
            tempRecord.Height           = this.binaryReader.ReadInt16();

            return(tempRecord);
        }
コード例 #2
0
        /// <summary>Creates new <see cref="FileCabinetRecord"/> instance.</summary>
        /// <param name="userInputData">User input data.</param>
        /// <returns>Returns identifier of the new <see cref="FileCabinetRecord"/> instance.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <em>userInput</em> is <em>null</em>.</exception>
        public int CreateRecord(UnverifiedData userInputData)
        {
            if (userInputData == null)
            {
                throw new ArgumentNullException(nameof(userInputData));
            }

            this.Validator.ValidateParameters(userInputData);

            int id     = this.storedIdentifiers.Count != 0 ? this.storedIdentifiers.Max() + 1 : MinValueOfId;
            var record = new FileCabinetRecord
            {
                Id              = id,
                Name            = new FullName(userInputData.FirstName, userInputData.LastName),
                DateOfBirth     = userInputData.DateOfBirth,
                Sex             = userInputData.Sex,
                NumberOfReviews = userInputData.NumberOfReviews,
                Salary          = userInputData.Salary,
            };

            this.AddRecord(record);
            this.storedIdentifiers.Add(record.Id);
            this.undeletedRecordsCount++;
            return(id);
        }
コード例 #3
0
        /// <summary>
        /// Creates the record.
        /// </summary>
        /// <param name="recordParams">The record parameters.</param>
        /// <returns>The identifier.</returns>
        public int CreateRecord(RecordParams recordParams)
        {
            if (recordParams is null)
            {
                throw new ArgumentNullException($"{nameof(recordParams)} must nit be null");
            }

            this.validator.ValidateCabinetRecord(recordParams);

            FileCabinetRecord record = new FileCabinetRecord
            {
                Id          = ++this.id,
                FirstName   = recordParams.FirstName,
                LastName    = recordParams.LastName,
                DateOfBirth = recordParams.DateOfBirth,
                Department  = recordParams.Department,
                Salary      = recordParams.Salary,
                Class       = recordParams.Class,
            };

            this.list.Add(record);
            this.dictionaryId.Add(record.Id, record);
            AddToDictionary <string, FileCabinetRecord>(this.firstNameDictionary, recordParams.FirstName.ToUpperInvariant(), record);
            AddToDictionary <string, FileCabinetRecord>(this.lastNameDictionary, recordParams.LastName.ToUpperInvariant(), record);
            AddToDictionary <DateTime, FileCabinetRecord>(this.dateOfBirthDictionary, recordParams.DateOfBirth, record);
            return(record.Id);
        }
        /// <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();
        }
コード例 #5
0
 /// <summary>
 /// Метод производящий валидацию всех свойств.
 /// </summary>
 /// <param name="newRecord">Запись, подвергаемая валидации.</param>
 public void ValidateParameters(FileCabinetRecord newRecord)
 {
     foreach (var validator in this.validators)
     {
         validator.ValidateParameters(newRecord);
     }
 }
コード例 #6
0
        /// <summary>
        /// Writes information to xml file.
        /// </summary>
        /// <param name="record">Record to write about.</param>
        /// <returns>Whether operation succeeded.</returns>
        public bool Write(FileCabinetRecord record)
        {
            if (record == null)
            {
                return(false);
            }

            this.writer.WriteStartElement("record");
            this.writer.WriteAttributeString("id", record.Id.ToString(CultureInfo.InvariantCulture));
            this.writer.WriteStartElement("name");
            this.writer.WriteAttributeString("first", record.FirstName);
            this.writer.WriteAttributeString("last", record.LastName);
            this.writer.WriteEndElement();
            this.writer.WriteStartElement("dateOfBirth");
            this.writer.WriteString(record.DateOfBirth.ToString("yyyy-MMM-d", CultureInfo.InvariantCulture));
            this.writer.WriteEndElement();
            this.writer.WriteStartElement("favourite");
            this.writer.WriteAttributeString("number", record.FavouriteNumber.ToString(CultureInfo.InvariantCulture));
            this.writer.WriteAttributeString("character", record.FavouriteCharacter.ToString(CultureInfo.InvariantCulture));
            this.writer.WriteAttributeString("game", record.FavouriteGame);
            this.writer.WriteEndElement();
            this.writer.WriteStartElement("donations");
            this.writer.WriteString(record.Donations.ToString(CultureInfo.InvariantCulture));
            this.writer.WriteEndElement();
            this.writer.WriteEndElement();

            return(true);
        }
        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);
        }
コード例 #8
0
        /// <summary>
        /// This Method implements read records from file in csv-format.
        /// </summary>
        /// <returns>List records.</returns>
        public IList <FileCabinetRecord> ReadAll()
        {
            var list     = new List <FileCabinetRecord>();
            int position = 70;

            this.reader.BaseStream.Seek(position, SeekOrigin.Begin);

            while (this.reader.Peek() > -1)
            {
                string fileString = this.reader.ReadLine();

                var records = fileString.Split(',');

                var record = new FileCabinetRecord()
                {
                    Id            = Convert.ToInt32(records[0], CultureInfo.InvariantCulture),
                    FirstName     = records[1],
                    LastName      = records[2],
                    DateOfBirth   = Convert.ToDateTime(records[3], CultureInfo.InvariantCulture),
                    CabinetNumber = Convert.ToInt16(records[4], CultureInfo.InvariantCulture),
                    Salary        = Convert.ToDecimal(records[5], CultureInfo.InvariantCulture),
                    Category      = Convert.ToChar(records[6], CultureInfo.InvariantCulture),
                };

                list.Add(record);
            }

            return(list);
        }
コード例 #9
0
        private void WriteRecordWithID(BinaryWriter writer, FileCabinetRecord record)
        {
            writer.Write(record.Id);

            var firstName = new char[60];

            for (int i = 0; i < record.FirstName.Length && i < MaxLengthForFirstNameDefault; i++)
            {
                firstName[i] = record.FirstName[i];
            }

            writer.Write(firstName);

            var lastName = new char[60];

            for (int i = 0; i < record.LastName.Length && i < MaxLengthForLastNameDefault; i++)
            {
                lastName[i] = record.LastName[i];
            }

            writer.Write(lastName);

            writer.Write(record.Sex);
            writer.Write(record.DateOfBirth.Day);
            writer.Write(record.DateOfBirth.Month);
            writer.Write(record.DateOfBirth.Year);
            writer.Write(record.Weight);
            writer.Write(record.Balance);
        }
コード例 #10
0
        /// <summary>
        /// Adds record to the list of records.
        /// </summary>
        /// <param name="record">Record to add.</param>
        /// <returns>Record's id.</returns>
        public int AddRecord(FileCabinetRecord record)
        {
            if (record == null)
            {
                throw new ArgumentNullException($"Record object is invalid.");
            }

            string exceptionMessage = this.validator.Validate(record);

            if (exceptionMessage != null)
            {
                return(-1);
            }

            if (this.ids.Contains(record.Id))
            {
                int indexOfPrev = this.list.FindIndex(rec => rec.Id.Equals(record.Id));

                this.RemoveFromDictionary(indexOfPrev);

                this.list[indexOfPrev] = record;
            }
            else
            {
                this.list.Add(record);
                this.ids.Add(record.Id);
            }

            this.UpdateDictionaries(record);
            this.PurgeCache(record);

            return(record.Id);
        }
コード例 #11
0
        /// <summary>
        /// Редактирование записи в списке.
        /// </summary>
        /// <param name="newRecord">Новые параметры записи.</param>
        public void EditRecord(FileCabinetRecord newRecord)
        {
            if (newRecord == null)
            {
                throw new Exception();
            }

            this.validator.ValidateParameters(newRecord);
            FileCabinetRecord current = this.list.Find(x => x.Id == newRecord.Id);

            if (current == null)
            {
                throw new ArgumentException($"No element with id = {newRecord.Id}");
            }

            string prevFirstName = current.FirstName;
            string prevLastName  = current.LastName;
            string prevDoB       = current.DateOfBirth.ToShortDateString();

            current.FirstName        = newRecord.FirstName;
            current.LastName         = newRecord.LastName;
            current.DateOfBirth      = newRecord.DateOfBirth;
            current.Wage             = newRecord.Wage;
            current.FavouriteNumeral = newRecord.FavouriteNumeral;
            current.Height           = newRecord.Height;
            this.EditNoteAtDictionary(this.firstNameDictionary, newRecord.FirstName, newRecord.Id, current, prevFirstName);
            this.EditNoteAtDictionary(this.lastNameDictionary, newRecord.LastName, newRecord.Id, current, prevLastName);
            this.EditNoteAtDictionary(this.dateOfBirthDictionary, newRecord.DateOfBirth.ToShortDateString(), newRecord.Id, current, prevDoB);

            Console.WriteLine($"Record #{newRecord.Id} is updated.");
        }
コード例 #12
0
        private void AddRecord(FileCabinetRecord record)
        {
            if (record == null)
            {
                throw new ArgumentNullException(nameof(record));
            }

            this.storedIdentifiers.Add(record.Id);

            this.list.Add(record);

            string firstNameKey = record.Name.FirstName.ToUpperInvariant();

            if (!this.firstNameDictionary.ContainsKey(firstNameKey))
            {
                this.firstNameDictionary.Add(firstNameKey, new List <FileCabinetRecord>());
            }

            this.firstNameDictionary[firstNameKey].Add(record);
            string lastNameKey = record.Name.LastName.ToUpperInvariant();

            if (!this.lastNameDictionary.ContainsKey(lastNameKey))
            {
                this.lastNameDictionary.Add(lastNameKey, new List <FileCabinetRecord>());
            }

            this.lastNameDictionary[lastNameKey].Add(record);

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

            this.dateOfBirthDictionary[record.DateOfBirth].Add(record);
        }
コード例 #13
0
        /// <summary>
        /// Inserts the specified record.
        /// </summary>
        /// <param name="record">The record.</param>
        /// <exception cref="ArgumentNullException">Throws when record is null.</exception>
        /// <exception cref="ArgumentException">
        /// Record id must be more than zero
        /// or
        /// Such identifier already exists.
        /// </exception>
        public void Insert(FileCabinetRecord record)
        {
            if (record is null)
            {
                throw new ArgumentNullException(nameof(record));
            }

            if (record.Id == -1)
            {
                throw new ArgumentException($"Record id must be more than zero");
            }

            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
            {
                throw new ArgumentException("Such identifier already exists.");
            }
        }
コード例 #14
0
        /// <summary>
        /// Получение всех импортируемых записей.
        /// </summary>
        /// <returns>Список импортированных записей.</returns>
        public IList <FileCabinetRecord> ReadAll()
        {
            List <FileCabinetRecord> records = new List <FileCabinetRecord>();

            using (this.reader)
            {
                var line = this.reader.ReadLine();
                while (this.reader.EndOfStream != true)
                {
                    FileCabinetRecord record = new FileCabinetRecord();
                    line = this.reader.ReadLine();
                    var cells = line.Split(',');
                    record.Id               = int.Parse(cells[0], CultureInfo.InvariantCulture);
                    record.FirstName        = cells[1];
                    record.LastName         = cells[2];
                    record.DateOfBirth      = DateTime.Parse(cells[3], CultureInfo.CurrentCulture);
                    record.Wage             = decimal.Parse(cells[4], CultureInfo.InvariantCulture);
                    record.Height           = short.Parse(cells[5], CultureInfo.InvariantCulture);
                    record.FavouriteNumeral = char.Parse(cells[6]);
                    records.Add(record);
                }
            }

            return(records);
        }
コード例 #15
0
 /// <summary>
 /// Adds a record to the dictionary by key <paramref name="id"/>.
 /// </summary>
 /// <param name="id">Input key.</param>
 /// <param name="record">Input record.</param>
 public void AddInDictionaryId(int id, FileCabinetRecord record)
 {
     if (!this.idrecordDictionary.ContainsKey(id))
     {
         this.idrecordDictionary[id] = record;
     }
 }
コード例 #16
0
        /// <summary>
        /// Writes information to csv file.
        /// </summary>
        /// <param name="record">Record to write about.</param>
        /// <returns>Whether operation succeeded.</returns>
        public bool Write(FileCabinetRecord record)
        {
            if (record == null)
            {
                return(false);
            }

            PropertyInfo[] properties = record.GetType().GetProperties();

            for (int i = 0; i < properties.Length; i++)
            {
                if (properties[i].PropertyType == typeof(DateTime))
                {
                    DateTime date = (DateTime)properties[i].GetValue(record);
                    this.writer.Write(date.ToString("yyyy-MMM-d", CultureInfo.InvariantCulture));
                }
                else
                {
                    this.writer.Write(properties[i].GetValue(record));
                }

                if (i != properties.Length - 1)
                {
                    this.writer.Write(',');
                }
            }

            this.writer.Write("\n");
            return(true);
        }
コード例 #17
0
        /// <summary>
        /// Changing data in an existing record.
        /// </summary>
        /// <param name="id">Id of the record to edit.</param>
        /// <param name="parameters">Input new FirstName, LastName, DateOfBirth, Gender, Salary, Age.</param>
        public void EditRecord(int id, FileCabinetServiceContext parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            using (var file = File.Open(this.fileStream.Name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                this.contextStrategy.ValidateParameters(parameters);
                byte[] recordBuffer = new byte[file.Length];
                file.Read(recordBuffer, 0, recordBuffer.Length);

                this.list = recordBuffer.ToListFileCabinetRecord();
                var updateRecord            = this.list.Find(record => record.Id == id);
                FileCabinetRecord oldrecord = updateRecord;
                var positionInFile          = this.GetPositionInFileById(oldrecord.Id);
                this.RemoveRecordInAllDictionary(oldrecord, positionInFile);
                updateRecord.Id          = id;
                updateRecord.Age         = parameters.Age;
                updateRecord.Salary      = parameters.Salary;
                updateRecord.Gender      = parameters.Gender;
                updateRecord.FirstName   = parameters.FirstName;
                updateRecord.LastName    = parameters.LastName;
                updateRecord.DateOfBirth = parameters.DateOfBirth;
                this.AddRecordInAllDictionary(updateRecord, positionInFile);
                this.FileCabinetRecordToBytes(updateRecord);
            }
        }
コード例 #18
0
        /// <summary>
        /// Create record with the specified id.
        /// </summary>
        /// <param name="parameters">Input parameters.</param>
        /// <param name="id">Input id record.</param>
        /// <returns>Id of the created record.</returns>
        public int Create(FileCabinetServiceContext parameters, int id)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            this.contextStrategy.ValidateParameters(parameters);

            var record = new FileCabinetRecord
            {
                Id          = id,
                FirstName   = parameters.FirstName,
                LastName    = parameters.LastName,
                DateOfBirth = parameters.DateOfBirth,
                Gender      = parameters.Gender,
                Age         = parameters.Age,
                Salary      = parameters.Salary,
            };

            this.AddRecordInAllDictionary(record);
            this.list.Add(record);
            this.list = this.list.OrderBy(x => x.Id).ToList();
            return(record.Id);
        }
コード例 #19
0
        /// <summary>Gets the records.</summary>
        /// <returns>Returns a read-only collection  of records.</returns>
        public ReadOnlyCollection <FileCabinetRecord> GetRecords()
        {
            this.fileStream.Seek(BeginOfFile, SeekOrigin.Begin);
            using var reader = new BinaryReader(this.fileStream, Encoding.Unicode, true);
            var   records = new List <FileCabinetRecord>();
            short reservedField;

            while (reader.PeekChar() > -1)
            {
                reservedField = reader.ReadInt16();
                if ((reservedField & DeletedBitMask) == DeletedBitMask)
                {
                    this.fileStream.Seek(RecordLenghtInBytes - sizeof(short), SeekOrigin.Current);
                    continue;
                }

                var record = new FileCabinetRecord
                {
                    Id              = reader.ReadInt32(),
                    Name            = new FullName(new string(reader.ReadChars(MaxFirstNameLength)).Trim(NullCharacter), new string(reader.ReadChars(MaxLastNameLength)).Trim(NullCharacter)),
                    DateOfBirth     = new DateTime(reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32()),
                    Sex             = reader.ReadChar(),
                    NumberOfReviews = reader.ReadInt16(),
                    Salary          = reader.ReadDecimal(),
                };

                records.Add(record);
            }

            return(new ReadOnlyCollection <FileCabinetRecord>(records));
        }
コード例 #20
0
        private void Delete(string parameters)
        {
            if (parameters is null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            Dictionary <string, string> where = QueryParser.DeleteParser(parameters);

            if (where != null)
            {
                FileCabinetRecord whereRecord = DataHelper.CreateRecordFromDict(where);

                var records = this.Service.FindRecords(whereRecord, QueryParser.TypeCondition);

                var builder             = new StringBuilder();
                int countMatchedRecords = 0;
                foreach (var item in records)
                {
                    builder.Append($"#{item.Id}, ");
                    countMatchedRecords++;
                }

                string text = countMatchedRecords == 0
                    ? $"No deleted records."
                    : $"{(countMatchedRecords == 1 ? "Record" : "Records")} " +
                              $"{builder.ToString().TrimEnd(WhiteSpace, Comma)} " +
                              $"{(countMatchedRecords == 1 ? "is" : "are")} deleted.";

                this.Service.Delete(records);
                Memoization.RefreshMemoization();
                Console.WriteLine(text);
            }
        }
コード例 #21
0
 public void Write(FileCabinetRecord record)
 {
     document.Root.Add(new XElement("record", new XAttribute("id", record.Id),
                                    new XElement("dateOfBirth", record.DateOfBirth.ToString("yyyy-MMM-dd", new CultureInfo("en-US"))),
                                    new XElement("age", record.Age),
                                    new XElement("money", record.Money),
                                    new XElement("letter", record.Letter)));
 }
コード例 #22
0
        /// <inheritdoc/>
        public IEnumerable <FileCabinetRecord> FindRecords(FileCabinetRecord predicate, string type)
        {
            this.Print(nameof(this.FindRecords), string.Empty);
            IEnumerable <FileCabinetRecord> value = this.fileCabinetService.FindRecords(predicate, type);

            this.Print(nameof(this.FindRecords), $"{(value == null ? string.Empty : value.GetType().Name)}");
            return(value);
        }
コード例 #23
0
        /// <inheritdoc/>
        public void Write(FileCabinetRecord record)
        {
            if (record is null)
            {
                throw new ArgumentNullException(nameof(record));
            }

            this.writer.WriteLine(record.ToString());
        }
コード例 #24
0
        /// <inheritdoc/>
        public IEnumerable <FileCabinetRecord> FindRecords(FileCabinetRecord predicate, string type)
        {
            this.stopwatch.Restart();
            var value = this.fileCabinetService.FindRecords(predicate, type);

            this.stopwatch.Stop();
            Print(nameof(this.FindRecords), this.stopwatch.ElapsedTicks);
            return(value);
        }
コード例 #25
0
        /// <inheritdoc/>
        public void EditRecord(FileCabinetRecord record)
        {
            this.stopwatch = Stopwatch.StartNew();

            this.fileCabinetService.EditRecord(record);

            this.stopwatch.Stop();
            Console.WriteLine($"Edit method execution is {this.stopwatch.ElapsedTicks} ticks.");
        }
コード例 #26
0
ファイル: ServiceMeter.cs プロジェクト: ZaahKing/file-cabinet
 /// <inheritdoc/>
 public void InsertRecord(FileCabinetRecord record)
 {
     Measure(
         "Insert method execution duration is {0} ticks.",
         () =>
     {
         this.service.InsertRecord(record);
     });
 }
コード例 #27
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.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}");
                }
            }
        }
コード例 #28
0
        // TODO : Refator method
        public void EditRecord(int id, FileCabinetRecord newRecord)
        {
            int i = 0;

            while (i < fileStream.Length)
            {
                fileStream.Position = i + 2;
                byte[] idBytes = new byte[4];
                fileStream.Read(idBytes, 0, idBytes.Length);

                if (id == Convert.ToInt32(Encoding.Default.GetString(idBytes)))
                {
                    fileStream.Position = i + 6;
                    byte[] firstNameBytes = new byte[120];
                    Encoding.Default.GetBytes(newRecord.FirstName).CopyTo(firstNameBytes, 0);
                    fileStream.Write(firstNameBytes, 0, firstNameBytes.Length);

                    fileStream.Position = i + 126;
                    byte[] lastNameBytes = new byte[120];
                    Encoding.Default.GetBytes(newRecord.LastName).CopyTo(lastNameBytes, 0);
                    fileStream.Write(lastNameBytes, 0, lastNameBytes.Length);

                    fileStream.Position = i + 246;
                    byte[] yearBytes = new byte[4];
                    Encoding.Default.GetBytes(newRecord.DateOfBirth.Year.ToString()).CopyTo(yearBytes, 0);
                    fileStream.Write(yearBytes, 0, yearBytes.Length);

                    fileStream.Position = i + 250;
                    byte[] monthBytes = new byte[4];
                    Encoding.Default.GetBytes(newRecord.DateOfBirth.Month.ToString()).CopyTo(monthBytes, 0);
                    fileStream.Write(monthBytes, 0, monthBytes.Length);

                    fileStream.Position = i + 254;
                    byte[] dayBytes = new byte[4];
                    Encoding.Default.GetBytes(newRecord.DateOfBirth.Day.ToString()).CopyTo(dayBytes, 0);
                    fileStream.Write(dayBytes, 0, dayBytes.Length);

                    fileStream.Position = i + 258;
                    byte[] ageBytes = new byte[2];
                    Encoding.Default.GetBytes(newRecord.Age.ToString()).CopyTo(ageBytes, 0);
                    fileStream.Write(ageBytes, 0, ageBytes.Length);

                    fileStream.Position = i + 260;
                    byte[] moneyBytes = new byte[16];
                    Encoding.Default.GetBytes(newRecord.Money.ToString()).CopyTo(moneyBytes, 0);
                    fileStream.Write(moneyBytes, 0, moneyBytes.Length);

                    fileStream.Position = i + 276;
                    byte[] letterBytes = new byte[1];
                    Encoding.Default.GetBytes(newRecord.Letter.ToString()).CopyTo(letterBytes, 0);
                    fileStream.Write(letterBytes, 0, letterBytes.Length);
                }

                i += 277;
            }
        }
コード例 #29
0
        /// <summary>
        /// Method get data and create record.
        /// </summary>
        /// <param name="inputData">input data.</param>
        /// <returns>id of new record.</returns>
        public int CreateRecord(FileCabinetInputData inputData)
        {
            if (inputData is null)
            {
                throw new ArgumentNullException(nameof(inputData), "must not be null");
            }

            this.Validator.ValidateParameters(inputData);
            var record = new FileCabinetRecord
            {
                Id          = this.list.Count + 1,
                FirstName   = inputData.FirstName,
                LastName    = inputData.LastName,
                DateOfBirth = inputData.DateOfBirth,
                Gender      = inputData.Gender,
                Experience  = inputData.Experience,
                Account     = inputData.Account,
            };

            this.list.Add(record);

            if (this.firstNameDictionary.ContainsKey(record.FirstName.ToUpper(CultureInfo.InvariantCulture)))
            {
                this.firstNameDictionary[record.FirstName.ToUpper(CultureInfo.InvariantCulture)].Add(record);
            }
            else
            {
                this.firstNameDictionary.Add(record.FirstName.ToUpper(CultureInfo.InvariantCulture), new List <FileCabinetRecord> {
                    record
                });
            }

            if (this.lastNameDictionary.ContainsKey(record.LastName.ToUpper(CultureInfo.InvariantCulture)))
            {
                this.lastNameDictionary[record.LastName.ToUpper(CultureInfo.InvariantCulture)].Add(record);
            }
            else
            {
                this.lastNameDictionary.Add(record.LastName.ToUpper(CultureInfo.InvariantCulture), new List <FileCabinetRecord> {
                    record
                });
            }

            if (this.dateOfBirthDictionary.ContainsKey(record.DateOfBirth))
            {
                this.dateOfBirthDictionary[record.DateOfBirth].Add(record);
            }
            else
            {
                this.dateOfBirthDictionary.Add(record.DateOfBirth, new List <FileCabinetRecord> {
                    record
                });
            }

            return(record.Id);
        }
コード例 #30
0
        /// <summary>
        /// Adds timing count for edit method.
        /// </summary>
        /// <param name="record">Record to edit.</param>
        /// <returns>Whether operation succeeded.</returns>
        public int EditRecord(FileCabinetRecord record)
        {
            this.watch = Stopwatch.StartNew();
            int id = this.service.EditRecord(record);

            this.watch.Stop();
            Console.WriteLine($"Edit method execution duration is " + this.watch.ElapsedTicks + " ticks.");

            return(id);
        }