// The ADIF file format stores its times in UTC. We will leave any conversion to the parent program. DateTime GetTimeFromRecord(_Field record) { if (record._header.Length != 6 && record._header.Length != 4) { return(new DateTime()); } string temp = string.Empty; int hours = 0; int minutes = 0; int seconds = 0; hours = Convert.ToInt32(record._data.Substring(0, 2)); minutes = Convert.ToInt32(record._data.Substring(2, 2)); if (record._data.Length == 6) { seconds = Convert.ToInt32(record._data.Substring(4, 2)); } // The time and date are stored separately. So we will set the date here to 1/1/1500. // This date is such so we can know if the date needs to be updated when merging the // date and time. return(new DateTime(1500, 1, 1, hours, minutes, seconds, DateTimeKind.Utc)); }
// General line parser. private List <_Field> ParseLine(string line) { string sub = string.Empty; int index = 0; _Field record = new _Field(); List <_Field> results = new List <_Field>(); // Multiple fields can be on one line. Thus we must make sure all are accounted for. while (line.IndexOf("<", index) != -1 && line.IndexOf(">", index) != -1) { // Separate and pass just the header. record._header = ParseFieldHeader(line.Substring(index, (line.IndexOf(">", index) - index) + 1)); // Separate and pass the field. record._data = GetFieldDataFromWithHeader(record._header, line.Substring(index, (line.IndexOf(">", index) - index) + record._header.Length + 1)); // Place record in a list in case there are multiple per line. results.Add(record); // Keep the index upto date on what has been parsed. index = line.IndexOf(">", index) + record._header.Length + 1; } return(results); }
// The ADIF file format stores its date with respect to the UTC time. private DateTime GetDateFromRecord(_Field record) { if (record._header.Length != 8) { return(new DateTime()); } int year = 0; int month = 0; int day = 0; year = Convert.ToInt32(record._data.Substring(0, 4)); month = Convert.ToInt32(record._data.Substring(4, 2)); day = Convert.ToInt32(record._data.Substring(6, 2)); return(new DateTime(year, month, day)); }
/// <summary> /// Сохранить поле. /// </summary> /// <param name="field">Поле.</param> /// <param name="currentUserId">Идентификатор текущего пользователя.</param> /// <returns>Поле.</returns> public _FieldBase Save(_FieldBase field, int currentUserId) { { Argument.Require(currentUserId != 0, "Текущий пользователь не определен."); Argument.Require(field != null, "Поле пустое."); Argument.Require(field._EntityId > 0, "Идентификатор сущности пустой."); using (var uow = this.CreateAdminUnitOfWork()) { if (field.IsIdentity) { List <_Field> entityFields = uow._FieldRepository.Query(entityId: field._EntityId); _Field identity = entityFields.FirstOrDefault(f => f.IsIdentity); Argument.Require(identity == null || identity.Id == field.Id, $"У сущности должно быть единственное поле-идентификатор. " + $"В сущности \"{identity._EntityName}\" поле-идентификатор \"{identity.Name}\"."); } return(uow._FieldRepository.Save(field)); } } }
public _GenericEntity GetEntityById(int entityId, int entityInstanceId) { Argument.Require(entityId > 0, "Идентификатор сущности пустой."); Argument.Require(entityInstanceId > 0, "Идентификатор экземпляра сущности пустой."); using (var uow = this.CreateAdminUnitOfWork()) { List <_Field> fields = uow._FieldRepository.Query(entityId: entityId); _Field identityField = fields.FirstOrDefault(f => f.IsIdentity); Argument.Require(identityField != null, "В сущности не найдено поле-идентификатор."); return(this.GetEntitiesList( _entityId: entityId, pageSize: 1, filters: new List <_GenericEntityFieldFilter>() { new _GenericEntityFieldFilter() { _FieldId = identityField.Id, Value = entityInstanceId.ToString() } }) .FirstOrDefault()); } }
// The ADIF file format stores its date with respect to the UTC time. private DateTime GetDateFromRecord(_Field record) { if (record._header.Length != 8) return new DateTime(); int year = 0; int month = 0; int day = 0; year = Convert.ToInt32(record._data.Substring(0, 4)); month = Convert.ToInt32(record._data.Substring(4, 2)); day = Convert.ToInt32(record._data.Substring(6, 2)); return new DateTime(year, month, day); }
// General line parser. private List<_Field> ParseLine(string line) { string sub = string.Empty; int index = 0; _Field record = new _Field(); List<_Field> results = new List<_Field>(); // Multiple fields can be on one line. Thus we must make sure all are accounted for. while (line.IndexOf("<", index) != -1 && line.IndexOf(">", index) != -1) { // Separate and pass just the header. record._header = ParseFieldHeader(line.Substring(index, (line.IndexOf(">", index) - index) + 1)); // Separate and pass the field. record._data = GetFieldDataFromWithHeader(record._header, line.Substring(index, (line.IndexOf(">", index) - index) + record._header.Length + 1)); // Place record in a list in case there are multiple per line. results.Add(record); // Keep the index upto date on what has been parsed. index = line.IndexOf(">", index) + record._header.Length + 1; } return results; }
// The ADIF file format stores its times in UTC. We will leave any conversion to the parent program. DateTime GetTimeFromRecord(_Field record) { if (record._header.Length != 6 && record._header.Length != 4) return new DateTime(); string temp = string.Empty; int hours = 0; int minutes = 0; int seconds = 0; hours = Convert.ToInt32(record._data.Substring(0, 2)); minutes = Convert.ToInt32(record._data.Substring(2, 2)); if (record._data.Length == 6) seconds = Convert.ToInt32(record._data.Substring(4, 2)); // The time and date are stored separately. So we will set the date here to 1/1/1500. // This date is such so we can know if the date needs to be updated when merging the // date and time. return new DateTime(1500, 1, 1, hours, minutes, seconds, DateTimeKind.Utc); }
/// <summary> /// Получить список экземпляров сущности. /// </summary> /// <param name="_entityId">Идентификатор сущности.</param> /// <param name="sort_FieldId">Идентификатор поля для сортировки.</param> /// <param name="sortDirection">Идентификатор направления сортировки.</param> /// <param name="filters">Фильтры.</param> /// <param name="pageSize">Размер страницы.</param> /// <param name="pageNumber">Номер страницы.</param> /// <returns>Список обобщенных сущностей.</returns> public List <_GenericEntity> GetEntitiesList( int _entityId, int?sort_FieldId = null, SortDirections sortDirection = SortDirections.Ascending, List <_GenericEntityFieldFilter> filters = null, int pageSize = 1000, int pageNumber = 0) { using (var uow = this.CreateAdminUnitOfWork()) { _Entity entity = uow._EntityRepository.GetById(_entityId); List <_Field> fields = uow._FieldRepository.Query(entityId: _entityId); _Field sortField = fields.FirstOrDefault(f => f.Id == sort_FieldId) ?? fields.First(); IEnumerable <string> selectList = fields.Select(f => { switch (f._FieldTypeId) { case (int)_FieldTypes.Integer: case (int)_FieldTypes.Decimal: return($"CAST({f.DatabaseName} AS TEXT) AS f_{f.Id}"); case (int)_FieldTypes.DateTime: return($"TO_CHAR({f.DatabaseName}, '{SQL_DATE_TIME_FORMAT}') AS f_{f.Id}"); default: return($"{f.DatabaseName} AS f_{f.Id}"); } }); filters = filters ?? new List <_GenericEntityFieldFilter>(); IEnumerable <string> filterList = filters.Select(f => { var field = fields.FirstOrDefault(x => x.Id == f._FieldId); Argument.Require(field != null, "Не найдено поле сущности для фильтра."); object deserializedValue = _DeserializeField(f.Value, field._FieldTypeId); string sqlValue = _ToSqlField(deserializedValue, field._FieldTypeId); return($"{field.DatabaseName} = {sqlValue}"); }); string query = $"SELECT " + $"{Environment.NewLine}{string.Join($"{Environment.NewLine}, ", selectList)} " + $"{Environment.NewLine}FROM {entity.DatabaseScheme}.\"{entity.DatabaseName}\" " + (!filterList.Any() ? "" : $"{Environment.NewLine}WHERE {string.Join($"{Environment.NewLine} AND ", filterList)} ") + $"{Environment.NewLine}ORDER BY {sortField.DatabaseName} {sortDirection.GetDescription()} " + $"{Environment.NewLine}OFFSET {pageNumber} * {pageSize} LIMIT {pageSize};"; List <_GenericEntity> result = uow._DynamicRepository.Sql(query) .Select(e => { var ent = new _GenericEntity() { EntityId = _entityId }; ent.Fields = e .Select(f => { var fieldId = Int32.Parse(f.Key.Replace("f_", "")); var field = fields.FirstOrDefault(x => x.Id == fieldId); return(new _GenericEntityField() { FieldId = fieldId, _FieldTypeId = field._FieldTypeId, Value = f.Value as string }); }) .ToList(); return(ent); }) .ToList(); return(result); } }
public int SaveEntity(_GenericEntity genericEntity, int userId) { Argument.Require(genericEntity != null, "Сущность пустая."); Argument.Require(userId > 0, "Идентификатор пользователя пустой."); Argument.Require(genericEntity.EntityId > 0, "Идентификатор сущности пустой."); using (var uow = this.CreateAdminUnitOfWork()) { _Entity entity = uow._EntityRepository.GetById(genericEntity.EntityId); Argument.Require(entity != null, "Сущность не найдена."); List <_Field> fields = uow._FieldRepository.Query(entityId: entity.Id); _Field identityField = fields.FirstOrDefault(f => f.IsIdentity); Argument.Require(identityField != null, "В сущности не найдено поле-идентификатор."); var identityFieldWithValue = genericEntity.Fields.FirstOrDefault(e => e.FieldId == identityField.Id); Argument.Require(identityFieldWithValue != null, "Не найдено значение поля-идентификатора в сохраняемых данных."); bool isEdit = !string.IsNullOrWhiteSpace(identityFieldWithValue.Value) && Int32.TryParse(identityFieldWithValue.Value, out int id) && id != 0; if (isEdit) { _GenericEntity existingEntityInstance = this.GetEntitiesList( _entityId: entity.Id, filters: new List <_GenericEntityFieldFilter>() { new _GenericEntityFieldFilter() { _FieldId = identityField.Id, Value = identityFieldWithValue.Value } }, pageSize: 1).FirstOrDefault(); Argument.Require(existingEntityInstance != null, "Обновляемая сущность не найдена."); } Dictionary <int, string> fieldSqlValues = new Dictionary <int, string>(); foreach (var field in fields) { _GenericEntityField fieldWithValue = genericEntity.Fields.FirstOrDefault(x => x.FieldId == field.Id); object deserializedValue = _DeserializeField(fieldWithValue?.Value, field._FieldTypeId); string sqlValue = _ToSqlField(deserializedValue, field._FieldTypeId); fieldSqlValues[field.Id] = sqlValue; } string fieldNames = string.Join($"{Environment.NewLine}, ", fields.Where(f => !f.IsIdentity).Select(f => f.DatabaseName)); string fieldValues = string.Join($"{Environment.NewLine}, ", fields.Where(f => !f.IsIdentity).Select(f => fieldSqlValues[f.Id])); string upsertQuery = null; if (isEdit) { upsertQuery = $"UPDATE {entity.DatabaseScheme}.\"{entity.DatabaseName}\" " + "SET (" + $"{Environment.NewLine}{fieldNames}" + ")" + $"{Environment.NewLine}= ({fieldValues})" + $"{Environment.NewLine}WHERE {identityField.DatabaseName} = {fieldSqlValues[identityField.Id]};"; } else { upsertQuery = $"INSERT INTO {entity.DatabaseScheme}.\"{entity.DatabaseName}\" " + $"{Environment.NewLine}(" + $"{Environment.NewLine}{fieldNames}" + $"{Environment.NewLine}) VALUES (" + $"{Environment.NewLine}{fieldValues}" + $"{Environment.NewLine}) " + $"{Environment.NewLine}RETURNING {identityField.DatabaseName};"; } var result = uow._DynamicRepository.Sql(upsertQuery); var resultRow = result.FirstOrDefault(); if (resultRow == null || resultRow.Values.Count == 0) { return(0); } int newId = (result.FirstOrDefault().Values.FirstOrDefault() as int?) ?? 0; return(newId); } }