コード例 #1
0
        public async Task <SongDto> IncreaseSongPopularityAsync(Guid id)
        {
            _logger?.LogDebug("'{0}' has been invoked", MethodBase.GetCurrentMethod().DeclaringType);
            var response = new SongDto();

            if (ModelState.IsValid)
            {
                try
                {
                    _logger?.LogInformation("The IncreaseSongPopularityAsync have been retrieved successfully.");

                    var song = await _albumRepository.IncreaseSongPopularityAsync(id);

                    return(_mapper.Map <SongDto>(song));
                }
                catch (Exception ex)
                {
                    _logger?.LogCritical("There was an error on '{0}' invocation: {1}", MethodBase.GetCurrentMethod().DeclaringType, ex);
                    return(response = new SongDto {
                        ErrorMessage = new string[] { ex.Message }
                    });
                }
            }
            else
            {
                return response = new SongDto {
                           ErrorMessage = new string[] { "ModelState is not valid: " + ModelState.ToString() }
                }
            };
        }
コード例 #2
0
        public async Task <IHttpActionResult> Post([FromBody] SongDto songDto)
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var guid     = Guid.NewGuid().ToString();
            var filePath = Path.Combine(
                HostingEnvironment.MapPath("~/" + UploadsFolder),
                guid);

            var provider = new MultipartFormDataStreamProvider(filePath);
            await Request.Content.ReadAsMultipartAsync(provider);

            var inStream = provider.GetStream(Request.Content, Request.Content.Headers);

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await inStream.CopyToAsync(fileStream);

                if (inStream.Length == 0)
                {
                    return(BadRequest("File is empty"));
                }
            }

            songDto.FileName = guid;
            _songsService.Insert(songDto);

            return(Ok());
        }
コード例 #3
0
 public IActionResult Delete(int id)
 {
     try
     {
         var songToDelete = _context.Songs.Where(s => s.Id == id).FirstOrDefault();
         if (songToDelete != null)
         {
             SongDto copyOfSong = new SongDto {
                 Id     = songToDelete.Id,
                 Album  = songToDelete.Album,
                 Title  = songToDelete.Title,
                 Artist = songToDelete.Artist
             };
             _context.Remove(songToDelete);
             _context.SaveChanges();
             return(StatusCode(200, copyOfSong));
         }
         else
         {
             return(StatusCode(400));
         }
     }
     catch
     {
         return(StatusCode(500));
     }
 }
コード例 #4
0
ファイル: SongDao.cs プロジェクト: dagofonseca/music
        public Response <IEnumerable <SongDto> > SelectAll()
        {
            List <SongDto> response = new List <SongDto>();

            try
            {
                using (musicDBEntities db = new musicDBEntities())
                {
                    List <Song> songs = db.Song.ToList();

                    foreach (Song song in songs)
                    {
                        SongDto aux = new SongDto(song.song_id, song.title, song.genre, song.released, song.duration,
                                                  song.fk_album_id.GetValueOrDefault(), song.fk_artist_id.GetValueOrDefault());

                        response.Add(aux);
                    }
                }
                return(new Response <IEnumerable <SongDto> >(true, response.Count + " Songs found", response));
            }
            catch (Exception e)
            {
                if (e.InnerException == null)
                {
                    return(new Response <IEnumerable <SongDto> >(false, "Somethig was wrong. Exception: " + e.Message, response));
                }
                else
                {
                    return(new Response <IEnumerable <SongDto> >(false, "Somethig was wrong. Exception: " + e.InnerException.InnerException.Message, response));
                }
            }
        }
コード例 #5
0
ファイル: SongController.cs プロジェクト: mamcer/soulstone-2
        public HttpResponseMessage Get(int id)
        {
            try
            {
                using (var unitOfWork = new UnitOfWork())
                {
                    var result = unitOfWork.SongRepository.Get(id);

                    var songDto = new SongDto
                    {
                        Id       = result.Id,
                        Album    = result.Album,
                        Artist   = result.Artist,
                        Bitrate  = result.Bitrate,
                        Duration = result.Duration,
                        Genre    = result.Genre,
                        Title    = result.Title,
                        Year     = result.Year.HasValue ? result.Year.Value : 0
                    };

                    return(Request.CreateResponse(HttpStatusCode.OK, songDto));
                }
            }
            catch (Exception ex)
            {
                IocUnityContainer.Instance.Resolve <ILogManager>().DefaultLogger.Error.Write(ex.Message, ex);
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
コード例 #6
0
ファイル: SongDao.cs プロジェクト: dagofonseca/music
        public Response <SongDto> FindById(int id)
        {
            if (id <= 0)
            {
                return(new Response <SongDto>(false, "Id must be grater than 0", null));
            }

            SongDto response;

            try
            {
                using (musicDBEntities db = new musicDBEntities())
                {
                    Song song = db.Song.Find(id);
                    response = new SongDto(song.song_id, song.title, song.genre, song.released, song.duration,
                                           song.fk_album_id.GetValueOrDefault(), song.fk_artist_id.GetValueOrDefault());
                }
                return(new Response <SongDto>(true, "Song was find", response));
            }
            catch (Exception e)
            {
                if (e.InnerException == null)
                {
                    return(new Response <SongDto>(false, "Somethig was wrong. Exception: " + e.Message, null));
                }
                else
                {
                    return(new Response <SongDto>(false, "Somethig was wrong. Exception: " + e.InnerException.InnerException.Message, null));
                }
            }
        }
コード例 #7
0
        public async Task <IActionResult> PutSong(int id, SongDto song)
        {
            song.Id = id;

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest());
            }

            var isUnique = this.songsService.IsUnique(song.Name, id);

            if (isUnique == false)
            {
                return(this.BadRequest("Already song with that name"));
            }

            var result = await this.songsService.Update(id, song);

            if (result == false)
            {
                return(this.NotFound());
            }


            return(NoContent());
        }
コード例 #8
0
        private async Task AddSong(object item, SongDto selectedSong)
        {
            var playlistSongDto = new PlaylistSongDto
            {
                Song     = selectedSong,
                Position = _playlist.Count + 1
            };

            using (var client = new HttpClient())
            {
                InitializeClient(client);
                var response = await client.PostAsJsonAsync <PlaylistSongDto>(string.Format("playlists/{0}/songs", _selectedPlaylist.Id), playlistSongDto).ConfigureAwait(false);

                if (response.IsSuccessStatusCode)
                {
                    lstPlaylist.Items.Add(item);
                    _playlist.Add(playlistSongDto);
                    lblPlaylistSongs.Text = string.Format("Total {0} songs", _playlist.Count);
                }
                else
                {
                    ShowErrorMessage(GetErrorMessageFromResponse(response));
                }
            }
        }
コード例 #9
0
        public async Task <int> Add(SongDto input)
        {
            var existsWithName = this.repository.All()
                                 .Where(x => x.Name == input.Name)
                                 .FirstOrDefault();

            if (existsWithName != null)
            {
                return(-1);
            }

            var song = new Song()
            {
                Name      = input.Name,
                Genre     = input.Genre,
                WriterId  = (int)input.WriterId,
                AlbumId   = (int)input.AlbumId,
                Price     = input.Price,
                Duration  = input.Duration,
                CreatedOn = input.CreatedOn
            };

            await this.repository.AddAsync(song);

            await this.repository.SaveChangesAsync();

            var id = this.repository.All()
                     .Where(x => x.Name == song.Name)
                     .FirstOrDefault().Id;

            return(id);
        }
コード例 #10
0
ファイル: SongManager.cs プロジェクト: dagofonseca/music
 private Response <SongDto> ValidateSong(SongDto song)
 {
     if (song == null)
     {
         return(new Response <SongDto>(false, "Song cannot be null", null));
     }
     else if (!ValidateAlbum(song))
     {
         return(new Response <SongDto>(false, "Album is not valid", null));
     }
     else if (!ValidateArtist(song))
     {
         return(new Response <SongDto>(false, "Artist is not valid", null));
     }
     else if (!ValidateReleased(song))
     {
         return(new Response <SongDto>(false, "Year release must be less than Album's year release", null));
     }
     else if (!ValidateTitle(song))
     {
         return(new Response <SongDto>(false, "Title cannot be empty", null));
     }
     else if (!ValidateGenre(song))
     {
         return(new Response <SongDto>(false, "Genre cannot be empty", null));
     }
     else
     {
         return(new Response <SongDto>(true, "Song Valid", song));
     }
 }
コード例 #11
0
        public void Insert(SongDto songDto)
        {
            var song = new Song()
            {
                Duration   = songDto.Duration,
                FileName   = songDto.FileName,
                Title      = songDto.SongTitle,
                MeanTempo  = songDto.MeanTempo,
                MeanEnergy = songDto.MeanEnergy,
                Artist     = GetSongArtist(songDto),
                SongMarks  = new List <SongMark>()
                {
                    new SongMark()
                    {
                        Energy = Convert.ToInt32(songDto.MeanEnergy),
                        Tempo  = Convert.ToInt32(songDto.MeanTempo)
                    }
                }
            };

            _repositoryHolder.SongRepository.Insert(song);

            _uof.Save();
            _tagsService.AddTagsToSong(song, songDto.Tags);
        }
コード例 #12
0
        public async Task Post(SongDto model)
        {
            var mapped = _mapper.Map <Song>(model);

            _repository.Song.Create(mapped);
            await _repository.SaveAsync();
        }
コード例 #13
0
    private bool SongSearchMatches(SongDto songDto)
    {
        string searchText = songSearchTextField.value.ToLowerInvariant();

        return(searchText.IsNullOrEmpty() ||
               songDto.Title.ToLowerInvariant().Contains(searchText) ||
               songDto.Artist.ToLowerInvariant().Contains(searchText));
    }
コード例 #14
0
ファイル: Song.cs プロジェクト: niklashaetty/wevalidate
 public static Either <string, Song> Validate(SongDto songDto)
 {
     return
         (from validId in Id.Validate(songDto.Id)
          from validArtist in Artist.Validate(songDto.Artist)
          from validAlbum in Album.Validate(songDto.Album)
          select new Song(validId, validArtist, validAlbum));
 }
コード例 #15
0
 public SongDto MarkSongToBePlayed(SongDto song)
 {
     if (song is not null)
     {
         Songs[song]++;
     }
     return(song);
 }
コード例 #16
0
ファイル: Song.cs プロジェクト: khiemcaleb/Chorder
 public void Modify(SongDto dto)
 {
     Title  = dto.Title;
     Key    = dto.Key;
     Artist = dto.Artist;
     Author = dto.Author;
     Year   = dto.Year;
 }
コード例 #17
0
ファイル: SongManager.cs プロジェクト: dagofonseca/music
        private bool ValidateReleased(SongDto song)
        {
            AlbumDto album     = dalAlb.FindById(song.AlbumId).Data;
            int      albumYear = album.Released;
            int      songYear  = song.Released;

            return(songYear <= albumYear);
        }
コード例 #18
0
 public IHttpActionResult UpdateSongById(int songId, [FromBody] SongDto song)
 {
     if (!ModelState.IsValid)
     {
         throw new ModelValidationException("Song was not properly formatted.");
     }
     return(Ok(_songService.UpdateSongById(songId, song)));
 }
コード例 #19
0
        public int CreateSong(SongDto songDto)
        {
            var song = _mapper.Map <Song>(songDto);

            _uow.Songs.Create(song);
            _uow.Complete();
            return(song.Id);
        }
コード例 #20
0
        public ActionResult Save([FromBody] JObject json)
        {
            var s    = JObject.Parse(json.ToString());
            var song = SongDto.FromJson(s);

            //Console.WriteLine(song);
            _ss.Save(song);
            return(Ok());
        }
コード例 #21
0
ファイル: SongDao.cs プロジェクト: killnine/Hymnstagram
        public void Insert(SongDto dto)
        {
            if (dto == null)
            {
                return;
            }

            _logger.LogInformation("Inserting 'Song' record {@dto}", dto);
            DataSource.Songs.Add(dto);
        }
コード例 #22
0
        public static SongDto Map(Song song)
        {
            SongDto songDto = new SongDto()
            {
                Id   = song.Id,
                Name = song.Name
            };

            return(songDto);
        }
コード例 #23
0
        public static Song Map(SongDto songDto)
        {
            Song song = new Song()
            {
                Id   = songDto.Id,
                Name = songDto.Name
            };

            return(song);
        }
コード例 #24
0
        public IActionResult Post([FromBody] SongDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var id = _songService.CreateSong(dto);

            return(Ok(new { id }));
        }
コード例 #25
0
        public ActionResult <Song> PostSong(SongDto songDto)
        {
            var result = _songService.Add(songDto);

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

            return(CreatedAtAction("GetSong", new { id = result.ResultData.Id }, songDto));
        }
コード例 #26
0
        /// <summary>
        /// Creates song with category that corresponds with given name
        /// </summary>
        /// <param name="song">song</param>
        /// <param name="albumName">category name</param>
        public async Task <Guid> CreateSongWithAlbumNameAsync(SongDto song, string albumName)
        {
            using (var uow = UnitOfWorkProvider.Create())
            {
                song.AlbumId = (await albumService.GetAlbumIdsByNamesAsync(albumName)).FirstOrDefault();
                var productId = songService.Create(song);
                await uow.Commit();

                return(productId);
            }
        }
コード例 #27
0
 public IActionResult Create([FromBody] SongDto song)
 {
     if (!song.IsValid())
     {
         return(BadRequest());
     }
     if (songService.Create(song))
     {
         return(NoContent());
     }
     return(BadRequest());
 }
コード例 #28
0
        public ActionResult Create(SongDto song)
        {
            song.AuthorId = Current.UserId;
            if (!ModelState.IsValid)
            {
                return(View(song));
            }
            ISongsRepository <SongDto> songsRepo = Container.Resolve <ISongsRepository <SongDto> >(DefaultRepository);

            songsRepo.Create(song);
            return(RedirectToAction("Index"));
        }
コード例 #29
0
ファイル: SongManager.cs プロジェクト: dagofonseca/music
        public Response <SongDto> Create(SongDto newObject)
        {
            Response <SongDto> resp = ValidateSong(newObject);

            if (resp.Status == true)
            {
                Response <int> dataResponse = dal.Insert(newObject);
                newObject.Id = dataResponse.Data;
                return(new Response <SongDto>(dataResponse.Status, dataResponse.Message, newObject));
            }
            return(resp);
        }
コード例 #30
0
 public IActionResult Update([FromRoute] int id, [FromBody] SongDto song)
 {
     if (!song.IsValid())
     {
         return(BadRequest());
     }
     song.Id = id;
     if (songService.Update(song))
     {
         return(NoContent());
     }
     return(BadRequest());
 }
コード例 #31
0
        // PUT api/Songs/5
        public HttpResponseMessage PutSong(int id, SongDto song)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            var songToUpdate = db.Songs.FirstOrDefault(s => s.SongId == id);

            if (songToUpdate != null && song != null)
            {
                songToUpdate.UpdateWith(new Song
                {
                    SongTitle = song.SongTitle,
                    SongYear = song.SongYear,
                    Genre = song.Genre
                });
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(songToUpdate).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }