public HttpResponseMessage Post(AuthorDTO author)
        {
            HttpResponseMessage result;

            try
            {
                if (author == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NoContent);
                }

                var mapper = configToEntity.CreateMapper();
                var a      = mapper.Map <AuthorDTO, Author>(author);

                var updatedItem = _authorRepo.AddOrUpdate(a);
                _authorRepo.SaveChanges();
                var content = config.CreateMapper().Map <Author, AuthorDTO>(updatedItem);
                result = Request.CreateResponse(HttpStatusCode.Created, content);
            }
            catch (Exception ex)
            {
                result = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, ex);
            }

            return(result);
        }
        public async Task <IActionResult> Post([FromBody] AuthorDTO authorDTO)
        {
            var newAuthor = _mapper.Map <Author>(authorDTO);
            await _authorService.InsertAuthor(newAuthor);

            return(Created(nameof(Get), new { id = newAuthor.Id, newAuthor }));
        }
Exemple #3
0
        public async Task <IActionResult> PutAuthor(int id, AuthorDTO authorDTO)
        {
            var author = _mapper.Map <Author>(authorDTO);

            if (id != author.AuthorId)
            {
                return(BadRequest());
            }

            _context.Entry(author).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AuthorExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok(_mapper.Map <AuthorDTO>(author)));
        }
Exemple #4
0
        public async Task <IActionResult> GetAuthor(int Id)
        {
            string location = GetControllerActionNames();

            try
            {
                _logger.LogInfo($"{location}: Attempted call for Id: {Id}.");
                Author author = await _authorRepository.FindById(Id);

                if (author == null)
                {
                    _logger.LogWarn($"{location}: Failed to retrieve record with Id: {Id}.");

                    return(NotFound());
                }

                AuthorDTO response = _mapper.Map <AuthorDTO>(author);
                _logger.LogInfo($"{location}: Successful got record with Id: {Id}.");

                return(Ok(response));
            }
            catch (Exception e)
            {
                return(InternalError($"{location}: {e.Message} - {e.InnerException}"));
            }
        }
        public async Task Handler_ShouldAddAuthor()
        {
            // Arrange
            var author = new AuthorDTO
            {
                Id        = 4,
                UserId    = "QWERTY1234567890_test",
                FirstName = "FirstName_test",
                LastName  = "LastName_test",
                BirthDate = new DateTime(2004, 01, 01),
                Email     = "*****@*****.**",
            };

            var command = new CreateAuthorCommand {
                Model = author
            };

            // Act
            var handler = new CreateAuthorCommand.CreateAuthorCommandHandler(Context, Mapper);
            await handler.Handle(command, CancellationToken.None);

            var entity = Context.Authors.Find(author.Id);

            // Assert
            entity.ShouldNotBeNull();

            entity.Id.ShouldBe(command.Model.Id);
            entity.UserId.ShouldBe(command.Model.UserId);
            entity.FirstName.ShouldBe(command.Model.FirstName);
            entity.LastName.ShouldBe(command.Model.LastName);
            entity.BirthDate.ShouldBe(command.Model.BirthDate);
        }
Exemple #6
0
        public AuthorDTO GetAuthorByName(string AuthorFN, string AuthorLN)
        {
            connection.Open();

            SqlCommand cmd = connection.CreateCommand();

            cmd.CommandText = "SELECT * FROM Author WHERE Firstname = @Firstname AND Lastname = @Lastname";
            cmd.Parameters.AddWithValue("@Firstname", AuthorFN);
            if (AuthorLN != null)
            {
                cmd.Parameters.AddWithValue("@Lastname", AuthorLN);
            }
            else
            {
                cmd.Parameters.AddWithValue("@Lastname", DBNull.Value);
            }

            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                AuthorDTO author = new AuthorDTO(Convert.ToInt32(rdr[0]), rdr[1] as string, rdr[2] as string, rdr[3] as string, rdr[4] as string, Convert.ToInt32(rdr[5] as string), Convert.ToInt32(rdr[6] as string));
                rdr.Close();
                connection.Close();
                return(author);
            }
            rdr.Close();
            connection.Close();
            return(null);
        }
Exemple #7
0
        // GET: Author/Delete/5
        public ActionResult Delete(int id)
        {
            AuthorModel model = new AuthorModel {
            };

            AuthorDTO obj = db.GetAuthorByUnique_Id(id);

            if (obj == null)
            {
                TempData["Error"] = "ასეთი ჩანაწერი არ არსებობს";
                return(RedirectToAction("Index"));
            }

            model.Unique_Id   = obj.Unique_Id;
            model.Firstname   = obj.Firstname;
            model.Lastname    = obj.Lastname;
            model.Gender      = obj.Gender.Gender1;
            model.Personal_Id = obj.Personal_Id;
            model.Birth_Date  = obj.Birth_Date;
            model.Country     = obj.Country.Name;
            model.City        = obj.City.Name;
            model.Phone       = obj.Phone;
            model.Email       = obj.Email;

            return(View(model));
        }
        public async Task Handler_GivenValidData_ShouldUpdateAuthor()
        {
            // Arrange
            var author = new AuthorDTO
            {
                Id        = 2,
                UserId    = "QWERTY1234567890_new",
                FirstName = "FirstName_new",
                LastName  = "LastName_new",
                BirthDate = new DateTime(2000, 01, 01),
                Email     = "*****@*****.**",
            };

            var command = new UpdateAuthorCommand {
                Model = author
            };

            // Act
            var handler = new UpdateAuthorCommand.UpdateAuthorCommandHandler(Context);
            await handler.Handle(command, CancellationToken.None);

            var entity = Context.Authors.Find(author.Id);

            // Assert
            entity.ShouldNotBeNull();

            entity.FirstName.ShouldBe(command.Model.FirstName);
            entity.LastName.ShouldBe(command.Model.LastName);
            entity.BirthDate.ShouldBe(command.Model.BirthDate);

            entity.UserId.ShouldNotBe(command.Model.UserId);
        }
Exemple #9
0
        public static List <Book> getAllAid(string aId)
        {
            List <BookDTO> dtoList = null;;

            // This method retrieves a list of all books in the library system
            if (string.IsNullOrEmpty(aId))
            {
                dtoList = LibraryDataAccess.getAllBooksDAL();  //BookDTO is the interface common for BL and DAL
            }
            else
            {
                //Fetch the correct AuthorDTO object and connect an Author object for it
                AuthorDTO dto = LibraryDataAccess.loadAuthorDAL(Convert.ToInt32(aId));
                dto.loadStatus = LoadStatus.Ghost; //Force it to load all data
                Author AuthorObject = new Author(dto);
                // Use the author objects IsbnList property
                dtoList = LibraryDataAccess.getAllAuthorBookDAL(AuthorObject.IsbnList);
            }
            // Convert to Book objects since UI only references BL (not DAL or DTO)
            List <Book> results = new List <Book>();

            foreach (BookDTO dto in dtoList)
            {
                Book item = new Book(dto);
                results.Add(item);
            }
            return(results);
        }
Exemple #10
0
        public async Task CreateAuthorAsync(AuthorDTO author)
        {
            var entity = mapper.Map <Author>(author);

            entity.BookAuthors = new List <BookAuthor>();

            var doesAuthorExists = await uow.Authors.ExistsAsync(a => a.Name.ToUpper().Equals(entity.Name.ToUpper()));

            if (!doesAuthorExists)
            {
                foreach (var book in author.Books)
                {
                    var bookEntity = await uow.Books.GetBookByTitleAsync(book);

                    //TODO: add here a condition if there is no such book in db
                    var bookAuthor = new BookAuthor
                    {
                        Book   = bookEntity,
                        Author = entity,
                    };

                    entity.BookAuthors.Add(bookAuthor);
                }

                await uow.Authors.CreateAuthorAsync(entity);
            }
        }
Exemple #11
0
 private void Save_Click(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrEmpty(txtbox_FirstName.Text) || string.IsNullOrEmpty(txtbox_LastName.Text) || string.IsNullOrEmpty(txtbox_MiddleName.Text))
     {
         ShowMsg("Adding error", "First fill all fields");
     }
     else
     {
         AuthorDTO authorDTO = new AuthorDTO()
         {
             FirstName = txtbox_FirstName.Text, LastName = txtbox_LastName.Text, MiddleName = txtbox_MiddleName.Text
         };
         IBLLClass bLLClass = new BLLClass();
         if (!bLLClass.IsExistAuthor(authorDTO))
         {
             bLLClass.AddAuthor(authorDTO);
             authors.LoadAuthors();
             ShowMsg("Adding", "Author added!");
             this.Close();
         }
         else
         {
             ShowMsg("Adding error", "Such author already exists!");
         }
     }
 }
Exemple #12
0
        public async Task <ActionResult <Author> > PostAuthor([FromBody] AuthorDTO author, [FromHeader(Name = "Authorization")] string admin)
        {
            if (!String.IsNullOrWhiteSpace(admin))
            {
                if (admin.Equals("admin"))
                {
                    Author a = new Author();
                    a.Name     = author.Name;
                    a.Email    = author.Email;
                    a.Username = author.Username;
                    a.Articles = author.Articles;

                    _context.Authors.Add(a);
                    await _context.SaveChangesAsync();

                    return(CreatedAtAction("GetAuthor", new { id = a.Id }, a));
                }
                else
                {
                    return(Unauthorized());
                }
            }
            else
            {
                return(StatusCode(500));
            }
        }
Exemple #13
0
        public async Task <IActionResult> PutAuthor([FromRoute] Guid id, [FromBody] AuthorDTO author)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != author.Id)
            {
                return(BadRequest());
            }

            _context.Entry(author).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AuthorExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> Put(int id, [FromBody] AuthorDTO authorDTO)
        {
            var currentAuthor = await _authorService.GetAuthor(id);

            if (currentAuthor == null)
            {
                return(NotFound());
            }

            if (id != authorDTO.Id)
            {
                return(BadRequest());
            }

            var updateAuthor = _mapper.Map <Author>(authorDTO);

            updateAuthor.Id = id;

            var result = await _authorService.UpdateAuthor(updateAuthor);

            if (!result)
            {
                return(BadRequest());
            }

            return(NoContent());
        }
Exemple #15
0
        public ActionResult Delete(int id, AuthorModel model)
        {
            try
            {
                // TODO: Add delete logic here

                AuthorDTO objA = db.GetAuthorByUnique_Id(id);
                if (objA == null)
                {
                    TempData["Error"] = "ასეთი ჩანაწერი არ არსებობს";
                    return(RedirectToAction("Index"));
                }

                AuthorDTO obj = db.GetAuthorByUnique_Id(id);


                db.DeleteAuthor(obj);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Exemple #16
0
        public void CreateNewAuthor(AuthorDTO authorDTO)
        {
            Author authorEntity = _mapper.Map <Author>(authorDTO);

            authorEntity.Id = Guid.NewGuid();
            _authorsRepository.Save(authorEntity);
        }
        public ActionResult Details(int id)
        {
            AuthorDTO author = null;

            try
            {
                author = authorsService.Get(id);
            }
            catch
            {
                return(RedirectToAction("Error", new { exeption = "The author doesn't exist in database anymore!" }));
            }
            if (author == null)
            {
                return(NotFound());
            }
            var _author = new AuthorViewModel
            {
                AuthorId = author.AuthorId,
                Name     = author.Name,
                Sername  = author.Sername,
                Age      = author.Age,
                NickName = author.NickName
            };

            ViewBag.Image   = author.Photo;
            ViewBag.IsAdmin = HttpContext.User.IsInRole("Administrator");

            return(View(_author));
        }
Exemple #18
0
        public ActionResult DeleteConfirmed(int id)
        {
            AuthorDTO authorDto = myBooksService.GetAuthor(id);

            myBooksService.DeleteAuthor(id);
            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult Create(AuthorViewModel _author)
        {
            AuthorDTO author = new AuthorDTO();

            if (ModelState.IsValid)
            {
                if (authorsService.GetAll().Where(x => x.NickName == _author.NickName).Count() > 0)
                {
                    return(RedirectToAction("Error", new { exeption = "The author already exist!" }));
                }
                else
                {
                    author.Name     = _author.Name;
                    author.Sername  = _author.Sername;
                    author.NickName = _author.NickName;
                    author.Age      = _author.Age;
                    author.Photo    = _author.Image != null?ImageConverter.GetBytes(_author.Image) : null;

                    authorsService.Add(author);
                    authorsService.Save();
                    return(RedirectToAction(nameof(List)));
                }
            }
            return(View(_author));
        }
Exemple #20
0
        public async Task Handle_GivenValidUserId_ReturnsAuthorDTO()
        {
            // Arrange
            var author = new AuthorDTO
            {
                Id        = 1,
                UserId    = "QWERTY1234567890_One",
                FirstName = "FirstName_One",
                LastName  = "LastName_One",
                BirthDate = new DateTime(1988, 01, 01),
            };

            var query = new GetAuthorByUserIdQuery {
                UserId = "QWERTY1234567890_One"
            };

            // Act
            var handler = new GetAuthorByUserIdQuery.GetAuthorByUserIdQueryHandler(Context, Mapper);
            var result  = await handler.Handle(query, CancellationToken.None);

            // Assert
            result.ShouldBeOfType <AuthorDTO>();
            result.ShouldNotBeNull();

            result.Id.ShouldBe(author.Id);
            result.UserId.ShouldBe(author.UserId);
            result.FirstName.ShouldBe(author.FirstName);
            result.LastName.ShouldBe(author.LastName);
            result.BirthDate.ShouldBe(author.BirthDate);
        }
Exemple #21
0
        private async void LoginAsync(PasswordBox passwordBox)
        {
            if (passwordBox == null)
            {
                return;
            }

            try
            {
                AuthorDTO result = await _model.LoginAsync(UserName, passwordBox.Password);

                //_model.LoginAsync(UserName, passwordBox.Password)

                if (result != null)
                {
                    OnLoginSuccess(result);
                }
                else
                {
                    OnLoginFailed();
                }
            }
            catch (PersistenceUnavailableException)
            {
                OnMessageApplication("No connection to the service.");
            }
        }
Exemple #22
0
        public void AddAuthor(AuthorDTO author)
        {
            connection.Open();

            SqlCommand cmd = connection.CreateCommand();

            cmd.CommandText = "INSERT INTO Author(Firstname, Preposition, Lastname, City, Year_of_birth, Year_of_death) VALUES (@Firstname, @Preposition, @Lastname, @City, @Year_of_birth, @Year_of_death)";
            cmd.Parameters.AddWithValue("@Firstname", author.Firstname);
            cmd.Parameters.AddWithValue("@Preposition", String.IsNullOrWhiteSpace(author.Preposition) ? (object)DBNull.Value : (object)author.Preposition);
            cmd.Parameters.AddWithValue("@Lastname", String.IsNullOrWhiteSpace(author.Lastname) ? (object)DBNull.Value : (object)author.Lastname);
            cmd.Parameters.AddWithValue("@City", String.IsNullOrWhiteSpace(author.City) ? (object)DBNull.Value : (object)author.City);
            if (author.Year_of_birth == 0)
            {
                cmd.Parameters.AddWithValue("@Year_of_birth", DBNull.Value);
            }
            else
            {
                cmd.Parameters.AddWithValue("@Year_of_birth", author.Year_of_birth);
            }
            if (author.Year_of_death == 0)
            {
                cmd.Parameters.AddWithValue("@Year_of_death", DBNull.Value);
            }
            else
            {
                cmd.Parameters.AddWithValue("@Year_of_death", author.Year_of_death);
            }
            cmd.ExecuteNonQuery();
            cmd.Dispose();

            connection.Close();
        }
        public async Task <IActionResult> UpdateAuthor(int authorId, [FromBody] AuthorDTO author)
        {
            if (authorId != author.AuthorId)
            {
                return(BadRequest());
            }

            _wrapper.AuthorRepository.UpdateAuthor(_mapper.Map <Author>(author));

            try
            {
                await _wrapper.SaveAsync();
            }
            catch (DbUpdateConcurrencyException e)
            {
                if (!await AuthorExists(authorId))
                {
                    return(NotFound());
                }
                else
                {
                    return(BadRequest(e.Message));
                }
            }

            return(Ok());
        }
Exemple #24
0
        public static List <AuthorDTO> getAuthors()
        {
            string           SQL               = "SELECT * FROM AUTHOR";
            List <AuthorDTO> authorList        = new List <AuthorDTO>();
            string           _connectionString = DataSource.GetConnectionString("AdminConnection");
            SqlConnection    con               = new SqlConnection(_connectionString);
            SqlCommand       cmd               = new SqlCommand(SQL, con);

            try
            {
                con.Open();
                SqlDataReader dar = cmd.ExecuteReader();
                while (dar.Read())
                {
                    AuthorDTO aDTO = new AuthorDTO();
                    aDTO._aId = Convert.ToInt32(dar["Aid"] as string);
                    authorList.Add(aDTO);
                }
            }
            catch (Exception er)
            {
                throw er;
            }
            finally
            {
                con.Close();
            }
            return(authorList);
        }
Exemple #25
0
        public static AuthorDTO getAuthor(int aId)
        {
            AuthorDTO     dto = null;
            string        _connectionString = DataSource.GetConnectionString("AdminConnection");
            SqlConnection con = new SqlConnection(_connectionString);
            SqlCommand    cmd = new SqlCommand("SELECT * FROM author WHERE aid = " + Convert.ToString(aId) + ";", con);

            try
            {
                con.Open();
                SqlDataReader dar = cmd.ExecuteReader();
                if (dar.Read())
                {
                    dto            = new AuthorDTO();
                    dto._aId       = (int)dar["Aid"];
                    dto._lastName  = dar["LastName"] as string;
                    dto._firstName = dar["FirstName"] as string;
                    dto._birthYear = (dar["BirthYear"] == DBNull.Value) ? 0 : Convert.ToInt32(dar["BirthYear"].ToString());
                }
            }
            catch (Exception eObj)
            {
                throw eObj;
            }
            finally
            {
                con.Close();
            }
            return(dto);
        }
Exemple #26
0
 public void GetAllPersons(int authorId)
 {
     using (var context = new MusicAppDb())
     {
         context.Authors.ToList().Select(x => AuthorDTO.FromEntity(x)).ToList().ForEach(x => Console.WriteLine(x.FullName));
     }
 }
Exemple #27
0
        public bool Update(AuthorDTO authorDTO)
        {
            if (authorDTO == null)
            {
                return(false);
            }

            Author author = new Author
            {
                Id          = authorDTO.Id,
                FirstName   = authorDTO.FirstName,
                LastName    = authorDTO.LastName,
                Description = authorDTO.Description,
                ActiveFrom  = authorDTO.ActiveFrom,
                ActiveTo    = authorDTO.ActiveTo,
                BookCount   = authorDTO.BookCount,
                Rating      = authorDTO.Rating
            };

            try
            {
                UoW.AuthorRepo.Update(author);
                UoW.Save();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #28
0
        public void UpdateTest()
        {
            //Arange
            AuthorDTO updateDTO = new AuthorDTO()
            {
                Id   = "a1",
                Name = "NameUpdated"
            };
            bool isUpdate = false;
            Mock <IUnitOfWork>           unitOfWorkMock = new Mock <IUnitOfWork>();
            Mock <IRepository <Author> > repositoryMock = new Mock <IRepository <Author> >();

            repositoryMock.Setup(repo => repo.Get(It.IsAny <Expression <Func <Author, bool> > >()))
            .Returns <Expression <Func <Author, bool> > >(predicate =>
                                                          authors.Where(predicate.Compile()).AsQueryable());
            repositoryMock.Setup(repo => repo.Update(It.Is <Author>(entity =>
                                                                    (entity.Id == updateDTO.Id) &&
                                                                    (entity.Name == updateDTO.Name))))
            .Callback(() => isUpdate = true);
            unitOfWorkMock.Setup(getRepo => getRepo.GetRepository <Author>()).Returns(repositoryMock.Object);
            AuthorService authorsService = new AuthorService(unitOfWorkMock.Object);

            //Act
            authorsService.Update(updateDTO);

            //Assert
            Assert.True(isUpdate);
        }
Exemple #29
0
        public void AddTest()
        {
            //Arange
            AuthorDTO newAutohorDTO = new AuthorDTO()
            {
                Id   = "a0",
                Name = "Name0"
            };
            bool isAdded = false;
            Mock <IUnitOfWork>           unitOfWorkMock = new Mock <IUnitOfWork>();
            Mock <IRepository <Author> > repositoryMock = new Mock <IRepository <Author> >();

            repositoryMock.Setup(repo => repo.Get(It.IsAny <Expression <Func <Author, bool> > >()))
            .Returns <Expression <Func <Author, bool> > >(predicate =>
                                                          authors.Where(predicate.Compile()).AsQueryable());
            repositoryMock.Setup(repo => repo.Add(It.IsAny <Author>())).Callback(() => isAdded = true);
            unitOfWorkMock.Setup(getRepo => getRepo.GetRepository <Author>()).Returns(repositoryMock.Object);
            AuthorService authorService = new AuthorService(unitOfWorkMock.Object);

            //Act
            authorService.Add(newAutohorDTO);

            //Assert
            Assert.True(isAdded);
        }
Exemple #30
0
        public IActionResult EditAuthor(EditAuthorViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (model == null)
                {
                    throw new Exception();
                }

                AuthorDTO newAuthor = new AuthorDTO
                {
                    Id          = model.Id,
                    Name        = model.Name.Trim(),
                    Description = model.Description,
                    Surname     = model.Surname.Trim()
                };
                if (model.Image != null)
                {
                    byte[] imageData = null;
                    using (var binaryReader = new BinaryReader(model.Image.OpenReadStream()))
                    {
                        imageData = binaryReader.ReadBytes((int)model.Image.Length);
                    }
                    newAuthor.Image = imageData;
                }
                else
                {
                    throw new Exception();
                }
                _authorService.Update(newAuthor);
            }
            return(RedirectToAction("AuthorsList"));
        }
 public void GenerateData(List<ChangeList> allChangeLists)
 {
     foreach (var changeList in allChangeLists)
     {
         AuthorDTO authorDto;
         var author = changeList.Author;
         if (!data.TryGetValue(author, out authorDto))
         {
             authorDto = new AuthorDTO {Author = author, Commits = new Dictionary<int, CommitDTO>()};
             data.Add(author, authorDto);
         }
         var commits = authorDto.Commits;
         CommitDTO values;
         var year = changeList.Date.Year;
         if (!commits.TryGetValue(year, out values))
         {
             values = new CommitDTO() {All = 0, Hourly = new int[24]};
             commits.Add(year, values);
         }
         var hour = changeList.Date.Hour;
         values.Hourly[hour]++;
         values.All++;
     }
 }
Exemple #32
0
 partial void OnAuthorChanging(AuthorDTO value);
Exemple #33
0
 public static ChangesetDTO CreateChangesetDTO(string revision, AuthorDTO author, global::System.DateTime time)
 {
     ChangesetDTO changesetDTO = new ChangesetDTO();
     changesetDTO.Revision = revision;
     if ((author == null))
     {
         throw new global::System.ArgumentNullException("author");
     }
     changesetDTO.Author = author;
     changesetDTO.Time = time;
     return changesetDTO;
 }