Esempio n. 1
0
        public async Task <CourseDetailViewModel> EditCourseAsync(CourseEditInputModel inputModel)
        {
            DataSet dataSet = await db.QueryAsync($"SELECT COUNT(*) FROM Courses WHERE Id={inputModel.Id}");

            if (Convert.ToInt32(dataSet.Tables[0].Rows[0][0]) == 0)
            {
                throw new CourseNotFoundException(inputModel.Id);
            }

            try
            {
                dataSet = await db.QueryAsync($"UPDATE Courses SET Title={inputModel.Title}, Description={inputModel.Description}, Email={inputModel.Email}, CurrentPrice_Currency={inputModel.CurrentPrice.Currency}, CurrentPrice_Amount={inputModel.CurrentPrice.Amount}, FullPrice_Currency={inputModel.FullPrice.Currency}, FullPrice_Amount={inputModel.FullPrice.Amount} WHERE Id={inputModel.Id}");
            }
            catch (SqliteException exc) when(exc.SqliteErrorCode == 19)
            {
                throw new CourseTitleUnavailableException(inputModel.Title, exc);
            }

            if (inputModel.Image != null)
            {
                try {
                    string imagePath = await imagePersister.SaveCourseImageAsync(inputModel.Id, inputModel.Image);

                    dataSet = await db.QueryAsync($"UPDATE Courses SET ImagePath={imagePath} WHERE Id={inputModel.Id}");
                }
                catch (Exception exc)
                {
                    throw new CourseImageInvalidException(inputModel.Id, exc);
                }
            }

            CourseDetailViewModel course = await GetCourseAsync(inputModel.Id);

            return(course);
        }
Esempio n. 2
0
        public async Task <CourseDetailViewModel> EditCourseAsync(CourseEditInputModel inputModel)
        {
            //Recupero dell'entità Course
            //FindAsync: specializzato con le chiavi primarie, gli fornisco l'id
            Course course = await dbContext.Courses.FindAsync(inputModel.Id);

            if (course == null)
            {
                throw new CourseNotFoundException(inputModel.Id);
            }

            //...e lui ci recupererà il corso (collegato a quell'id) andando a richiamare i metodi presenti in Courses
            course.ChangeTitle(inputModel.Title);
            course.ChangePrices(inputModel.FullPrice, inputModel.CurrentPrice);
            course.ChangeDescription(inputModel.Description);
            course.ChangeEmail(inputModel.Email);

            //concorrenza ottimistica (prima di invocare il SaveAsync)
            //chiediamo il registro dell'entità (Entry(course) e la sua proprietà RowVersion a cui settiamo l'original value)
            //il valore fornito dall'input model é letto dal db
            dbContext.Entry(course).Property(course => course.RowVersion).OriginalValue = inputModel.RowVersion;

            if (inputModel.Image != null)
            {
                try{
                    string imagePath = await imagePersister.SaveCourseImageAsync(inputModel.Id, inputModel.Image);

                    //aggiorno solo l'image path con il nuovo percorso che é stato restituito
                    course.ChangeImagePath(imagePath);
                }
                catch (Exception ex) //immagine troppo grande!
                {
                    throw new CourseImageInvalidException(inputModel.Id, ex);
                }
            }

            //dbContext.Update(course); non necessario perché già l'entità course viene tracciata

            try
            {
                //SaveChangesAsync invia un comando update al database
                await dbContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw new OptimisticConcurrencyException();
            }
            catch (DbUpdateException ex) when((ex.InnerException as SqliteException)?.SqliteErrorCode == 19)
            {
                throw new CourseTitleUnavailableException(inputModel.Title, ex);
            }

            return(CourseDetailViewModel.FromEntity(course));
        }
Esempio n. 3
0
        public async Task <CourseDetailViewModel> EditCourseAsync(CourseEditInputModel inputModel)
        {
            Course course = await dbContext.Courses.FindAsync(inputModel.Id);

            if (course == null)
            {
                throw new CourseNotFoundException(inputModel.Id);
            }

            course.ChangeTitle(inputModel.Title);
            course.ChangePrices(inputModel.FullPrice, inputModel.CurrentPrice);
            course.ChangeDescription(inputModel.Description);
            course.ChangeEmail(inputModel.Email);

            dbContext.Entry(course).Property(course => course.RowVersion).OriginalValue = inputModel.RowVersion;

            if (inputModel.Image != null)
            {
                try
                {
                    string imagePath = await imagePersister.SaveCourseImageAsync(inputModel.Id, inputModel.Image);

                    course.ChangeImagePath(imagePath);
                }
                catch (Exception exc)
                {
                    throw new CourseImageInvalidException(inputModel.Id, exc);
                }
            }

            //dbContext.Update(course);

            try
            {
                await dbContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw new OptimisticConcurrencyException();
            }
            catch (DbUpdateException exc) when((exc.InnerException as SqliteException)?.SqliteErrorCode == 19)
            {
                throw new CourseTitleUnavailableException(inputModel.Title, exc);
            }

            return(CourseDetailViewModel.FromEntity(course));
        }
Esempio n. 4
0
        public async Task <CourseDetailViewModel> EditCourseAsync(CourseEditInputModel inputModel)
        {
            try
            {
                string imagePath = null;
                if (inputModel.Image != null)
                {
                    imagePath = await imagePersister.SaveCourseImageAsync(inputModel.Id, inputModel.Image);
                }
                int affectedRows = await db.CommandAsync($"UPDATE Courses SET ImagePath=COALESCE({imagePath}, ImagePath), Title={inputModel.Title}, Description={inputModel.Description}, Email={inputModel.Email}, CurrentPrice_Currency={inputModel.CurrentPrice.Currency.ToString()}, CurrentPrice_Amount={inputModel.CurrentPrice.Amount}, FullPrice_Currency={inputModel.FullPrice.Currency.ToString()}, FullPrice_Amount={inputModel.FullPrice.Amount} WHERE Id={inputModel.Id} AND Status<>{nameof(CourseStatus.Deleted)} AND RowVersion={inputModel.RowVersion}");

                if (affectedRows == 0)
                {
                    bool courseExists = await db.QueryScalarAsync <bool>($"SELECT COUNT(*) FROM Courses WHERE Id={inputModel.Id} AND Status<>{nameof(CourseStatus.Deleted)}");

                    if (courseExists)
                    {
                        throw new OptimisticConcurrencyException();
                    }
                    else
                    {
                        throw new CourseNotFoundException(inputModel.Id);
                    }
                }
            }
            catch (ConstraintViolationException exc)
            {
                throw new CourseTitleUnavailableException(inputModel.Title, exc);
            }
            catch (ImagePersistenceException exc)
            {
                throw new CourseImageInvalidException(inputModel.Id, exc);
            }

            CourseDetailViewModel course = await GetCourseAsync(inputModel.Id);

            return(course);
        }
        public async Task <CourseDetailViewModel> EditCourseAsync(CourseEditInputModel inputModel)
        {
            //verifica quante righe esistono con quell'id
            //se ritorna 0: non c'é alcun corso corrispondente al criterio

            /*bool courseExists = await db.ExecuteQueryScalarAsync<bool>($"SELECT COUNT(*) FROM Courses WHERE Id={inputModel.Id}");
             * if (!courseExists)
             * {
             *  throw new CourseNotFoundException(inputModel.Id);   //e sollevo un eccezione impedendo lo svolgimento delle funzioni a seguire
             * }*/

            try
            {
                string imagePath = null;
                if (inputModel.Image != null)
                {
                    imagePath = await imagePersister.SaveCourseImageAsync(inputModel.Id, inputModel.Image);
                }
                //COALESCE: può accettare un qualsiasi numero di argomenti e restituisce il primo che trova NON NULL
                //se image path é null (nessuna img fornita), restituisce il valore stesso del campo imagePath (riassegnato su se stesso)

                int affectedRows = await db.CommandAsync($"UPDATE Courses SET ImagePath=COALESCE({imagePath}, ImagePath), Title={inputModel.Title}, Description={inputModel.Description}, Email={inputModel.Email}, CurrentPrice_Currency={inputModel.CurrentPrice.Currency.ToString()}, CurrentPrice_Amount={inputModel.CurrentPrice.Amount}, FullPrice_Currency={inputModel.FullPrice.Currency.ToString()}, FullPrice_Amount={inputModel.FullPrice.Amount} WHERE Id={inputModel.Id} AND RowVersion={inputModel.RowVersion}");

                if (affectedRows == 0)  //se il numero di righe interessate é 0
                {
                    //verifichiamo se il corso esiste
                    bool courseExists = await db.ExecuteQueryScalarAsync <bool>($"SELECT COUNT(*) FROM Courses WHERE Id={inputModel.Id}"); //count = 1: corso esistente, count = 0: corso non esiste

                    if (courseExists)                                                                                                      //se il corso esiste
                    {
                        //allora é fallito il controllo sulla rowVersion (concorrenza ottimistica)
                        throw new OptimisticConcurrencyException();
                    }
                    else //se il corso non dovesse esistere
                    {
                        throw new CourseNotFoundException(inputModel.Id);
                    }
                }
            }
            catch (ConstraintViolationException ex)
            {
                //eccezione personalizzata: creazione del corso fallita perché il titolo é già in utilizzo da un altro corso
                throw new CourseTitleUnavailableException(inputModel.Title, ex);
            }
            catch (ImagePersistenceException ex) //immagine troppo grande!
            {
                throw new CourseImageInvalidException(inputModel.Id, ex);
            }

            /*if (inputModel.Image != null)
             * {
             *  try{
             *      string imagePath = await imagePersister.SaveCourseImageAsync(inputModel.Id, inputModel.Image);
             *      //aggiorno solo l'image path con il nuovo percorso che é stato restituito
             *      dataSet = await db.ExecuteQueryAsync($"UPDATE Courses SET ImagePath={imagePath} WHERE Id={inputModel.Id}");
             *  }
             *  catch(Exception ex) //immagine troppo grande!
             *  {
             *      throw new CourseImageInvalidException(inputModel.Id, ex);
             *  }
             *
             * }*/

            CourseDetailViewModel course = await GetCourseAsync(inputModel.Id);

            return(course);
        }