public EditAlbumViewModel Map(AlbumDetail album, ICollection <ArtistNameRef> artistNames, ICollection <GenreDetail> genres)
        {
            GenreViewModelMapper genreMapper = new GenreViewModelMapper();
            EditAlbumViewModel   model       = new EditAlbumViewModel();

            model.Id              = album.Id;
            model.ArtistId        = album.ArtistId;
            model.Title           = album.Title;
            model.DescriptionText = album.DescriptionText;
            model.Label           = album.Label;
            model.Price           = album.Price;
            model.Producer        = album.Producer;
            model.ReleaseDate     = album.ReleaseDate;
            model.CoverImageId    = album.CoverImageId;
            model.Created         = album.CreatedUtc;
            model.Updated         = album.UpdatedUtc;
            model.PublishedStatus = album.PublishedStatus;


            model.Tracks        = album.Tracks.Select(x => this.Map(x)).ToList();
            model.ArtistOptions = artistNames
                                  .Select(x => new SelectListItem
            {
                Text     = x.Name,
                Value    = x.Id.ToString(),
                Selected = x.Id == model.ArtistId
            }).ToList();

            model.Genres = genres.Select(g => genreMapper.Map(g)).ToList();
            model.Genres.Where(g => album.Genres.Contains(g.Name)).ToList().ForEach(x => x.IsSelected = true);

            return(model);
        }
Exemple #2
0
        public async void AddAlbum_ReturnsResultWithCorrectNumberOfTracks()
        {
            Album       input      = CreateValidModel();
            AlbumDetail createdObj = await this.repo.AddAsync(input);

            Assert.Equal(input.Tracks.Count, createdObj.Tracks.Count);
        }
Exemple #3
0
        public async void UpdateAlbum_OverWritesTracksWithNewRecords_WhenNoTrackIdsAreSuppliedForTracks(int numTracks)
        {
            int existingAlbumId = await SetupValidAlbumRecordInDatabase();

            Album a = await this.repo.GetAsync(existingAlbumId);

            int[] originalTrackIds = a.Tracks.Select(t => t.TrackId.Value).ToArray();

            List <AlbumTrack> newTracks = new List <AlbumTrack>();

            for (int i = 0; i < numTracks; i++)
            {
                newTracks.Add(new AlbumTrack
                {
                    DurationInSeconds = 100,
                    Title             = "new_title",
                    TrackId           = null,
                    TrackNumber       = i
                });
            }
            a.Tracks = newTracks;
            AlbumDetail result = await repo.UpdateAsync(existingAlbumId, a);

            // test that all prev ids were removed
            foreach (int trackId in originalTrackIds)
            {
                Assert.DoesNotContain(result.Tracks, x => x.TrackId == trackId);
            }
        }
Exemple #4
0
        public async void AddAlbum_ReturnsAlbumDetailResult_WithValidInput()
        {
            Album       input  = CreateValidModel();
            AlbumDetail result = await this.repo.AddAsync(input);

            Assert.IsType <AlbumDetail>(result);
        }
Exemple #5
0
        public async void AddAlbum_ReturnsNonNullResult_WithValidInput()
        {
            Album       input  = CreateValidModel();
            AlbumDetail result = await this.repo.AddAsync(input);

            Assert.NotNull(result);
        }
Exemple #6
0
        public async void GetAlbum_ReturnsTracksWithValidIds()
        {
            int albumId = await SetupValidAlbumRecordInDatabase();

            AlbumDetail result = await this.repo.GetAsync(albumId);

            foreach (var t in result.Tracks)
            {
                Assert.NotNull(t.TrackId);
            }
        }
Exemple #7
0
 private long AddAlbumDetail(DTO.LABURNUM.COM.AlbumDetailModel model)
 {
     API.LABURNUM.COM.AlbumDetail apiAlbumDetail = new AlbumDetail()
     {
         Attachment = model.Attachment,
         AlbumId    = model.AlbumId,
         CreatedOn  = new Component.Utility().GetISTDateTime(),
         IsActive   = true
     };
     this._laburnum.AlbumDetails.Add(apiAlbumDetail);
     this._laburnum.SaveChanges();
     return(apiAlbumDetail.AlbumDetailId);
 }
 public AlbumListItemViewModel Map(AlbumDetail a)
 {
     return(new AlbumListItemViewModel
     {
         Id = a.Id,
         Created = a.CreatedUtc,
         Status = a.PublishedStatus,
         Title = a.Title,
         ArtistName = a.ArtistName,
         ArtistId = a.ArtistId,
         Updated = a.UpdatedUtc
     });
 }
Exemple #9
0
        public async void AddAlbum_ReturnsResultWithMatchingProperties()
        {
            Album       input      = CreateValidModel();
            AlbumDetail createdObj = await this.repo.AddAsync(input);

            Assert.Equal(input.Title, createdObj.Title);
            Assert.Equal(input.PublishedStatus, createdObj.PublishedStatus);
            Assert.Equal(input.DescriptionText, createdObj.DescriptionText);
            Assert.Equal(input.Label, createdObj.Label);
            Assert.Equal(input.Price, createdObj.Price);
            Assert.Equal(input.Producer, createdObj.Producer);
            Assert.Equal(input.ReleaseDate, createdObj.ReleaseDate);
            Assert.Equal(input.TotalDurationInSeconds, createdObj.TotalDurationInSeconds);
            Assert.Equal(input.Genres, createdObj.Genres);
        }
 public AlbumDetail MapOnTo(EditAlbumViewModel model, AlbumDetail existingObject, int?coverImageId)
 {
     existingObject.Title           = model.Title;
     existingObject.DescriptionText = model.DescriptionText;
     existingObject.Genres          = model.Genres.Where(g => g.IsSelected).Select(g => g.Name).ToList();
     if (coverImageId.HasValue)
     {
         existingObject.CoverImageId = coverImageId.Value;
     }
     existingObject.Label       = model.Label;
     existingObject.Price       = model.Price;
     existingObject.Producer    = model.Producer;
     existingObject.ReleaseDate = model.ReleaseDate;
     existingObject.Tracks      = model.Tracks.Select(x => this.Map(x)).ToList();
     return(existingObject);
 }
Exemple #11
0
        public AlbumDetail MapToDetailRep(DbAlbum a)
        {
            PublishedStatusEnumMapper statusMapper = new PublishedStatusEnumMapper();

            if (a == null)
            {
                throw new NullReferenceException($"A null value was passed to the mapper. Expected an object of type {nameof(DbAlbum)}");
            }
            List <AlbumTrack> tracks = a.Tracks
                                       .OrderByDescending(x => x.TrackNumber)
                                       .Select(x => new AlbumTrack()
            {
                Title             = x.Title,
                DurationInSeconds = x.DurationInSeconds,
                TrackNumber       = x.TrackNumber,
                TrackId           = x.Id
            }).OrderBy(x => x.TrackNumber).ToList();

            var album = new AlbumDetail
            {
                Id                     = a.Id,
                Title                  = a.Title,
                DescriptionText        = a.DescriptionText,
                CoverImageId           = a.AlbumCoverImageId,
                Price                  = a.Price,
                Producer               = a.Producer,
                Label                  = a.Label,
                ReleaseDate            = a.ReleaseDate,
                TotalDurationInSeconds = a.TotalDurationInSeconds,
                Tracks                 = tracks,
                  CoverImageUrl        = (a.AlbumCoverImageId.HasValue ? $"/api/image/{a.AlbumCoverImageId.Value}" : null),
                Genres                 = a.AlbumGenres.Select(g => g.Genre.Name).ToList(),
                CreatedUtc             = new DateTime(a.CreatedUtc.Ticks, DateTimeKind.Utc),
                UpdatedUtc             = new DateTime(a.UpdatedUtc.Ticks, DateTimeKind.Utc),
                PublishedStatus        = statusMapper.Map(a.PublishStatus),
                ArtistId               = a.ArtistId
            };

            if (a.Artist != null)
            {
                album.ArtistName = a.Artist.Name;
            }


            return(album);
        }
Exemple #12
0
        public async void UpdateAlbum_UpdatesTracksWhenTrackIdsAreSuppliedForTracks()
        {
            int existingAlbumId = await SetupValidAlbumRecordInDatabase();

            Album a = await this.repo.GetAsync(existingAlbumId);

            int[] originalTrackIds = a.Tracks.Select(t => t.TrackId.Value).ToArray();

            foreach (var t in a.Tracks)
            {
                t.Title = "new_title";
            }
            AlbumDetail result = await repo.UpdateAsync(existingAlbumId, a);

            foreach (int trackId in originalTrackIds)
            {
                Assert.Contains(result.Tracks, x => x.TrackId == trackId);
            }
        }
Exemple #13
0
        public async Task <IActionResult> Get(int id)
        {
            try{
                AlbumDetail a = await _repository.GetAsync(id);

                if (a != null)
                {
                    return(Ok(a));
                }
                else
                {
                    return(NotFound(new ApiErrorRep($"Album with ID {id} was nto found")));
                }
            }catch (RepositoryException e) {
                return(BadRequest(new ApiErrorRep(e.Message)));
            }catch (Exception e) {
                _logger.LogError("GetArtist", e, "Error getting album");
                return(StatusCode(500, new ApiErrorRep("Unknown error")));
            }
        }
Exemple #14
0
        //insert vào DB
        private void InsertData()
        {
            ListAlbum newAlbum = new ListAlbum();

            newAlbum.name = labTen.Text;
            newAlbum.link = txtNhap.Text;
            int albumId = newAlbum.id;

            db.ListAlbums.Add(newAlbum);
            foreach (var item in album)
            {
                AlbumDetail detail = new AlbumDetail();
                // detail.idAlbum = int.Parse(db.ListAlbums.Max(s => s.id).ToString());
                detail.idAlbum = albumId;
                detail.song    = item.song;
                detail.singer  = item.singer;
                detail.link    = item.link;
                db.AlbumDetails.Add(detail);
            }
            db.SaveChanges();
        }
Exemple #15
0
        public async Task <ActionResult> Index(int albumId)
        {
            AlbumDetail albumDetail = await AlbumOperations.GetAlbumAsync(DbContext, albumId);

            if (albumDetail == null)
            {
                return(HttpNotFound());
            }

            UserInfo albumUser = await GetUserInfoAsync(albumDetail.UserId);

            AlbumViewModel vm = await SetVmEditorInfo(new AlbumViewModel
            {
                AlbumId  = albumId,
                FullName = albumUser.Name,
                PosessiveInformalName = UserOperations.GetInformalPosessiveName(albumUser),
                AvatarUrl             = UserOperations.GetAvatarUrl(albumUser),
                Detail = albumDetail
            });

            return(View(albumDetail.UserId == UserId ? "OwnedAlbum" : "Album", vm));
        }
Exemple #16
0
        public async Task <IActionResult> Add([FromBody] Album album)
        {
            if (ModelState.IsValid)
            {
                try{
                    AlbumDetail a = await _repository.AddAsync(album);

                    return(CreatedAtRoute(
                               new { controller = "album", action = nameof(Get), id = a.Id }
                               , a));
                }catch (RepositoryException e) {
                    return(BadRequest(new ApiErrorRep(e.Message)));
                }catch (Exception e) {
                    _logger.LogError("AddAlbum", e, "Error adding album");
                    return(StatusCode(500, new ApiErrorRep("Unknown error")));
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Exemple #17
0
        public async void UpdateAlbum_ReturnsTheCorrectNumberOfTracks_WhenOverWritingTracksWithoutValidTrackIds(int numTracks)
        {
            int existingAlbumId = await SetupValidAlbumRecordInDatabase();

            Album a = await this.repo.GetAsync(existingAlbumId);

            List <AlbumTrack> newTracks = new List <AlbumTrack>();

            for (int i = 0; i < numTracks; i++)
            {
                newTracks.Add(new AlbumTrack
                {
                    DurationInSeconds = 100,
                    Title             = "new_title",
                    TrackId           = null, // null id should replace record
                    TrackNumber       = i
                });
            }
            a.Tracks = newTracks;
            AlbumDetail result = await repo.UpdateAsync(existingAlbumId, a);

            Assert.Equal(newTracks.Count, result.Tracks.Count);
        }
        public async Task <IActionResult> Edit(int id)
        {
            AlbumViewModelMapper mapper = new AlbumViewModelMapper();
            EditAlbumViewModel   model  = new EditAlbumViewModel();


            var genresResult = await _genreRepo.ListAsync(contentPublicationFlags : PublishStatus.PUBLISHED);

            var allGroups = await _albumGroupRepo.ListAsync();

            var albumGroupKeys = (await _albumGroupRepo.GetGroupsForAlbum(id)).Select(x => x.Key);


            AlbumDetail album = await _albumRepo.GetAsync(id);

            if (album != null)
            {
                PublishStatus flags = PublishStatus.PUBLISHED | PublishStatus.UNPUBLISHED;
                ICollection <ArtistNameRef> artistNames = await _artistRepo.ListNamesAsync(flags);

                model        = mapper.Map(album, artistNames, genresResult.Genres);
                model.Groups = allGroups.Select(x => new CheckBoxListItem
                {
                    Label      = x.Name,
                    Value      = x.Key,
                    IsSelected = (albumGroupKeys.Contains(x.Key))
                }).ToList();

                return(View(model));
            }
            else
            {
                // todo: show error message
                return(RedirectToAction(nameof(Index)));
            }
        }
Exemple #19
0
        public async void GetAlbum_ReturnsNullWhenNoArtistExists()
        {
            AlbumDetail result = await this.repo.GetAsync(929292);

            Assert.Null(result);
        }
Exemple #20
0
 private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
 {
     ResetColumnCount(e.NewSize.Width);
     AlbumDetail.Measure(AlbumDetail.RenderSize);
 }
        public async Task <IActionResult> Edit(EditAlbumViewModel model)
        {
            AlbumViewModelMapper mapper = new AlbumViewModelMapper();
            PublishStatus        flags  = PublishStatus.PUBLISHED | PublishStatus.UNPUBLISHED;
            var artistNames             = await _artistRepo.ListNamesAsync(flags);

            model.ArtistOptions = artistNames
                                  .Select(x => new SelectListItem
            {
                Text     = x.Name,
                Value    = x.Id.ToString(),
                Selected = x.Id == model.ArtistId
            }).ToList();

            List <CheckBoxListItem> groupOptions = (await _albumGroupRepo.ListAsync())
                                                   .Select(x => new CheckBoxListItem {
                Label      = x.Name,
                Value      = x.Key,
                IsSelected = model.Groups.Any(grp => grp.IsSelected && grp.Value == x.Key)
            }).ToList();

            model.Groups = groupOptions;


            AlbumDetail album = await _albumRepo.GetAsync(model.Id);

            if (album != null)
            {
                // set non postback properties
                model.CoverImageId    = album.CoverImageId;
                model.Created         = album.CreatedUtc;
                model.Updated         = album.UpdatedUtc;
                model.PublishedStatus = album.PublishedStatus;
                if (ModelState.IsValid)
                {
                    int?createdCoverImageId = null;
                    if (model.CoverImage != null && model.CoverImage.Length > 0)
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            await model.CoverImage.CopyToAsync(ms);

                            ImageReferenceDetail imageRef = await _imageRepo.AddAsync(new ImageReferenceDetail
                            {
                                Data     = ms.ToArray(),
                                FileName = model.CoverImage.FileName,
                                MimeType = model.CoverImage.ContentType
                            });

                            if (imageRef != null)
                            {
                                createdCoverImageId = imageRef.Id;
                            }
                        }
                    }

                    album = mapper.MapOnTo(model, album, createdCoverImageId);
                    await _albumRepo.UpdateAsync(album.Id, album);

                    await _albumGroupRepo.SetGroupsForAlbum(model.Id, model.Groups.Where(g => g.IsSelected).Select(g => g.Value).ToList());

                    this.SetBootstrapPageAlert("Success", "Artist updated", BootstrapAlertType.success);
                    return(RedirectToAction(nameof(Index)));
                }
                else
                {
                    return(View(model));
                }
            }
            else
            {
                // todo: show error message
                return(RedirectToAction(nameof(Index)));
            }
        }
Exemple #22
0
        /// <param name='albumId'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        public async Task <HttpOperationResponse <AlbumDetail> > GetByAlbumidWithOperationResponseAsync(int albumId, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            // Tracing
            bool   shouldTrace  = ServiceClientTracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("albumId", albumId);
                ServiceClientTracing.Enter(invocationId, this, "GetByAlbumidAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/api/Albums/";
            url = url + Uri.EscapeDataString(albumId.ToString());
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = new HttpRequestMessage();

            httpRequest.Method     = HttpMethod.Get;
            httpRequest.RequestUri = new Uri(url);

            // Set Credentials
            if (this.Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            }

            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            HttpStatusCode statusCode = httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (statusCode != HttpStatusCode.OK)
            {
                HttpOperationException <object> ex = new HttpOperationException <object>();
                ex.Request  = httpRequest;
                ex.Response = httpResponse;
                ex.Body     = null;
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            HttpOperationResponse <AlbumDetail> result = new HttpOperationResponse <AlbumDetail>();

            result.Request  = httpRequest;
            result.Response = httpResponse;

            // Deserialize Response
            if (statusCode == HttpStatusCode.OK)
            {
                AlbumDetail resultModel = new AlbumDetail();
                JToken      responseDoc = null;
                if (string.IsNullOrEmpty(responseContent) == false)
                {
                    responseDoc = JToken.Parse(responseContent);
                }
                if (responseDoc != null)
                {
                    resultModel.DeserializeJson(responseDoc);
                }
                result.Body = resultModel;
            }

            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return(result);
        }