public IActionResult Album(int id) { currentAlbum = SqlHelper.GetAlbumByID(id); ViewBag.Title = "SLB - Search Listen Buy"; return(View(currentAlbum)); }
public void Edit(AlbumModel model) { var record = _session.Single <Album>(x => x.Id == model.Id); record.Update(model); _session.CommitChanges(); }
public ActionResult GetAlbums(int id) { var album = Context.GetAlbum(id); var model = new AlbumModel(album); return(Json(model)); }
public int UpdateAlbumPost(int postId, IFormCollection data) { var album = new AlbumModel(); int albumId = _postService.GetById(postId).albumId; // Update album image and video if (albumId > 0) { //update album with video and image if (data["images"] != "" || data["video"] != "") { album.idImmagini = data["images"]; album.idVideo = data["video"]; _albumService.Update(albumId, album); } else { //remove album from post _albumService.Delete(albumId); albumId = 0; } } else { //create album albumId = AddAlbumToPost(data); } return(albumId); }
private static int AddTitleArtist(AlbumModel album) { try { using (var connection = SqlHelper.GetConnection()) { var sqlCommand = new SqlCommand(); sqlCommand.Connection = connection; sqlCommand.CommandText = @"Insert INTO Album (Title, Artists) VALUES (@Title, @Artists); SELECT CAST(scope_identity() AS int)" ; sqlCommand.Parameters.Add(new SqlParameter("@Title", album.Title)); sqlCommand.Parameters.Add(new SqlParameter("@Artists", album.Artists)); return((int)sqlCommand.ExecuteScalar()); } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Error: " + e.Message); Console.ResetColor(); return(-1); } }
public IEnumerable <AlbumModel> SearchAlbums(string name) { var albums = new List <AlbumModel>(); try { using (var context = new sparrow_dbEntities()) { var albumList = context.SPRW_ALBUM.Where(i => i.NAME.StartsWith(name)).Take(3); foreach (var album in albumList) { var selectedAlbum = new AlbumModel { // Artist = new ArtistModel // { // AristName = album.SPRW_ARTIST.NAME, // ArtistId = album.ARTIST_ID, // Description = album.SPRW_ARTIST.DESCRP // }, AlbumName = album.NAME, AlbumId = album.ARTIST_ID }; albums.Add(selectedAlbum); } } } catch (Exception e) { } return(albums); }
public async Task <IActionResult> Create([Bind("Name,IdSinger,Image")] AlbumModel album, IFormFile ful) { if (ModelState.IsValid) { album.NameUnsigned = RemoveUnicode(album.Name); _context.Add(album); await _context.SaveChangesAsync(); if (ful != null) { var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot/img/album", album.Id + "." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1]); using (var stream = new FileStream(path, FileMode.Create)) { await ful.CopyToAsync(stream); } album.Image = album.Id + "." + ful.FileName.Split(".")[ful.FileName.Split(".").Length - 1]; _context.Update(album); await _context.SaveChangesAsync(); } return(RedirectToAction(nameof(Index))); } ViewData["IdSinger"] = new SelectList(_context.Singer, "Id", "Name"); ViewBag.Alert = "Tạo mới album không thành công, vui lòng thử lại"; return(View(album)); }
/// <summary> /// 通过AlbumId获取专辑信息(不含歌曲列表) /// </summary> /// <param name="cover">是否覆盖已存在的Artist信息</param> public IAsyncAction GetAlbumInfo(AlbumModel album, bool cover = false) { if (album.XiamiID == 0) { throw new ArgumentException("AlbumModel未设置ID"); } return(Run(async token => { try { LogService.DebugWrite($"Get info of Album {album.XiamiID}", nameof(WapApi)); var gettask = HttpHelper.GetAsync($"http://www.xiami.com/app/xiating/album?id={album.XiamiID}"); token.Register(() => gettask.Cancel()); var content = await gettask; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(content); List <Task> process = new List <Task>();//并行处理 process.Add(Task.Run(() => { if (album.SongList == null || cover) { album.SongList = ParseAlbumSongs(doc.DocumentNode.SelectSingleNode("//div/ul[1]"), album).ToList(); } })); process.Add(Task.Run(() => { if (album.RelateHotAlbums == null || cover) { album.RelateHotAlbums = ParseRelateAlbums(doc.DocumentNode.SelectSingleNode("//h3").NextSibling.NextSibling).ToList(); } })); var infonode = doc.DocumentNode.SelectSingleNode("//section[1]/div[1]/div[2]/div[1]"); if (album.Art.Host == "") { var art = infonode.SelectSingleNode(".//img").GetAttributeValue("src", AlbumModel.SmallDefaultUri); album.Art = new Uri(art); album.ArtFull = new Uri(art.Replace("_1", "")); } album.Name = infonode.SelectSingleNode(".//h2").InnerText; album.Rating = infonode.SelectSingleNode(".//p").InnerText.Remove(0, 4).Trim(); album.ReleaseDate = infonode.SelectSingleNode(".//span/span").InnerText.Remove(0, 5);//TODO: 针对地域进行转换 var artisttag = infonode.SelectSingleNode(".//span/a"); if ((album.Artist == null) || cover) { var idtext = artisttag.GetAttributeValue("onclick", "artist_detail(0);"); var addrlength = "artist_detail(".Length; uint artistID = uint.Parse(idtext.Substring(addrlength, idtext.IndexOf(")", addrlength) - addrlength)); ArtistModel artist = album.Artist ?? ArtistModel.GetNew(artistID); artist.Name = artisttag.InnerText; album.Artist = artist; } await Task.WhenAll(process); LogService.DebugWrite($"Finish Getting info of Album {album.Name}", nameof(WapApi)); } catch (Exception e) { LogService.ErrorWrite(e); throw e; } })); }
//专辑信息比较复杂,只考虑Web public IAsyncAction GetAlbumInfo(AlbumModel album, bool cover = false) { return(Run(async(c) => { await WebApi.Instance.GetAlbumInfo(album, cover); })); }
public AlbumModel GetAlbum(int albumId) { try { var albumModel = new AlbumModel(); using (var context = new sparrow_dbEntities()) { var album = context.SPRW_ALBUM.FirstOrDefault(i => i.ALBUM_ID == albumId); if (album != null) { albumModel.AlbumId = album.ALBUM_ID; albumModel.AlbumName = album.NAME; var tracks = new List <TrackModel>(); foreach (var track in album.SPRW_TRACK) { var trackModel = new TrackModel { TrackId = track.TRACK_ID, TrackName = track.NAME }; tracks.Add(trackModel); } albumModel.Tracks = tracks; } } return(albumModel); } catch (Exception e) { throw e; } }
public IEnumerable <SongModel> InitPlaylistE() { //以下为测试代码 for (int i = 0; i < 6; i++) { SongModel sm = SongModel.GetNew(1775616994); if (i == 0) { sm.Name = $"Foundations (Original Mix)"; sm.Album = AlbumModel.GetNew(2100274906); //sm.MediaUri = new Uri(@"ms-appx:///Assets/Ring01.wma"); ExtensionMethods.InvokeAndWait(async() => sm.MediaUri = new Uri(await Net.DataApi.GetDownloadLink(sm, false))); sm.Album.Art = new Uri("http://img.xiami.net/images/album/img35/105735/21002749061455506376_2.jpg"); sm.Album.ArtFull = new Uri("http://img.xiami.net/images/album/img35/105735/21002749061455506376.jpg"); } yield return(sm); sm = SongModel.GetNew(1771503325); if (i == 0) { sm.Name = $"Give My Regards"; sm.Album = AlbumModel.GetNew(504506); //sm.MediaUri = new Uri(@"ms-appx:///Assets/Ring02.wma"); ExtensionMethods.InvokeAndWait(async() => sm.MediaUri = new Uri(await Net.DataApi.GetDownloadLink(sm, false))); sm.Album.Art = new Uri("http://img.xiami.net/images/album/img35/105735/5045061333262175_2.jpg"); sm.Album.ArtFull = new Uri("http://img.xiami.net/images/album/img35/105735/5045061333262175.jpg"); } yield return(sm); } }
public RequestResult GetAlbumPaginated(AlbumModel albumModel) { var result = new RequestResult(StatusResult.Success); try { using (var unitOfWork = UnitOfWorkFactory.CreateUnitOfWork()) { var albumQuantidade = unitOfWork.Repository.Count <Album>(x => x.GeneroId == albumModel.GeneroId).Result; var albumList = unitOfWork.Repository.Get <Album>(x => x.GeneroId == albumModel.GeneroId).OrderBy(x => x.Nome) .Skip(albumModel.Skip) .Take(albumModel.Take).ToList(); var resultPaginated = new AlbumResponse { Albuns = albumList, Quantidade = albumQuantidade }; result.Data = resultPaginated; } } catch (Exception ex) { result.Status = StatusResult.Danger; result.Messages.Add(new Message(string.Format(_localizer["UnexpectedError"], ex.Message))); } return(result); }
public ActionResult Album(int id) { var album = _albumService.GetAllAlbumWithPhotos().FirstOrDefault(a => a.ID == id); var albumModel = new AlbumModel() { ID = album.ID, UID = album.UID, Name = album.Name, Comment = album.Comment, CreatedBy = album.CreatedBy, DateCreated = album.DateCreated, Photos = album .Photos .OrderBy(p => p.ID) .Select(p => new PhotoModel() { ID = p.ID, FileName = p.FileName, Name = p.Name, CreatedBy = p.CreatedBy, IsDeleted = p.IsDeleted, UID = p.UID }) }; return(View(albumModel)); }
public JsonResult SaveAlbum(AlbumModel album) { var sessionId = this.Session["SessionID"].ToString(); IUserSessionRepository userSessionRepository = RepositoryClassFactory.GetInstance().GetUserSessionRepository(); UserSession userSession = userSessionRepository.FindByID(sessionId); if (userSession == null) { return(Json(new { errorCode = (int)ErrorCode.Redirect, message = Resources.AdminResource.msg_sessionInvalid }, JsonRequestBehavior.AllowGet)); } InsertResponse response = new InsertResponse(); album.Title = album.Title.Length > 200 ? album.Title.Substring(0, 100) + "..." : album.Title; if (!string.IsNullOrEmpty(album.Description)) { album.Description = album.Description.Length > 300 ? album.Description.Substring(0, 296) + "..." : album.Description; } else { album.Description = null; } album.ActionURL = string.Format("{0}-{1}", UrlSlugger.ToUrlSlug(album.Title), UrlSlugger.Get8Digits()); album.CreatedDate = DateTime.Now; album.AlbumID = Guid.NewGuid().ToString(); album.CreatedBy = userSession != null ? userSession.UserID : string.Empty; response = _albumService.CreateAlbum(album); return(Json(new { errorCode = response.ErrorCode, message = response.Message }, JsonRequestBehavior.AllowGet)); }
public async Task <ServiceResult> Add(AlbumResultModel model) { var serviceResult = new ServiceResult(); var songsResult = model.Songs == null || model.Songs.Count == 0 ? new DatabaseManyResult <SongModel>() { Success = true, Entities = null } : await _songRepository.GetMany(model.Songs, 0, 50); if (!songsResult.Success) { serviceResult.Error.Code = ErrorStatusCode.BudRequest; serviceResult.Error.Description = songsResult.Message; return(serviceResult); } var artistsResult = model.Artists == null || model.Artists.Count == 0 ? new DatabaseManyResult <ArtistModel>() { Success = true, Entities = null } : await _artistRepository.GetMany(model.Artists, 0, 50); if (!artistsResult.Success) { serviceResult.Error.Code = ErrorStatusCode.BudRequest; serviceResult.Error.Description = artistsResult.Message; return(serviceResult); } var genresResult = model.Genres == null || model.Genres.Count == 0 ? new DatabaseManyResult <GenreModel>() { Success = true, Entities = null } : await _genreRepository.GetMany(model.Genres, 0, 50); if (!genresResult.Success) { serviceResult.Error.Code = ErrorStatusCode.BudRequest; serviceResult.Error.Description = genresResult.Message; return(serviceResult); } var modelObject = new AlbumModel() { Id = model.Id, Name = model.Name, ArtId = model.ArtId, Songs = songsResult.Entities, Artists = artistsResult.Entities, Genres = genresResult.Entities }; var result = await _albumRepository.Add(modelObject); serviceResult.Success = result.Success; if (!result.Success) { serviceResult.Error.Code = ErrorStatusCode.BudRequest; serviceResult.Error.Description = result.Message; } return(serviceResult); }
public async Task <IActionResult> BigAlbum() { var photoCount = 0; //自己实现的Request的扩展方法 var formValueProvider = await Request.StreamFile((file) => { photoCount++; return(System.IO.File.Create($@"{_folder}\{file.FileName}")); }); var model = new AlbumModel { Title = formValueProvider.GetValue("title").ToString(), Date = Convert.ToDateTime(formValueProvider.GetValue("date").ToString()) }; // ... return(Ok(new { title = model.Title, date = model.Date.ToString("yyyy/MM/dd"), photoCount = photoCount })); }
public IHttpActionResult Update(int id, AlbumModel album) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var existingAlbum = this.data .Albums .All() .FirstOrDefault(alb => alb.Id == id); if (existingAlbum == null) { return(BadRequest("Album with id: " + id + " do not exists!")); } existingAlbum.Title = album.Title; existingAlbum.Year = album.Year; existingAlbum.Producer = album.Producer; this.data.SaveChanges(); album.Id = existingAlbum.Id; return(Ok(album)); }
public ActionResult Detail(AlbumModel model) { if (ModelState.IsValid) { var album = new Album() { Id = model.Id, ArtistId = model.ArtistId, Name = model.Name, Type = (MusicalogAlbumService.AlbumType)model.Type, Label = model.Label, Stock = model.Stock }; using (MusicalogAlbumServiceClient client = new MusicalogAlbumServiceClient()) { var artistsDto = album.Id > 0 ? client.UpdateAlbum(album.Id, album) : client.CreateAlbum(album); if (artistsDto.Id > 0) { ViewBag.Message = string.Format("Album has been {0} successfuly.", album.Id > 0 ? "saved" : "created"); if (model.Id == 0) { ModelState.Clear(); model = new AlbumModel(); } initializeStaticDatas(model); return(View(model)); } } } initializeStaticDatas(model); return(View(model)); }
public void RaiseAlbumCreated(AlbumModel album) { if (AlbumCreated != null) { AlbumCreated(this, new AlbumCreatedEventArgs(album)); } }
public void Delete(int id) { var photo = _photoService.GetById(id); var folderName = _commonService.cleanStringPath(_photoFolderService.GetById(photo.folderId).name); //remove photo from album var albums = _albumService.GetAll(); foreach (var album in albums) { var images = album.idImmagini.Split('|').Where(x => x != id.ToString()).ToArray(); var newAlbumImages = ""; foreach (var image in images) { newAlbumImages = string.Concat(newAlbumImages, image, "|"); } var newAlbum = new AlbumModel(); if (newAlbumImages.Length > 0) { newAlbum.idImmagini = newAlbumImages.Remove(newAlbumImages.Length - 1); } else { newAlbum.idImmagini = ""; } newAlbum.idVideo = album.idVideo; _albumService.Update(album.id, newAlbum); } var filePath = string.Concat("Content\\Images\\", folderName, "\\", photo.name); _fileService.Delete(filePath); _photoService.Delete(id); }
public RequestResult <AlbumModel> DeleteAlbum(AlbumModel albumModel) { if (albumModel == null || albumModel.Id == 0) { return(new RequestResult <AlbumModel>(HttpStatusCode.BadRequest)); } if (!repository.AlbumExists(albumModel.Id)) { return(new RequestResult <AlbumModel>(HttpStatusCode.NotFound)); } if (HasSongs(albumModel.Id)) { var songResult = songService.DeleteSong(albumModel.Id); if (songResult.Status != HttpStatusCode.OK) { return(new RequestResult <AlbumModel>("Cannot delete Album's Songs")); } } var result = repository.DeleteAlbum(albumModel.Id); return(new RequestResult <AlbumModel>()); }
private Album CreateAlbum(AlbumModel album, List <TrackModel> tracks) { var a = CreateAlbum(album); a.Tracks = new List <Track>(from t in tracks select CreateTrack(album, t)); return(a); }
public AlbumModel GetAlbum(int id) { var result = new AlbumModel(); var album = repository.GetAlbum(id); if (album == null) { return(null); } Mapper.CreateMap <Album, AlbumModel>(); result = Mapper.Map <AlbumModel>(album); var albumSongs = repository.GetSong(id); if (!albumSongs.IsNotNullOrEmpty()) { return(result); } Mapper.CreateMap <Song, SongModel>(); List <SongModel> songs = new List <SongModel>(); foreach (var albumSong in albumSongs) { var song = Mapper.Map <SongModel>(albumSong); songs.Add(song); } result.Songs = songs; return(result); }
public ActionResult Create(PhotoModel photo, HttpPostedFileBase[] filesToBeUploaded) { //why is the photo id and album id same? int albumId = photo.PhotoModelId; AlbumModel album = EntityModelMapper.EntityToModel(AlbumRepo.Get(albumId)); foreach (var file in filesToBeUploaded) { //set important properties of the new photo object PhotoModel currentPhoto = new PhotoModel() { //PhotoId = Guid.NewGuid(), Name = photo.Name, FileName = file.FileName, DateCreated = DateTime.Now, Description = "[no description set]", UploadedBy = album.User.Username, Comments = new List <CommentModel>(), }; //physically saves copie(s) of the photos to the path specified file.SaveAs(Server.MapPath("~/UsersData/" + album.User.Username + "/" + album.Name + "/" + file.FileName)); //saves the photo object to the album object //todo: should not this be saved to the static list of a users album photos immediately? album.Photos.Add(currentPhoto); } ; return(RedirectToAction("Index", "Home")); //return PartialView("_Photos",/*allphotos*/); }
public AlbumModel GetAlbumId(int rathoreDetailId) { AlbumModel result = new AlbumModel(); return(result); }
public void Put(int id, [FromBody] AlbumModel value) { var album = this.data.Get(id); value.UpdateAlbum(album); this.data.Update(id, album); }
private static int AddExtraArtistList(AlbumModel album) { try { int result = -1; foreach (ArtistModel artist in album.ExtraArtists) { using (var connection = SqlHelper.GetConnection()) { var sqlCommand = new SqlCommand(); sqlCommand.Connection = connection; sqlCommand.CommandText = @"Insert INTO ExtraArtists (Name, Role, Title, AlbumID) VALUES (@Name, @Role, @Title, @AlbumID); SELECT CAST(scope_identity() AS int)" ; sqlCommand.Parameters.Add(new SqlParameter("@Role", artist.Role)); sqlCommand.Parameters.Add(new SqlParameter("@Name", artist.Name)); sqlCommand.Parameters.Add(new SqlParameter("@Title", artist.AlbumTitle)); sqlCommand.Parameters.Add(new SqlParameter("@AlbumID", album.ID)); result = (int)sqlCommand.ExecuteScalar(); } } return(result); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error: " + e.Message); Console.ResetColor(); return(-1); } }
//更新相册 protected void UpateAlbum(int id) { string[] _fileurl = Request.Params.GetValues("txtpicpath"); //文件路径,修改时没有 string[] _fileid = Request.Params.GetValues("txtpicid"); //id string[] _fileintro = Request.Params.GetValues("txtpicintro"); //说明 string[] _filepx = Request.Params.GetValues("txtpicpx"); //排序 if (_fileid != null && _fileintro != null && _fileid != null) { for (int i = 0; i < _fileid.Length; i++) { AlbumModel am = new AlbumModel(); am.ModelId = mid; am.ParentId = id; am.PhotoUrl = _fileurl[i]; am.Intro = _fileintro[i]; am.AddTime = DateTime.Now; am.id = BasePage.GetRequestId(_fileid[i]); am.Px = BasePage.GetRequestId(_filepx[i]); if (BasePage.GetRequestId(_fileid[i]) == 0) { int ai = new AlbumBll().Add(am); } else { bool b = new AlbumBll().Update(am); } } } }
public static bool AlbumExists(AlbumModel album) { try { using (var connection = SqlHelper.GetConnection()) { var sqlCommand = new SqlCommand(); sqlCommand.Connection = connection; sqlCommand.CommandText = @"Select AlbumID from Album where Title= @Title and Artists = @Artists"; sqlCommand.Parameters.Add(new SqlParameter("@Title", album.Title)); sqlCommand.Parameters.Add(new SqlParameter("@Artists", album.Artists)); if ((sqlCommand.ExecuteScalar() is null)) { return(false); } return(true); } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Error: " + e.Message); Console.ResetColor(); return(false); } }
public static void New(AlbumModel album) { album.AlbumID = _albums.Count + 1; album.Artist = ArtistService.GetAll().First(a => a.ArtistID == album.ArtistID)?.Title; _albums.Add(album); }
private static int AddStyles(AlbumModel album) { try { int result = -1; for (int i = 0; i <= album.Styles.Count - 1; i++) { using (var connection = SqlHelper.GetConnection()) { var sqlCommand = new SqlCommand(); sqlCommand.Connection = connection; sqlCommand.CommandText = @"Insert INTO Styles (Style, AlbumID) VALUES (@Style, @AlbumID); SELECT CAST(scope_identity() AS int)" ; sqlCommand.Parameters.Add(new SqlParameter("@Style", album.Styles[i])); sqlCommand.Parameters.Add(new SqlParameter("@AlbumID", album.ID)); result = (int)sqlCommand.ExecuteScalar(); } } return(result); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Error: " + e.Message); Console.ResetColor(); return(-1); } }
public static AlbumModel Convert(Album album) { AlbumModel model = new AlbumModel { AlbumId = album.AlbumId, AlbumTitle = album.AlbumTitle, AlbumYear = album.AlbumYear, Producer = album.Producer, ArtistsCount = album.Artists.Count, SongsCount = album.Songs.Count }; return model; }
public static void CreateAlbumDirectory(AlbumModel model) { CreateUserDirectory(model.User); string path = AlbumPath(model); if (Directory.Exists(path)) System.Diagnostics.Debug.WriteLine(string.Format("Folder albumu {0} istnieje", model.Id)); else { System.Diagnostics.Debug.WriteLine(string.Format("Tworze folder albumu {0}", model.Id)); Directory.CreateDirectory(path); } System.Diagnostics.Debug.WriteLine(string.Format("Sciezka {0}", path)); }
public static List<string> AlbumThumbnails(AlbumModel album) { List<PhotoModel> photos = new List<PhotoModel>(album.Photos); photos.Sort(delegate(PhotoModel a, PhotoModel b) { return a.Date.CompareTo(b.Date); }); List<string> result = new List<string>(photos.Count); foreach (PhotoModel photo in photos) { result.Add(PhotoThumbnail(photo)); } return result; }
public IHttpActionResult Add(AlbumModel albumModel) { if (!this.ModelState.IsValid) { return BadRequest(ModelState); } var newAlbum = AlbumModel.ToAlbum(albumModel); this.data.Albums.Add(newAlbum); this.data.SaveChanges(); albumModel.ID = newAlbum.ID; return Ok(albumModel); }
//Zwraca sciezki(wzgledne, nie fizyczne) do miniaturek, //sortuje wzgledem daty utworzenia na dysku! zle, uzywac funkcji z Helpers public static List<string> GetAlbumThumbnail(AlbumModel album) { DirectoryInfo dir = new DirectoryInfo(AlbumPath(album)); FileSystemInfo[] files = dir.GetFileSystemInfos("*_mini.jpg"); Array.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b) { return a.CreationTime.CompareTo(b.CreationTime); }); List<string> list = new List<string>(); foreach (FileSystemInfo file in files) { list.Add(AlbumPath(album, false) + file.Name); } return list; }
public IHttpActionResult Create(AlbumModel album) { if (!this.ModelState.IsValid) { return BadRequest(this.ModelState); } var newAlbum = new Album() { Title = album.Title, Year = album.Year, Producer = album.Producer }; this.data.Albums.Add(newAlbum); this.data.SaveChanges(); album.AlbumId = newAlbum.AlbumId; return Ok(album); }
public static void AlbumDateRange(AlbumModel album, out string start, out string end) { start = ""; end = ""; if (album.Photos.Count == 0) return; DateTime startD = album.Photos.First().Date; DateTime endD = album.Photos.First().Date; foreach (PhotoModel photo in album.Photos) { if (photo.Date < startD) startD = photo.Date; else if (photo.Date > endD) endD = photo.Date; } start = startD.ToString("dd/MM/yyyy"); end = endD.ToString("dd/MM/yyyy"); }
public IHttpActionResult Update(int id, AlbumModel album) { if (!this.ModelState.IsValid) { return BadRequest(this.ModelState); } var albumToUpdate = this.data.Albums .All() .FirstOrDefault(a => a.AlbumId == id); if (albumToUpdate == null) { return BadRequest("The album with id: " + id + " does not exists."); } albumToUpdate.Producer = album.Producer; albumToUpdate.Title = album.Title; albumToUpdate.Year = album.Year; this.data.SaveChanges(); album.AlbumId = albumToUpdate.AlbumId; return Ok(album); }
public static void GetDate(AlbumModel album, out string start, out string end) { DirectoryInfo dir = new DirectoryInfo(AlbumPath(album)); if (!dir.Exists) { CreateAlbumDirectory(album); } FileSystemInfo[] files = dir.GetFileSystemInfos("*_mini.jpg"); Array.Sort<FileSystemInfo>(files, delegate(FileSystemInfo a, FileSystemInfo b) { return a.CreationTime.CompareTo(b.CreationTime); }); if (files.Length == 0) { start = ""; end = ""; return; } start = files.First().CreationTime.ToString("dd/MM/yyyy"); end = files.Last().CreationTime.ToString("dd/MM/yyyy"); }
public static bool isFollower(AlbumModel album, UserModel user) { foreach (UserModel follower in album.Followers) { if (follower.Id == user.Id) return true; } return false; }
public void Edit(AlbumModel model) { var record = _session.Single<Album>(x=>x.Id == model.Id); record.Update(model); _session.CommitChanges(); }
private static void CreateAlbums() { UserRepository users = new UserRepository(); UserModel user = users.GetByUsername("Klocu"); AlbumRepository albums = new AlbumRepository(); CategoryModel category=null; using (var session = SessionProvider.SessionFactory.OpenSession()) { category=session.CreateQuery("from CategoryModel where Name =:name").SetParameter("name","People").UniqueResult<CategoryModel>(); } AlbumModel album = new AlbumModel() { Category = category, CommentsAllow = true, CommentsAuth = false, Description = "Jak zmieniałem się w czasie", Name = "Moja twarz", Public = true, Rating = 0, User = user, Views = 1234 }; albums.Create(album); LinkedList<PhotoModel> list = new LinkedList<PhotoModel>(); PhotoModel photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 1, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/photo_2012051022444645.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011,4,30,22,33,5), Description = "Oto ja", Path = "/Static/photos/photo_2012051022450267.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2012, 2,28 , 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/photo_2012051022452109.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 8, 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/20110108.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 15, 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/20110115.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 22, 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/20110122.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 1, 29, 1, 8, 59), Description = "Oto ja", Path = "/Static/photos/20110129.jpg" }; list.AddLast(photo); album = new AlbumModel() { Category = category, CommentsAllow = true, CommentsAuth = false, Description = "", Name = "Widok za moin oknem", Public = true, Rating = 0, User = user, Views = 2 }; albums.Create(album); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2011-12-29 06.48.45.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2012-04-30 18.07.20.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2012-04-30 18.07.35.jpg" }; list.AddLast(photo); album = new AlbumModel() { Category = category, CommentsAllow = true, CommentsAuth = false, Description = "Zmieniający się rynek", Name = "Zmieniający się rynek", Public = true, Rating = 0, User = user, Views = 111 }; albums.Create(album); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2011-12-29 06.48.45.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2012-04-30 18.07.20.jpg" }; list.AddLast(photo); photo = new PhotoModel() { Album = album, Date = new DateTime(2011, 4, 30, 22, 33, 5), Description = "Oto ja", Path = "/Static/photos/2012-04-30 18.07.35.jpg" }; list.AddLast(photo); /* album = new AlbumModel() { Category = category, CommentsAllow = true, CommentsAuth = false, Description = "Jak zmieniałem się w czasie", Name = "Moja twarz", Public = true, Rating = 0, User = user, Views = 1234 }; */ using(var session= SessionProvider.SessionFactory.OpenSession()) using (var trans = session.BeginTransaction()) { foreach (PhotoModel p in list) session.Save(p); trans.Commit(); } }
public void Add(AlbumModel model) { _session.Add(model); }
public void Delete(AlbumModel model) { _session.Delete(model); }
public IAsyncAction GetAlbumInfo(AlbumModel album, bool cover = true) { if (album.XiamiID == 0) throw new ArgumentException("AlbumModel未设置ID"); return Run(async token => { try { LogService.DebugWrite($"Get info of Album {album.XiamiID}", nameof(WebApi)); var gettask = HttpHelper.GetAsync($"http://www.xiami.com/album/{album.XiamiID}"); token.Register(() => gettask.Cancel()); var content = await gettask; HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(content); var body = doc.DocumentNode.SelectSingleNode("/html/body/div[@id='page']"); List<Task> process = new List<Task>(); process.Add(Task.Run(() => { var listnode = body.SelectSingleNode(".//table[@id='track_list']"); if (album.SongList == null || cover) album.SongList = ParseAlbumSongs(listnode, album).ToList(); else ParseAlbumSongs(listnode, album.SongList); }, token)); var title = body.SelectSingleNode(".//h1"); if (album.Name == null || cover) album.Name = title.FirstChild.InnerText; if (title.LastChild.NodeType != HtmlNodeType.Element) if (album.Description == null || cover) album.Description = title.LastChild.InnerText; var info = body.SelectSingleNode(".//div[@id='album_info']"); album.Rating = info.SelectSingleNode(".//em").InnerText; var ratings = info.SelectNodes(".//ul/li"); for (int i = 0; i < ratings.Count; i++) album.RatingDetail[i] = int.Parse(ratings[i].LastChild.InnerText); var loveop = body.SelectSingleNode(".//ul[@class='acts_list']"); album.IsLoved = loveop.SelectSingleNode("./li[1]").GetAttributeValue("style", "") == "display:none"; var share = loveop.SelectSingleNode(".//em").InnerText; album.ShareCount = int.Parse(share.Substring(1, share.Length - 2)); foreach (var item in info.SelectNodes(".//tr")) { var tds = item.SelectNodes("./td"); switch (tds[0].InnerText) { case "艺人:": if (album.Artist == null) album.Artist = ArtistModel.GetNew(ParseXiamiID(tds[1].SelectSingleNode(".//a").GetAttributeValue("href", "/0"))); break; case "语种:": album.Language = tds[1].InnerText; break; case "唱片公司:": album.Publisher = tds[1].InnerText; break; case "发行时间": album.ReleaseDate = tds[1].InnerText; break; case "专辑类别": album.Type = tds[1].InnerText; break; case "专辑风格": album.Genre = tds[1].SelectNodes("./a").Select((node) => { var gen = GenreModel.GetNew(ParseXiamiID(node.GetAttributeValue("href", "/0"))); gen.Name = node.InnerText; return gen; }).ToList(); break; } } if (album.Art.Host == "") { var art = body.SelectSingleNode(".//img"); album.Art = new Uri(art.GetAttributeValue("src", AlbumModel.SmallDefaultUri)); album.ArtFull = new Uri(art.ParentNode.GetAttributeValue("href", AlbumModel.LargeDefaultUri)); } if (album.Introduction == null || cover) album.Introduction = body.SelectSingleNode(".//span[@property='v:summary']")?.InnerText?.Replace("<br />", ""); await Task.WhenAll(process); LogService.DebugWrite($"Finishi Getting info of Album {album.XiamiID}", nameof(WebApi)); } catch (Exception e) { LogService.ErrorWrite(e, nameof(WebApi)); throw e; } }); }
public static string getPhotoPathWithoutExtension(AlbumModel album, string photoName) { return AlbumPath(album, false) + photoName; }
// handles private access settings from form private UserModel[] SetPrivateAccess(AlbumModel album) { UserModel[] userModels = null; //an array of trusted users if (album.Public) { // make sure we dont read anything from 'password' field album.Password = null; } else switch (Request["privateMode"]) { case "password": if (album.Password != null) album.Password = album.Password.HashMD5(); else ModelState.AddModelError("Password", "You didn't provide a password"); break; case "users": album.Password = null; //nullify password, because its checkbox was not ticked if (string.IsNullOrEmpty(Request["usersList"])) { ModelState.AddModelError("Users", "You didn't provide a user list"); break; } string[] userLogins = Request["usersList"].Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); userModels = AlbumModel.FindUsersByLogins(userLogins); if (userModels == null) ModelState.AddModelError("Users", "At least one login you provided is incorrect."); else album.TrustedUsers = userModels; break; default: // album visible only to owner album.Password = null; //nullify password, because its checkbox was not ticked break; } return userModels; }
public static string AlbumPath(AlbumModel model, bool physical = true) { return UserPath(model.User, physical) + AlbumSubdirectoryPrefix + model.Id + "/"; }
public AlbumCreatedEventArgs(AlbumModel album) : base() { this.NewAlbum = album; }
public IHttpActionResult Update(int id, AlbumModel albumModel) { if (!this.ModelState.IsValid) { return BadRequest(ModelState); } var existingAlbum = this.data.Albums.Get(id); if (existingAlbum == null) { return BadRequest(BabRequestMessage); } AlbumModel.ToAlbum(albumModel, existingAlbum); this.data.Albums.Update(existingAlbum); this.data.SaveChanges(); return Ok(albumModel); }
public AlbumModel LookupAlbumById(int albumId) { if (albumLookupDictionary.ContainsKey(albumId)) { return albumLookupDictionary[albumId]; } else { AlbumTable albumTable = DatabaseManager.Current.LookupAlbumById(albumId); if (albumTable == null) { return null; } else { AlbumModel albumModel = new AlbumModel(albumTable); albumLookupDictionary.Add(albumModel.AlbumId, albumModel); return albumModel; } } }
public AlbumModel LookupAlbumByName(string albumName, int albumArtistId) { AlbumTable albumTable = DatabaseManager.Current.LookupAlbum(albumName, albumArtistId); if (albumTable == null) { AlbumTable newAlbum = new AlbumTable(string.Empty, albumArtistId, albumName, 0); DatabaseManager.Current.AddAlbum(newAlbum); AlbumModel albumModel = new AlbumModel(newAlbum); albumLookupDictionary.Add(albumModel.AlbumId, albumModel); RaiseAlbumCreated(albumModel); return albumModel; } else { return LookupAlbumById(albumTable.AlbumId); } }
private void LoadCollection() { PerfTracer perfTracer = new PerfTracer("LibraryModel Loading"); IEnumerable<SongTable> allSongs = DatabaseManager.Current.FetchSongs(); foreach (SongTable songEntry in allSongs) { SongModel songModel = new SongModel(songEntry); _allSongs.Add(songModel); songLookupDictionary.Add(songModel.SongId, songModel); } perfTracer.Trace("Songs Added"); IEnumerable<AlbumTable> allAlbums = DatabaseManager.Current.FetchAlbums(); foreach (AlbumTable albumEntry in allAlbums) { AlbumModel albumModel = new AlbumModel(albumEntry); _allAlbums.Add(albumModel); albumLookupDictionary.Add(albumModel.AlbumId, albumModel); } perfTracer.Trace("Albums Added"); IEnumerable<ArtistTable> allArtists = DatabaseManager.Current.FetchArtists(); foreach (ArtistTable artistEntry in allArtists) { ArtistModel artistModel = new ArtistModel(artistEntry); _allArtists.Add(artistModel); artistLookupDictionary.Add(artistModel.ArtistId, artistModel); } perfTracer.Trace("Artists Added"); IEnumerable<PlaylistTable> allPlaylists = DatabaseManager.Current.FetchPlaylists(); foreach (PlaylistTable playlistEntry in allPlaylists) { PlaylistModel playlistModel = new PlaylistModel(playlistEntry); Playlists.Add(playlistModel); playlistLookupDictionary.Add(playlistModel.PlaylistId, playlistModel); playlistModel.Populate(); } perfTracer.Trace("Playlists Added"); IEnumerable<MixTable> allMixes = DatabaseManager.Current.FetchMixes(); foreach (MixTable mixEntry in allMixes) { MixModel mixModel = new MixModel(mixEntry); Mixes.Add(mixModel); mixLookupDictionary.Add(mixModel.MixId, mixModel); mixModel.Populate(); } perfTracer.Trace("Mixes Added"); }
public static void NotifyAlbumObservers(AlbumModel album) { UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext); Uri requestUrl = url.RequestContext.HttpContext.Request.Url; foreach (UserModel follower in album.Followers) { if (follower.NotifySubscription) { string link = string.Format( "{0}://{1}{2}", requestUrl.Scheme, requestUrl.Authority, url.Action("Show", "Album", new { id = album.Id }) ); SendEmail(follower.Email, string.Format("{0} has added new photo", album.User.Login), string.Format("Dear {0},<br/>{1} has added new photo. If you want to see updates please follow this <a href=\"{2}\">link</a>", follower.Login, album.User.Login, link) ); } } }
public static string SavePhoto(Image img, AlbumModel album, string name) { CreateAlbumDirectory(album); if (!IsJPEG(img)) throw new FileUploadException("You must upload jpeg image."); using (Image transformed = Helpers.TransformWithAspectRatio(img, MAX_WIDTH, MAX_HEIGHT, false)) { EncoderParameters encoderParameters = new EncoderParameters(1); using (encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L)) { using (Image thumbnail = Helpers.TransformWithAspectRatio(transformed, THUMB_WIDTH, THUMB_HEIGHT, true)) { System.Diagnostics.Debug.WriteLine(AlbumPath(album) + name + "_mini.jpg"); thumbnail.Save(AlbumPath(album) + name + "_mini.jpg", GetEncoder(ImageFormat.Jpeg), encoderParameters); } name += ".jpg"; transformed.Save(AlbumPath(album) + name, GetEncoder(ImageFormat.Jpeg), encoderParameters); } return AlbumPath(album, false) + name; } }
public static void RemindPhoto(AlbumModel album) { }
internal IEnumerable<SongModel> ParseAlbumSongs(HtmlNode listnode, AlbumModel album) { string disc = null; foreach (var item in listnode.SelectNodes("./tbody/tr")) { if (item.SelectSingleNode("./td/strong") != null) disc = item.InnerText; else { SongModel song = SongModel.GetNew(uint.Parse(item.SelectSingleNode(".//input").GetAttributeValue("value", "0"))); song.Album = album; song.DiscID = disc; song.TrackID = int.Parse(item.ChildNodes[3].InnerText); ParsePlayListSong(song, item); //var title = songitem.SelectSingleNode(".//a"); //if (song.Name == null) // song.Name = title.InnerText; //if (song.TrackArtist == null) //{ // string t = title.NextSibling.InnerText.Trim(); // if (t.Length > 0) // song.TrackArtist = t; //} yield return song; } } }
private void SetNextNotification(AlbumModel album) { //next notification if (Request["reminder"] == "remindYes") { System.DateTime today = System.DateTime.Now; try { int tmp = Int32.Parse(Request["NotificationPeriod"]); System.DateTime answer = today.AddDays(tmp); album.NextNotification = answer; } catch (Exception) { ModelState.AddModelError("NotificationPeriod", "Number of days is incorrect"); } } else { album.NextNotification = null; album.NotificationPeriod = null; ModelState.Clear(); //clear errors TryValidateModel(album); //revalidate } }
/// <summary> /// 播放专辑 /// </summary> public async void PlayAlbum(AlbumModel album) { if (album == null) return; if (album.SongList == null) await Net.WebApi.Instance.GetAlbumInfo(album); PlaylistService.Instance.Clear(); PlaylistService.Instance.AddAlbum(album); PlayTrack(); }