Ejemplo n.º 1
0
 private void CommitTransaction()
 {
     try
     {
         _transaction.Commit();
         _transaction.Dispose();
     }
     catch (GenericADOException exception)
     {
         TransactionException transactionException = TransactionalExceptionAbstractFactory.GetException(exception);
         Log.Warn(transactionException);
         RollBackTransactionAndSetDisposedToTrue();
         Log.Warn("Transaction has been rollbacked correctly");
         throw transactionException;
     }
     catch (PropertyValueException ex)
     {
         var exceptionToThrow = new RepositoryException(ex.Message, ex);
         Log.Warn(exceptionToThrow, "Missing required property");
         _transaction.Rollback();
         throw exceptionToThrow;
     }
     catch (Exception exception)
     {
         _transaction.Rollback();
         Log.Error(exception, "An unknow exception has been throw during UnitOfWork disposing.");
         throw;
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Insert entities
        /// </summary>
        /// <param name="entities">Entities</param>
        public virtual void Insert(IEnumerable <T> entities)
        {
            try
            {
                if (entities == null)
                {
                    throw new ArgumentNullException("entities");
                }

                foreach (var entity in entities)
                {
                    this.Entities.Add(entity);
                }

                this._context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
                    }
                }

                var fail = new RepositoryException(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }
Ejemplo n.º 3
0
        internal static Exception CacheKeyNotSet(string resourceType)
        {
            RepositoryException exception = new RepositoryException(RepositoryErrorCodes.CacheKeyNotSet);

            exception.Data["ResourceType"] = resourceType;

            return(exception);
        }
Ejemplo n.º 4
0
 private void HandleRepositoryException(RepositoryException repositoryException, ExceptionContext context)
 {
     context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
     context.Result = new JsonResult(new
     {
         Error        = repositoryException.Message,
         ErrorDetails = repositoryException.Errors
     });
 }
        public void Constructor_1_OK()
        {
            // Arrange:

            // Act:
            var ex1 = new RepositoryException("test");

            // Assert:
        }
        public void Constructor_0_OK()
        {
            // Arrange:

            // Act:
            var ex0 = new RepositoryException();

            // Assert:
        }
Ejemplo n.º 7
0
        internal static Exception UtcTicksNotSet(string resourceType, string cacheKey, object?cacheValue)
        {
            RepositoryException exception = new RepositoryException(RepositoryErrorCodes.UtcTicksNotSet);

            exception.Data["ResourceType"] = resourceType;
            exception.Data["CacheKey"]     = cacheKey;
            exception.Data["CacheValue"]   = cacheValue;

            return(exception);
        }
Ejemplo n.º 8
0
        private static Task HandleRepositoryExceptionAsync(HttpContext context, RepositoryException exception)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)HttpStatusCode.NotAcceptable;

            return(context.Response.WriteAsync(new ErrorDetails()
            {
                StatusCode = context.Response.StatusCode,
                Message = exception.Message
            }.ToString()));
        }
        public void Constructor_2_OK()
        {
            // Arrange:

            // Act:
            var ex2 =
                new RepositoryException(
                    "test",
                    new Exception());

            // Assert:
        }
Ejemplo n.º 10
0
        public static RepositoryException ToRepositoryException(this SqlException sqlException)
        {
            var repositoryException = new RepositoryException(sqlException.Message, sqlException);

            foreach (SqlError error in sqlException.Errors)
            {
                var text = $"[#{error.Number}] Message: {error.Message}, " +
                           $"LineNumber: {error.LineNumber}, " +
                           $"Source: {error.Source}, " +
                           $"Procedure: {error.Procedure}";
                repositoryException.Errors.Add(text);
            }

            return(repositoryException);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Insert entity
        /// </summary>
        /// <param name="entity">Entity</param>
        public virtual void Insert(T entity)
        {
            try
            {
                if (entity == null)
                {
                    throw new ArgumentNullException("entity");
                }

                this.Entities.Add(entity);

                this._context.SaveChanges();
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException dbUpdEx)
            {
                var fail = new RepositoryException((dbUpdEx.InnerException.InnerException).Message, dbUpdEx.InnerException);
                throw fail;
            }
            catch (DbUnexpectedValidationException ex)
            {
                var fail = new RepositoryException(ex.Message, ex);
                throw fail;
            }
            catch (DbEntityValidationException dbEx)
            {
                var msg = string.Empty;

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
                    }
                }

                var fail = new RepositoryException(msg, dbEx);
                //Debug.WriteLine(fail.Message, fail);
                throw fail;
            }
        }
Ejemplo n.º 12
0
        public void UpdateEpisodeList(
            int podCastId,
            IList <Episode> episodes)
        {
            IQueryable <DBEpisode> oldEpisodes;

            try
            {
                oldEpisodes =
                    this.DB.All <DBEpisode>()
                    .Where(e => e.RefPodCastId == podCastId);
            }
            catch (Exception ex)
            {
                // TODO: EXCEPTION: Unknown SubSonic exception
                throw new RepositoryException(
                          "Error reading existing episode list",
                          ex);
            }

            IList <Exception> exceptions = new List <Exception>();

            foreach (var episode in episodes)
            {
                var oldEpisode =
                    oldEpisodes.Where(
                        e => e.EpisodeId == episode.Id)
                    .SingleOrDefault();
                if (oldEpisode == null)
                {
                    try
                    {
                        // Inserts new episode:
                        this.DB.Add <DBEpisode>(
                            episode.AsDB());
                    }
                    catch (Exception ex)
                    {
                        // TODO: EXCEPTION: Unknown SubSonic exception
                        exceptions.Add(ex);
                    }
                }
                else
                {
                    try
                    {
                        // Updates old episode:
                        this.UpdateDBEpisode(episode, oldEpisode);
                    }
                    catch (RepositoryException ex)
                    {
                        exceptions.Add(ex);
                    }
                }
            }

            if (exceptions.Count > 0)
            {
                string message =
                    string.Format(
                        CultureInfo.CurrentCulture,
                        "Errors during update of episode list: See Data property for all {0} inner exceptions",
                        exceptions.Count);
                var exception =
                    new RepositoryException(
                        message,
                        exceptions.First());
                exception.Data.Add(
                    "Inner exceptions",
                    exceptions);
                throw exception;
            }
        }
Ejemplo n.º 13
0
 public LCServiceException(string message, RepositoryException exc)
     : base(message, exc)
 {
     ExceptionStrings = new List <string>();
     ExceptionStrings = exc.ExceptionStrings;
 }
Ejemplo n.º 14
0
 internal Task LogAsync(RepositoryException e)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 15
0
        public async Task <SettingsDto> GetActiveDto(string deviceId)
        {
            var settings = new SettingsDto();

            var activeProfile = await Db.Profiles.Where(x => x.User.DeviceId == deviceId && x.Active).SingleOrDefaultAsync();

            if (activeProfile == null)
            {
                var device = await Db.Devices.Where(x => x.Id == deviceId).SingleOrDefaultAsync();

                if (device.CenterDeviceId != null)
                {
                    throw RepositoryException.NotCenterDevice(deviceId);
                }

                var profiles = await Db.Profiles.Where(x => x.User.DeviceId == deviceId).ToListAsync();

                if (profiles.Any())
                {
                    // profiles exist but none of them is active | make active one of them ( ???? )
                    activeProfile        = profiles.FirstOrDefault();
                    activeProfile.Active = true;
                    await Db.SaveChangesAsync();
                }
                else
                {
                    // profiles not exist create default profiles for first time use
                    await CreateDefaultProfiles(deviceId);
                }
            }

            settings.Guid = await GetGuid(deviceId);

            settings.ProfileName = activeProfile.Name;
            settings.Mode        = ProfileType.GetName(activeProfile.TypeId);

            if (activeProfile.TypeId == ProfileType.MODE_AUTO_PROFILE_ID)
            {
                var locationId = await Db.Locations.Where(x => x.DeviceId == deviceId && x.Active).Select(x => x.Id).SingleOrDefaultAsync();

                var minTempValue = await Db.MinTemperatures.Where(x => x.LocationId == locationId && x.ProfileId == activeProfile.Id).SingleOrDefaultAsync();

                if (minTempValue == null)
                {
                    throw new RepositoryException($"{locationId} id'li Location'ın default MinTemp bilgisi bulunamadı.");
                }

                settings.MinTemperature = minTempValue.Value;
            }
            else if (activeProfile.TypeId == ProfileType.MODE_MANUAL_ID)
            {
                settings.State = await stateRepository.Get(deviceId);
            }
            else if (activeProfile.TypeId == ProfileType.MODE_AUTO_SERVER_PROFILE_ID)
            {
                var minTemp = await Db.MinTemperatures.Where(x => x.ProfileId == activeProfile.Id).SingleOrDefaultAsync(); // location bilinmediği için locationId verilmeden sorgulanıyor

                if (minTemp == null)
                {
                    throw new RepositoryException($"{activeProfile.Id} id'li Profile'ın MinTemp bilgisi bulunamadı.");
                }

                var latestWeather = await weatherRepository.GetLastMinutes(minTemp.LocationId, 30);

                if (latestWeather == null || latestWeather.Count == 0)
                {
                    settings.State = true;
                }
                else
                {
                    var     weathers       = latestWeather.Take(2).ToList();
                    var     averageWeather = weathers.Sum(x => x.Temperature) / (double)weathers.Count();
                    decimal difference     = (decimal)averageWeather - (decimal)minTemp.Value;
                    if (difference <= -0.1m)
                    {
                        settings.State = true;
                    }
                    else if (difference >= 0.12m)
                    {
                        settings.State = false;
                    }
                    else
                    {
                        settings.State = true;
                    }
                }
            }
            else if (activeProfile.TypeId == ProfileType.MODE_AUTO_PROFILE_SCHEDULED_1_ID)
            {
                // todo: fix it
                settings.ProfileDtos = await profileRepository.GetDtos(deviceId);

                settings.ProfilePreferenceDtos = await profileRepository.GetProfilePreferenceDtos(activeProfile.Id);
            }
            else if (activeProfile.TypeId == ProfileType.MODE_AUTO_SCHEDULED_1_ID)
            {
                // todo: fix it
                var locationId = await Db.Locations.Where(x => x.DeviceId == deviceId && x.Active).Select(x => x.Id).SingleOrDefaultAsync();

                settings.MinTemperatureDtos = await Db.MinTemperatures.Where(x => x.LocationId == locationId && x.ProfileId == activeProfile.Id).Select(x => new MinTemperatureDto()
                {
                    Value = x.Value
                }).ToListAsync();
            }

            return(settings);
        }
Ejemplo n.º 16
0
 internal Task LogAsync(RepositoryException e)
 {
     //Dummy code
     return(null);
 }