/// <summary> /// Provides an image from an external API to be attached to a playlist /// </summary> /// <param name="PlaylistDTO">The DTO of the playlist the image will be assigned to</param> /// <returns>Returns the local file path the image was saved to</returns> public async Task <string> AssignImage(PlaylistDTO PlaylistDTO) { var jsonString = await client.GetAsync(startUrl).Result.Content.ReadAsStringAsync(); var pixaBayImageCollection = JsonSerializer.Deserialize <PixaBayImageCollection>(jsonString); int imgIndex = new Random().Next(0, pixaBayImageCollection.PixaBayImages.Count); string imgUrl = pixaBayImageCollection.PixaBayImages[imgIndex].WebFormatURL; (string, string)paths = GetFilePathForImage(PlaylistDTO); string filePath = paths.Item1; string physicalPath = paths.Item2; using (WebClient c = new WebClient()) { byte[] imageData = c.DownloadData(imgUrl.ToString()) ?? throw new ArgumentNullException("Image not found."); using MemoryStream mem = new MemoryStream(imageData); using (var yourImage = Image.FromStream(mem)) { yourImage.Save($"{physicalPath}.jpg", ImageFormat.Jpeg); } } return(filePath); }
public async Task Throw_When_NoPlaylistsExistToAttachImageTo() { //Arrange var options = Utils.GetOptions(nameof(Throw_When_NoPlaylistsExistToAttachImageTo)); PlaylistDTO firstPlaylistDTO = new PlaylistDTO { Id = 91, Title = "Home", PlaylistPlaytime = 5524, UserId = 2, Rank = 552348, }; var dateTimeProviderMock = new Mock <IDateTimeProvider>(); var mockImageService = new Mock <IPixaBayImageService>(); using (var assertContext = new RidePalDbContext(options)) { //Act var sut = new PlaylistService(assertContext, dateTimeProviderMock.Object, mockImageService.Object); //Assert await Assert.ThrowsExceptionAsync <ArgumentNullException>(() => sut.AttachImage(firstPlaylistDTO)); } }
public async Task DeleteThrowsWhenIdAlreadyDeleted() { var options = Utils.GetOptions(nameof(DeleteThrowsWhenIdAlreadyDeleted)); var playlist = new PlaylistDTO { Title = "In Utero", Duration = 1600, //PixabayImage = "https://en.wikipedia.org/wiki/In_Utero_(album)#/media/File:In_Utero_(Nirvana)_album_cover.jpg", }; using (var arrangeContext = new PGDbContext(options)) { var sut = new PlaylistService(arrangeContext); await sut.Create(playlist); await arrangeContext.SaveChangesAsync(); } using (var assertContext = new PGDbContext(options)) { var sut = new PlaylistService(assertContext); await sut.Delete(1); await Assert.ThrowsExceptionAsync <ArgumentException>(() => sut.Delete(1)); } }
/// <summary> /// Creates a playlist /// </summary> /// <param name="playlistDTO">Playlist to create</param> public async Task <Playlist> Create(PlaylistDTO playlistDTO) { if (playlistDTO == null) { throw new ArgumentNullException("Null Playlist"); } if (playlistDTO.Title.Length > 50) { throw new ArgumentOutOfRangeException("Playlist's title needs to be shorter than 50 characters."); } var existingPlaylist = await _context.Playlists.FirstOrDefaultAsync(x => x.Title == playlistDTO.Title); if (existingPlaylist != null) { throw new ArgumentException($"Playlist with title '{playlistDTO.Title}' already exists."); } Playlist playlistToAdd = playlistDTO.ToEntity(); var playlist = await _context.Playlists.AddAsync(playlistToAdd); Log.Logger.Information($"Playlist with title '{playlist.Entity.Title}' has been created."); await _context.SaveChangesAsync(); return(playlist.Entity); }
public IEnumerable <IPlaylist> GetAllPlaylists() { _connection.SqlConnection.Open(); String query = "Select * From Playlist"; SqlCommand command = new SqlCommand(query, _connection.SqlConnection); SqlDataReader reader = command.ExecuteReader(); var playlistList = new List <IPlaylist>(); while (reader.Read()) { var playlist = new PlaylistDTO { ID = Convert.ToInt32(reader["ID"]), UserID = Convert.ToInt32(reader["PlaylistID"]), Title = reader["Title"].ToString(), Description = reader["Description"].ToString(), Image = (byte[])reader["Image"] }; playlistList.Add(playlist); } return(playlistList); }
public async Task <OperationDetails> Update(PlaylistDTO playlistDTO) { var playlist = Database.PlaylistManager.Get(playlistDTO.Id); if (playlist != null) { playlist = new Playlist { Id = playlistDTO.Id, Name = playlistDTO.Name, UserId = playlistDTO.UserId }; List <PlaylistMusic> playlistMusics = playlistDTO.Musics.Select(x => new PlaylistMusic() { Id = Guid.NewGuid().ToString(), PlaylistId = playlist.Id, MusicId = x.Id }).ToList(); Database.PlaylistManager.Update(playlist); Database.PlaylistMusicManager.DeleteByPlaylistId(playlist.Id); foreach (var pm in playlistMusics) { Database.PlaylistMusicManager.Create(pm); } await Database.SaveAsync(); return(new OperationDetails(true, "Playlist update successfully", "")); } return(new OperationDetails(false, "Playlist is not exist", "Name")); }
public async Task UpdatePlaylistNameAsync(PlaylistDTO playlistDTO, string NewName) { var userPlaylist = mapper.Map <UserPlaylist>(playlistDTO); userPlaylist.PlaylistName = NewName; await unitOfWork.UserPlaylistRepository.Update(userPlaylist); }
public async Task <OperationDetails> Create(PlaylistDTO playlistDTO) { var playlists = Database.PlaylistManager.GetAll().ToList(); var playlist = playlists.Find(x => x.Name == playlistDTO.Name); if (playlist == null && playlistDTO.Name != null && playlistDTO.UserId != null) { playlist = new Playlist { Id = Guid.NewGuid().ToString(), Name = playlistDTO.Name, UserId = playlistDTO.UserId }; List <PlaylistMusic> playlistMusics = playlistDTO.Musics.Select(x => new PlaylistMusic() { Id = Guid.NewGuid().ToString(), PlaylistId = playlist.Id, MusicId = x.Id }).ToList(); Database.PlaylistManager.Create(playlist); foreach (var pm in playlistMusics) { Database.PlaylistMusicManager.Create(pm); } await Database.SaveAsync(); return(new OperationDetails(true, "Playlist added successfully", "")); } return(new OperationDetails(false, "Playlist is exist or empty", "Name")); }
public ActionResult PlaylistConcrete(int playlistId) { PlaylistConcreteViewModel modelPlaylist = new PlaylistConcreteViewModel(); using (IPlaylistService playlistService = ServiceCreator.CreatePlaylistService(Connection)) { PlaylistDTO playlistDto = playlistService.GetById(playlistId); if (playlistDto != null) { if (playlistDto.ApplicationUser.UserName != User.Identity.Name) { return(HttpNotFound()); } modelPlaylist.Id = playlistDto.Id; modelPlaylist.Name = playlistDto.Name; modelPlaylist.Description = playlistDto.Description; modelPlaylist.Videos = playlistDto.Videos; } } if (modelPlaylist == null) { return(HttpNotFound()); } return(View(modelPlaylist)); }
public async Task DeleteCorrectly() { var options = Utils.GetOptions(nameof(DeleteCorrectly)); var playlist = new PlaylistDTO { Title = "In Utero", Duration = 1600, //PixabayImage = "https://en.wikipedia.org/wiki/In_Utero_(album)#/media/File:In_Utero_(Nirvana)_album_cover.jpg", }; using (var arrangeContext = new PGDbContext(options)) { var sut = new PlaylistService(arrangeContext); await sut.Create(playlist); await arrangeContext.SaveChangesAsync(); } using (var assertContext = new PGDbContext(options)) { var sut = new PlaylistService(assertContext); await sut.Delete(1); var playlists = await sut.GetAllPlaylists(); int playlistsCount = playlists.Count(); Assert.AreEqual(0, playlistsCount); } }
public void Init() { var guid = _userAccountService.CreateAccount("Martin", "Password", "*****@*****.**"); _userService.CreateUser(guid.ID); _playlist1Id = 1; _playlist1 = new PlaylistDTO { Name = "Favorite songs", Created = new DateTime(2016, 10, 10), ID = _playlist1Id, UserId = 1 }; _playlist2Id = 2; _playlist2 = new PlaylistDTO { Name = "Christmas songs", Created = new DateTime(2016, 1, 1), ID = _playlist2Id, UserId = 1 }; _playlistService.CreatePlaylist(_playlist1, 1); _playlistService.CreatePlaylist(_playlist2, 1); }
public IEnumerable <IPlaylist> GetAllPlaylistsByUserID(int id) { _connection.SqlConnection.Open(); String query = "Select * From Playlist WHERE Playlist.UserID = @UserID"; SqlDataReader reader; using (SqlCommand command = new SqlCommand(query, _connection.SqlConnection)) { command.Parameters.AddWithValue("@UserID", id); reader = command.ExecuteReader(); } var playlistList = new List <IPlaylist>(); while (reader.Read()) { var playlist = new PlaylistDTO { Title = reader["Title"].ToString(), Description = reader["Description"].ToString(), Image = (byte[])reader["Image"] }; playlistList.Add(playlist); } return(playlistList); }
public async Task CreateCorrectly() { var options = Utils.GetOptions(nameof(CreateCorrectly)); var playlist = new PlaylistDTO { Title = "In Utero", Duration = 1600, //PixabayImage = "https://en.wikipedia.org/wiki/In_Utero_(album)#/media/File:In_Utero_(Nirvana)_album_cover.jpg", }; using (var arrangeContext = new PGDbContext(options)) { var sut = new PlaylistService(arrangeContext); await sut.Create(playlist); await arrangeContext.SaveChangesAsync(); } using (var assertContext = new PGDbContext(options)) { var result = await assertContext.Playlists.FirstOrDefaultAsync(x => x.Title == playlist.Title); Assert.AreEqual(playlist.Title, result.Title); Assert.AreEqual(playlist.Duration, result.Duration); //Assert.AreEqual(playlist.PixabayImage, result.Picture); } }
public async Task <IActionResult> Playlist(int id) { PlaylistDTO playlistDTO = await _playlistService.GetPlaylistById(id); PlaylistViewModel playlistViewModel = playlistDTO.ToViewModel(); return(View(playlistViewModel)); }
public async Task ReturnCorrectPlaylist_WhenParamsAreValid() { //Arrange var options = Utils.GetOptions(nameof(ReturnCorrectPlaylist_WhenParamsAreValid)); Playlist firstPlaylist = new Playlist { Id = 1, Title = "Home", PlaylistPlaytime = 5524, UserId = 2, Rank = 552348, IsDeleted = false }; Playlist secondPlaylist = new Playlist { Id = 2, Title = "Metal", PlaylistPlaytime = 5024, UserId = 2, Rank = 490258, IsDeleted = false }; var playlistDTO = new PlaylistDTO { Id = 2, Title = "Metal", PlaylistPlaytime = 5024, UserId = 2, Rank = 490258, }; var dateTimeProviderMock = new Mock <IDateTimeProvider>(); var mockImageService = new Mock <IPixaBayImageService>(); using (var arrangeContext = new RidePalDbContext(options)) { arrangeContext.Playlists.Add(firstPlaylist); arrangeContext.Playlists.Add(secondPlaylist); arrangeContext.SaveChanges(); } using (var assertContext = new RidePalDbContext(options)) { //Act var sut = new PlaylistService(assertContext, dateTimeProviderMock.Object, mockImageService.Object); var result = await sut.GetPlaylistByIdAsync(2); //Assert Assert.AreEqual(playlistDTO.Id, result.Id); Assert.AreEqual(playlistDTO.Title, result.Title); Assert.AreEqual(playlistDTO.Rank, result.Rank); Assert.AreEqual(playlistDTO.UserId, result.UserId); Assert.AreEqual(playlistDTO.PlaylistPlaytime, result.PlaylistPlaytime); } }
public async Task GetAllPlaylistsByUserCorrectly() { var options = Utils.GetOptions(nameof(GetAllPlaylistsByUserCorrectly)); var nirvanaPlaylist = new PlaylistDTO { Title = "In Utero", Duration = 1600, //PixabayImage = "https://en.wikipedia.org/wiki/In_Utero_(album)#/media/File:In_Utero_(Nirvana)_album_cover.jpg", UserId = "153a257-526504u", }; var acdcPlaylist = new PlaylistDTO { Title = "Back in Black", Duration = 2531, //PixabayImage = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/ACDC_Back_in_Black.png/220px-ACDC_Back_in_Black.png", UserId = "153a257-526504u", }; var scorpionsPLaylist = new PlaylistDTO { Title = "Lovedrive", Duration = 2190, //PixabayImage = "https://en.wikipedia.org/wiki/Lovedrive#/media/File:Scorpions-album-lovedrive.jpg", UserId = "68910y78a-89as1568", }; using (var arrangeContext = new PGDbContext(options)) { var sut = new PlaylistService(arrangeContext); await sut.Create(nirvanaPlaylist); await sut.Create(acdcPlaylist); await sut.Create(scorpionsPLaylist); await arrangeContext.SaveChangesAsync(); } using (var assertContext = new PGDbContext(options)) { var sut = new PlaylistService(assertContext); var firstUserPalylists = await sut.GetPlaylistsByUser("153a257-526504u"); int firstUserPalylistsCount = firstUserPalylists.Count(); var secondUserPalylists = await sut.GetPlaylistsByUser("68910y78a-89as1568"); int secondUserPalylistsCount = secondUserPalylists.Count(); Assert.AreEqual(2, firstUserPalylistsCount); Assert.AreEqual(1, secondUserPalylistsCount); } }
public UsersController() { services = new GoogleDriveServices(HttpContext.Current.Server.MapPath("~/")); Uri uri = HttpContext.Current.Request.Url; dto = new UserInfoDTO(uri); playlistDto = new PlaylistDTO(uri); songDto = new SongDTO(uri); }
public void CreatePlaylist(PlaylistDTO playlistDto, int userId) { using (var uow = UnitOfWorkProvider.Create()) { var playlist = Mapper.Map <Playlist>(playlistDto); playlist.User = GetPlaylistUser(userId); playlistRepository.Insert(playlist); uow.Commit(); } }
public PlaylistDTO GetById(int id) { Playlist playlist = Database.Playlists.Get(id); if (playlist != null) { PlaylistDTO playlistDto = getDTOFromPlaylist(playlist); return(playlistDto); } return(null); }
public static ApiModel.Playlist FromDTO(PlaylistDTO playlistDTO) { return(playlistDTO == null ? null : new ApiModel.Playlist() { Id = playlistDTO.Id, Title = playlistDTO.Title, IsGeneral = playlistDTO.IsGeneral, Owner = UserMapper.ToApi.FromData(playlistDTO.Owner), Audios = playlistDTO.Audios.Select(x => AudioMapper.ToApi.FromDTO(x)), }); }
public PlaylistDTO GetLastByName(string name) { Playlist playlist = Database.Playlists.GetAll().Where(p => p.Name == name).Last(); if (playlist != null) { PlaylistDTO playlistDTO = getDTOFromPlaylist(playlist); return(playlistDTO); } return(null); }
public void EditPlaylist(PlaylistDTO playlistDto, int userId) { using (var uow = UnitOfWorkProvider.Create()) { var playlist = playlistRepository.GetById(playlistDto.ID); Mapper.Map(playlistDto, playlist); playlist.User = GetPlaylistUser(userId); playlistRepository.Update(playlist); uow.Commit(); } }
private Playlist getPlaylistFromDTO(PlaylistDTO playlistDto) { var config = new MapperConfiguration(cfg => { cfg.CreateMap <PlaylistDTO, Playlist>(); cfg.CreateMap <VideoDTO, Video>(); cfg.CreateMap <UserDTO, ApplicationUser>(); }); var mapper = config.CreateMapper(); return(mapper.Map <PlaylistDTO, Playlist>(playlistDto)); }
public async Task <ActionResult> DeletePlaylist(int Id) { PlaylistDTO playlistDTO = await playlistService.GetPlaylistAsync(Id); if (playlistDTO == null) { return(NotFound()); } await playlistService.DeletePlaylistAsync(playlistDTO); return(NoContent()); }
/// <summary> /// Provides a physical and local file path to an image /// </summary> /// <param name="PlaylistDTO">The DTO of the playlist the image will be assigned to</param> /// <returns>Returns the physical and local path to an image</returns> public (string, string) GetFilePathForImage(PlaylistDTO PlaylistDTO) { var playlistImagesUploadFolder = Path.Combine(_env.WebRootPath, "assets\\img\\playlist"); this.fileCheck.CreateFolder(playlistImagesUploadFolder); var newFileName = $"{Guid.NewGuid()}_{PlaylistDTO.Title.Trim().Replace(" ", "_")}"; string playlistDBImageLocationPath = $"/assets/img/playlist/{newFileName}.jpg"; return(playlistDBImageLocationPath, $"{playlistImagesUploadFolder}\\{newFileName}"); }
public async Task <OperationDetails> Delete(PlaylistDTO playlistDTO) { var playlist = Database.PlaylistManager.Get(playlistDTO.Id); if (playlist != null) { Database.PlaylistManager.Delete(playlist.Id); await Database.SaveAsync(); return(new OperationDetails(true, "Playlist deleted successfully", "")); } return(new OperationDetails(false, "Playlist is not exist", "Name")); }
public static Playlist ToEntity(this PlaylistDTO playlistDTO) { return(new Playlist() { Id = playlistDTO.Id, UserId = playlistDTO.UserId, Title = playlistDTO.Title, Duration = playlistDTO.Duration, Rank = playlistDTO.Rank, //PixabayImage = playlistDTO.PixabayImage.ToEntity(), PlaylistsSongs = playlistDTO.PlaylistsSongs, }); }
/// <summary> /// Performs search for a playlist by a given ID in the database /// </summary> /// <param name="id">The ID of the playlist to search for</param> /// <returns>If successful, returns a DTO of the found playlist</returns> public async Task <PlaylistDTO> AdminGetPlaylistByIdAsync(int id) { var playlist = await this.context.Playlists .FirstOrDefaultAsync(playlist => playlist.Id == id); if (playlist == null) { throw new ArgumentNullException("No such playlist was found in the database."); } var playlistDTO = new PlaylistDTO(playlist); return(playlistDTO); }
public async Task <IActionResult> Create([Bind("Title," + "StartLocationName, DestinationName," + "RepeatArtist, TopTracks," + "MetalPercentage, RockPercentage, PopPercentage, JazzPercentage")] GeneratePlaylistViewModel genPlView) { if ((genPlView.MetalPercentage + genPlView.RockPercentage + genPlView.PopPercentage + genPlView.JazzPercentage) > 100) { return(RedirectToAction("Create", "Playlists", new { error = TempData["Error"] = "Combined genre percentage must not exceed 100%" })); } var userId = int.Parse(userManager.GetUserId(HttpContext.User)); var genres = new Dictionary <string, int>(); genres.Add("metal", genPlView.MetalPercentage); genres.Add("rock", genPlView.RockPercentage); genres.Add("pop", genPlView.PopPercentage); genres.Add("jazz", genPlView.JazzPercentage); if (ModelState.IsValid) { var genPlaylistDTO = new GeneratePlaylistDTO() { PlaylistName = genPlView.Title, StartLocation = genPlView.StartLocationName, Destination = genPlView.DestinationName, RepeatArtist = genPlView.RepeatArtist, UseTopTracks = genPlView.TopTracks, GenrePercentage = genres, UserId = userId }; PlaylistDTO playlistDTO = await generateService.GeneratePlaylist(genPlaylistDTO); if (playlistDTO == null) { throw new ArgumentNullException("Something went wrong with playlist creation."); } var playlistDtoWithImg = await this.service.AttachImage(playlistDTO); return(RedirectToAction("Details", new { id = playlistDtoWithImg.Id })); } return(RedirectToAction("Index", new { error = TempData["Error"] = "Playlist creation failed." })); }
public void CreatePlaylistTest() { Assert.AreEqual(2, _playlistService.ListPlaylists(null).Count()); var playlist = new PlaylistDTO { Name = "My playlist", Created = new DateTime(2016, 11, 1), UserId = 1 }; _playlistService.CreatePlaylist(playlist, 1); Assert.AreEqual(3, _playlistService.ListPlaylists(null).Count()); }