/// <summary>
        /// Delete the object to which this behavior belongs from the data store and optionally the file system.
        /// </summary>
        /// <param name="deleteFromFileSystem">Indicates whether to delete the file or directory from the hard drive in addition
        /// to deleting it from the data store. When true, the object is deleted from both the data store and hard drive. When
        /// false, only the record in the data store is deleted.</param>
        public void Delete(bool deleteFromFileSystem)
        {
            if (deleteFromFileSystem)
            {
                DeleteFromFileSystem(this._albumObject);
            }
            else
            {
                DeleteSupportFilesOnly(this._albumObject);
            }

            if (this._albumObject.IsRootAlbum)
            {
                // Don't delete the root album; just its contents.
                DeleteAlbumContents(deleteFromFileSystem);
            }
            else
            {
              using (var repo = new AlbumRepository())
              {
                repo.Delete(this._albumObject);
              repo.Save();
              }
            }
        }
示例#2
0
        public ActionResult AcceptComment(int id)
        {
            AlbumRepository albums = new AlbumRepository();
            CommentModel comment = albums.GetComment(id, true);
            UserRepository users = new UserRepository();
            UserModel user = users.GetByUsername(HttpContext.User.Identity.Name);
            string[] response = new string[2];

            if (user != null)
            {
                if (comment.Album.User.Id == user.Id) //ok
                {
                    response[0] = "ok";
                    response[1] = "";
                    comment.Accepted = true;
                    albums.Update(comment);
                }
                else
                {
                    response[0] = "error";
                    response[1] = "You are not allowed to accept this comment.";
                }
            }
            else
            {
                response[0] = "error";
                response[1] = "You need to be logged in to accept comments";
            }

            return Json(response);
        }
示例#3
0
        public void Execute(IJobExecutionContext context)
        {
            System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString()+" Executing photo notification job");
            AlbumRepository repo = new AlbumRepository();
            List<AlbumModel> albums = repo.GetAll();

            string path = context.JobDetail.JobDataMap.GetString("path");
            foreach(AlbumModel album in albums)
            {
                if (album.User.NotifyPhoto && album.NotificationPeriod!=null)
                {
                    DateTime time = album.NextNotification ?? DateTime.Today;
                    time = time.Date; //Data, godziny niepotrzebne
                    if (time <= DateTime.Today)
                    //if (time <= DateTime.Now)
                    {
                        album.NextNotification = DateTime.Today.AddDays(album.NotificationPeriod ?? 1);
                        //album.NextNotification = time.AddMinutes(album.NotificationPeriod * unit ?? 1);
                        repo.Update(album);

                        string link = path + "/Album/AddPhoto?albumId="+album.Id;

                        string body = string.Format("Hello {0},</br>It's time to add new photo to your album <a href='{1}'>{2}</a>",
                            album.User.Login,link,album.Name);
                        Helpers.SendEmailContextFree(album.User.Email, "Photo notification", body);
                    }

                }
            }
        }
        public ActionResult Describe(int id)
        {
            UserModel authUser = (User.Identity.IsAuthenticated ?
                new UserRepository().GetByUsername( User.Identity.Name ) : null);

            // check if album with given id exists
            AlbumRepository albums = new AlbumRepository();
            AlbumModel album = albums.GetById( id,
                withUser: true, withPhotos: true, withComments: true, withCategory: true, withTrustedUsers: true );
            if ( album == null )
                throw new Exception( "album not found" );

            // check if the caller can access the album
            if ( !albums.IsUserAuthorizedToViewAlbum( album, authUser, false ) )
                throw new Exception( "user not authorized to view this album" );

            // prepare photos list
            List<string> photos = new List<string>();
            foreach ( PhotoModel photo in album.Photos )
            {
                photos.Add( string.Format( "{0}/api/photos/{1}", Helpers.BaseURL(), photo.Id ) );
            }

            // prepare comments list
            List<Object> comments = new List<Object>();
            foreach ( CommentModel comment in album.Comments )
            {
                comments.Add( new
                {
                    author = comment.User.Login,
                    date = new
                    {
                        day = comment.Date.Day,
                        month = comment.Date.Month,
                        year = comment.Date.Year
                    },
                    body = comment.Body
                } );
            }

            // send back the album information
            return Json( new
            {
                ok = true,
                data = new
                {
                    id = album.Id,
                    name = album.Name,
                    description = album.Description,
                    category = album.Category.Name,
                    owner = album.User.Login,
                    is_public = album.Public,
                    rating = album.Rating,
                    views = album.Views,
                    photos = photos,
                    comments = comments
                }
            }, JsonRequestBehavior.AllowGet );
        }
        public async Task<Album> Album([FromBody] Album postedAlbum)
        {
            if (!ModelState.IsValid)            
                throw new ApiException("Model binding failed.",500);

            var albumRepo = new AlbumRepository(context);
            return await albumRepo.SaveAlbum(postedAlbum);

        }
示例#6
0
        public void MultitableFindTest()
        {
            // 'FindMultiple' function uses a query with INNER JOIN to avoid a second trip to the DB
            var albumRepo = new AlbumRepository();
            Guid uniqueId;
            Guid.TryParse("02545961-2a64-4fdd-8c4d-7cc8bd5c6857", out uniqueId);
            var album = albumRepo.FindMultitable(uniqueId);

            Debug.Assert(album.Id != null);
        }
示例#7
0
        public void SingleValuedReferenceTest()
        {
            // 'Find' function does two DB trips to get all info needed to return an album object.
            var albumRepo = new AlbumRepository();
            Guid uniqueId;
            Guid.TryParse("5e26185b-3de9-478b-b764-48d50a8944b0", out uniqueId);
            var album = albumRepo.Find(uniqueId);

            Debug.Assert(album.Id != null);
        }
        public async Task<Album> Album([FromBody] Album postedAlbum)
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
                throw new ApiException("You have to be logged in to modify data", 401);

            if (!ModelState.IsValid)            
                throw new ApiException("Model binding failed.",500);

            var albumRepo = new AlbumRepository(context);
            return await albumRepo.SaveAlbum(postedAlbum);
        }
示例#9
0
 public SqlDAL()
 {
     DBContext = new AlbumsDBModel();
     _albumRepository = new AlbumRepository(DBContext);
     _roleRepository = new RoleRepository(DBContext);
     _userRepository = new UserRepository(DBContext);
     _commentRepository = new CommentRepository(DBContext);
     _likeRepository = new LikeRepository(DBContext);
     _albumsPhotoRepository = new AlbumsPhotoRepository(DBContext);
     _photoRepository = new PhotoRepository(DBContext);
 }
示例#10
0
        public void CollectionReferenceTest()
        {
            // 'CollectionReferenceTest' function loads a collection referenced by an entity. Even when the entities in the collection
            // references the initial entity, the mapping implementation breaks the posibble infinite loop in which the loading process
            // could fall.
            var albumRepo = new AlbumRepository();
            Guid uniqueId;
            Guid.TryParse("d10826ce-5dc2-44e3-8ff7-b3d72bf4a2c0", out uniqueId);
            var albums = albumRepo.FindBy(uniqueId);

            Debug.Assert(albums.Count > 0);
        }
示例#11
0
        /// <summary>
        /// Assigns the specified <paramref name="galleryId" /> to the <paramref name="albums" />,
        /// acting recursively on all child albums.
        /// </summary>
        /// <param name="albums">The albums whose gallery is to be updated.</param>
        /// <param name="galleryId">The new gallery ID.</param>
        private static void AssignNewGalleryId(IEnumerable<IGalleryObject> albums, int galleryId)
        {
            foreach (IAlbum childAlbum in albums)
              {
            childAlbum.GalleryId = galleryId;
            //Factory.GetDataProvider().Album_Save(childAlbum);
            using (var repo = new AlbumRepository())
            {
              repo.Save(childAlbum);
            }

            AssignNewGalleryId(childAlbum.GetChildGalleryObjects(GalleryObjectType.Album), galleryId);
              }
        }
示例#12
0
        public HomeViewModel(SmugMugClient client, INavigationManager navigation, AlbumRepository albums)
        {
            _navigation = navigation;
            _albums = albums;
            _client = client;
            client.Key = "2FjugTuMjAMckx4VxwhunnjG4AAEwvGU";
            client.Secret = "2d23eecf34defb9b7a2cda639e2e9ffc";
            client.Callback = "http://vikingco.de";
            Groups.Add(albumgroup);
            Groups.Add(_popular);
            Load();

            AddAlbum = new DelegateCommand(() =>
                {

                });
        }
示例#13
0
        public ActionResult Index()
        {
            @ViewBag.Category = MainCategory.Home;
            List<HomepageAlbumModel> models = new List<HomepageAlbumModel>();
            AlbumRepository repo = new AlbumRepository();

            models.Add(new HomepageAlbumModel()
            {
                Name = "Popular",
                Albums = Helpers.Convert(repo.GetMostPopular(ALBUMS_IN_CATEGORY))
            });

            models.Add(new HomepageAlbumModel()
            {
                Name = "Top rated",
                Albums = Helpers.Convert(repo.GetTopRated(ALBUMS_IN_CATEGORY))
            });

            models.Add(new HomepageAlbumModel()
            {
                Name = "Random",
                Albums = Helpers.Convert(repo.GetRandom(ALBUMS_IN_CATEGORY))
            });

            models.Add(new HomepageAlbumModel()
            {
                Name = "Biggest",
                Albums = Helpers.Convert(repo.GetBiggest(ALBUMS_IN_CATEGORY))
            });

            models.Add(new HomepageAlbumModel()
            {
                Name = "Recently commented",
                Albums = Helpers.Convert(repo.GetRecentlyCommented(ALBUMS_IN_CATEGORY))
            });

            models.Add(new HomepageAlbumModel()
            {
                Name = "Most commented",
                Albums = Helpers.Convert(repo.GetMostCommented(ALBUMS_IN_CATEGORY))
            });

            return View(models);
        }
示例#14
0
        public ActionResult Describe(string userName)
        {
            UserModel authUser = (User.Identity.IsAuthenticated ?
                new UserRepository().GetByUsername( User.Identity.Name ) : null);

            userName = HttpUtility.UrlDecode( userName ).Trim();
            if ( userName == string.Empty )
                throw new Exception( "empty username" );

            UserRepository users = new UserRepository();
            UserModel user = users.GetByUsernameWithAlbums( userName, withTrustedUsers:true );
            if ( user == null )
                throw new Exception( "user not found" );

            AlbumRepository albumRepository = new AlbumRepository();
            List<string> albums = new List<string>();
            foreach ( AlbumModel album in user.Albums )
            {
                if ( albumRepository.IsUserAuthorizedToViewAlbum( album, authUser, false ) )
                {
                    albums.Add( string.Format( "{0}/api/albums/{1}", Helpers.BaseURL(), album.Id ) );
                }
            }

            return Json( new
            {
                ok = true,
                data = new
                {
                    id = user.Id,
                    username = user.Login,
                    date_of_birth = (user.DateOfBirth.HasValue ? new
                    {
                        day = user.DateOfBirth.Value.Day,
                        month = user.DateOfBirth.Value.Month,
                        year = user.DateOfBirth.Value.Year
                    } : null),
                    about = user.About,
                    albums = albums
                }
            }, JsonRequestBehavior.AllowGet );
        }
示例#15
0
        public ActionResult Describe(int id)
        {
            UserModel authUser = (User.Identity.IsAuthenticated ?
                new UserRepository().GetByUsername( User.Identity.Name ) : null);

            // check if photo with given id exists
            PhotoRepository photos = new PhotoRepository();
            PhotoModel photo = photos.GetById( id, withAlbum: true );
            if ( photo == null )
                throw new Exception( "photo not found" );

            // check if the caller can access the album containing the photo
            AlbumRepository albums = new AlbumRepository();
            AlbumModel album = albums.GetById( photo.Album.Id, withUser: true, withTrustedUsers: true );
            if ( !albums.IsUserAuthorizedToViewAlbum( album, authUser, false ) )
                throw new Exception( "user not authorized to view this photo/album" );

            // send back the photo information
            return Json( new
            {
                ok = true,
                data = new
                {
                    id = photo.Id,
                    album = string.Format( "{0}/api/albums/{1}", Helpers.BaseURL(), album.Id ),
                    date = new
                    {
                        day = photo.Date.Day,
                        month = photo.Date.Month,
                        year = photo.Date.Year
                    },
                    description = photo.Description,
                    image = Helpers.BaseURL() + photo.Path,
                    thumbnail = Helpers.BaseURL() + photo.Path.Substring(0, photo.Path.LastIndexOf(".jpg")) + "_mini.jpg",
                    latitude = photo.LocationLatitude,
                    longitude = photo.LocationLongitude
                }
            }, JsonRequestBehavior.AllowGet );
        }
示例#16
0
        /// <summary>
        /// Persist the object to which this behavior belongs to the data store. Also persist to the file system, if
        /// the object has a representation on disk, such as albums (stored as directories) and media objects (stored
        /// as files). New objects with ID = int.MinValue will have a new <see cref="IGalleryObject.Id"/> assigned
        /// and <see cref="IGalleryObject.IsNew"/> set to false.
        /// All validation should have taken place before calling this method.
        /// </summary>
        public void Save()
        {
            if (this._albumObject.IsVirtualAlbum)
            return; // Don't save virtual albums.

              // Must save to disk first, since the method queries properties that might be updated when it is
              // saved to the data store.
              PersistToFileSystemStore(this._albumObject);

              // Save to the data store.
              //Factory.GetDataProvider().Album_Save(this._albumObject);
              using (var repo = new AlbumRepository())
              {
            repo.Save(this._albumObject);
              }

              if (this._albumObject.GalleryIdHasChanged)
              {
            // Album has been assigned to a new gallery, so we need to iterate through all
            // its children and update those gallery IDs as well.
            AssignNewGalleryId(this._albumObject.GetChildGalleryObjects(GalleryObjectType.Album), this._albumObject.GalleryId);
              }
        }
示例#17
0
        public async Task<string> DeleteAlbumByName(string name)
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
                throw new ApiException("You have to be logged in to modify data", 401);

            var repo = new AlbumRepository(context);

            var pks = await context.Albums.Where(alb => alb.Title == name).Select(alb => alb.Id).ToListAsync();

            StringBuilder sb = new StringBuilder();
            foreach (int pk in pks)
            {
                bool result = await repo.DeleteAlbum(pk);
                if (!result)
                    sb.AppendLine(repo.ErrorMessage);
            }

            return sb.ToString();
        }
示例#18
0
        public async Task<bool> DeleteArtist(int id)
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
                throw new ApiException("You have to be logged in to modify data", 401);


            var db = new AlbumRepository(context);
            return await db.DeleteArtist(id);
        }
示例#19
0
        public async Task<IEnumerable<object>> ArtistLookup(string search = null)
        {
            if (string.IsNullOrEmpty(search))
                return new List<object>();
            
            var db = new AlbumRepository(context);

            var term = search.ToLower();
            var artists = await db.Context.Artists
                                  .Where(a => a.ArtistName.ToLower().StartsWith(term))
                                  .Select(a=> new
                                  {
                                      name = a.ArtistName,
                                      id=a.ArtistName                                      
                                  })
                                  .ToListAsync();

            return artists;
        }
示例#20
0
        public async Task<ArtistResponse> Artist([FromBody] Artist postedArtist)
        {
            if (!HttpContext.User.Identity.IsAuthenticated)
                throw new ApiException("You have to be logged in to modify data",401);

            var db = new AlbumRepository(context);
            var artist = await db.SaveArtist(postedArtist);

            if (artist == null)
                throw new ApiException("Unable to save artist.");

            return new ArtistResponse()
            {
                Artist = artist,
                Albums = await db.Context.Albums
                    .Include(a=> a.Tracks)
                    .Include(a=> a.Artist)            
                    .Where(a => a.ArtistId == artist.Id).ToListAsync()
            };
        }
示例#21
0
        public void Save()
        {
            Database db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase();

            if (_artist.ArtistId == 0)
            {
                //ADD ARTIST
                IRepository<IArtist> artist = new ArtistRepository(db);
                IRepositoryBLL<IArtist> artistRepoBll = new ArtistRepositoryBLL(artist);
                _artist = artistRepoBll.Add(_artist);

                //ADD ARTIST CONTACT
                IRepository<IArtistContact> contact1 = new ArtistContactRepository(db);
                IRepositoryBLL<IArtistContact> contactBll = new ArtistContactRepositoryBLL(contact1);
                _artistContact.ArtistId = _artist.ArtistId;
                _artistContact = contactBll.Add(_artistContact);

                //ADD DISCOGRAPHY
                IRepository<IDiscography> disco = new DiscographyRepository(db);
                IRepositoryBLL<IDiscography> discoBll = new DiscographyRepositoryBLL(disco);
                _discography.ArtistId = _artist.ArtistId;
                _discography = discoBll.Add(_discography);
            }

            if (_album.AlbumId == 0)
            {
                //ADD ALBUM
                IRepository<IAlbum> album1 = new AlbumRepository(db);
                IRepositoryBLL<IAlbum> albumBll = new AlbumRepositoryBLL(album1);
                _album.ArtistId = _artist.ArtistId;
                _album = albumBll.Add(_album);
            }

            //ADD SONGS
            IRepository<ISong> song1 = new SongRepository(db);
            IRepositoryBLL<ISong> songBll = new SongRepositoryBLL(song1);
            foreach (Song item in _songs)
            {
                item.AlbumId = _album.AlbumId;
                songBll.Add(item);
            }
        }
示例#22
0
        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();
            }
        }
        private IEnumerable<IGalleryObject> GetAlbumsHavingTitleOrCaption()
        {
            var galleryObjects = new GalleryObjectCollection();

            var metaTagsToSearch = new[] { MetadataItemName.Title, MetadataItemName.Caption };

            using (var repo = new AlbumRepository())
            {
                var qry = repo.Where(a => true, a => a.Metadata);

                qry = SearchOptions.SearchTerms.Aggregate(qry, (current, searchTerm) => current.Where(a =>
                    a.FKGalleryId == SearchOptions.GalleryId &&
                    a.Metadata.Any(md => metaTagsToSearch.Contains(md.MetaName) && md.Value.Contains(searchTerm))));

                qry = RestrictForCurrentUser(qry);

                foreach (var album in qry)
                {
                    galleryObjects.Add(Factory.GetAlbumFromDto(album));
                }
            }

            return galleryObjects;
        }
        private IEnumerable<IGalleryObject> GetAlbumsMatchingKeywords()
        {
            var galleryObjects = new GalleryObjectCollection();

            using (var repo = new AlbumRepository())
            {
                var qry = repo.Where(a => true, a => a.Metadata);

                qry = SearchOptions.SearchTerms.Aggregate(qry, (current, searchTerm) => current.Where(a =>
                    a.FKGalleryId == SearchOptions.GalleryId &&
                    a.Metadata.Any(md => md.Value.Contains(searchTerm))));

                qry = RestrictForCurrentUser(qry);

                foreach (var album in qry)
                {
                    galleryObjects.Add(Factory.GetAlbumFromDto(album));
                }
            }

            return galleryObjects;
        }
示例#25
0
 /// <summary>
 /// Obtiene el album por su nombre de artista y nombre de album
 /// </summary>
 /// <param name="albumTitle">Nombre de Album</param>
 /// <param name="artistTitle">Nombre de Artista</param>
 /// <returns>Retorna el Album en caso de existir, de otra forma retorna null</returns>
 private Album GetAlbumByTitleAndArtistTitle(string albumTitle, string artistTitle)
 {
     AlbumRepository repository = new AlbumRepository();
     List<Album> albums = repository.GetAlbumsByName(albumTitle);
     Album album=null;
     foreach (var a in albums)
     {
         if (a.Artist.Title.Equals(artistTitle))
             album = a;
     }
     repository.Dispose();
     return album;
 }
        /// <summary>
        /// Gets the <paramref name="top" /> most recently added albums, skipping the first
        /// <paramref name="skip" /> objects. Only albums the current user is authorized to
        /// view are returned.
        /// </summary>
        /// <param name="top">The number of items to retrieve.</param>
        /// <param name="skip">The number of items to skip over in the data store.</param>
        /// <returns><see cref="IEnumerable&lt;IGalleryObject&gt;" />.</returns>
        private IEnumerable<IGalleryObject> GetRecentlyAddedAlbums(int top, int skip = 0)
        {
            var galleryObjects = new GalleryObjectCollection();

            using (var repo = new AlbumRepository())
            {
                var qry = RestrictForCurrentUser(repo.Where(mo => mo.FKGalleryId == SearchOptions.GalleryId)
                    .OrderByDescending(m => m.DateAdded))
                    .Skip(skip).Take(top)
                    .Include(m => m.Metadata);

                foreach (var album in qry)
                {
                    galleryObjects.Add(Factory.GetAlbumFromDto(album));
                }
            }

            return galleryObjects;
        }
示例#27
0
        public ActionResult UploadNew(API.Models.NewPhotoModel photo)
        {
            if ( !User.Identity.IsAuthenticated )
                throw new Exception( "user not authenticated" );
            UserModel authUser = new UserRepository().GetByUsername( User.Identity.Name );

            // # Validate request

            // photo.AlbumID: album has to exist, has to be owned by authenticated user
            AlbumRepository albums = new AlbumRepository();
            AlbumModel album = albums.GetById( photo.AlbumID, withUser: true, withFollowers: true );
            if ( album == null )
                throw new Exception( "album with specified ID not found" );
            if ( album.User != authUser )
                throw new Exception( "authenticated user is not the owner of the specified album" );

            // photo.Date: can't be set in the future
            if ( photo.Date == null )
                throw new Exception( "date of the photo hasn't been specified" );
            if ( photo.Date > DateTime.Now )
                throw new Exception( "date of the photo can't be set in the future" );

            // photo.Description: can't be longer than 1000 characters
            if ( photo.Description != null && photo.Description.Length > 1000 )
                throw new Exception( "description of the photo can't be longer that 1000 characters" );

            // photo.Image: has to be valid base-64 encoded binary file, has to be valid image
            Image image;
            try
            {
                image = ApiHelpers.Base64ToImage( photo.Image.Replace("\n", "") );
            }
            catch (System.Exception ex)
            {
                throw new Exception( "provided image file is invalid: " + ex.Message );
            }

            string path;
            double? locLatitude;
            double? locLongitude;

            using ( image )
            {
                // photo.Image: has to be a valid JPEG
                if ( !image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg) )
                    throw new Exception( "provided image file is not of JPEG format" );

                // # New photo successfully validated - process

                // generate path for the image
                string photoName = "photo_" + DateTime.Now.ToString( "yyyyMMddHHmmssff" );
                path = FileHelper.getPhotoPathWithoutExtension( album, photoName ) + ".jpg";
                if ( string.IsNullOrEmpty( path ) )
                    throw new Exception( "failed to generate path for the image" );

                // save the photo to the file system
                try
                {
                    path = FileHelper.SavePhoto( image, album, photoName );
                }
                catch ( System.Exception ex )
                {
                    throw new Exception( "failed to save the image to the file system: " + ex.Message );
                }
                if ( string.IsNullOrEmpty( path ) )
                    throw new Exception( "failed to save the image to the file system" );

                // try to read GPS localization data
                if (photo.LocationLatitude.HasValue && photo.LocationLongitude.HasValue)
                {
                    locLatitude = photo.LocationLatitude;
                    locLongitude = photo.LocationLongitude;
                }
                else
                {
                    locLatitude = image.GPSLatitude();
                    locLongitude = image.GPSLongitude();
                }
            }

            // create photo entity
            PhotoModel newPhoto = new PhotoModel()
            {
                Path = path,
                Date = photo.Date,
                Description = photo.Description,
                Album = album
            };
            if ( locLatitude.HasValue && locLongitude.HasValue )
            {
                newPhoto.LocationLatitude = locLatitude.Value;
                newPhoto.LocationLongitude = locLongitude.Value;
            }

            // save the entity to the database
            try
            {
                new PhotoRepository().Create( newPhoto );
            }
            catch (System.Exception ex)
            {
                // TODO: delete both the image and its thumbnail from the file system
                throw new Exception( "failed to save the photo to the database: " + ex.Message );
            }

            Helpers.NotifyAlbumObservers(newPhoto.Album);

            // return result
            return Json( new
            {
                ok = true,
                data = new
                {
                    photo = string.Format( "{0}/api/photos/{1}", Helpers.BaseURL(), newPhoto.Id )
                }
            } );
        }
        public RepositoryRegistry()
        {
            For<ICredentialRepository>()
                .Use(factory =>
                {
                    return new CredentialRepository(factory.GetInstance<Entities>());
                });

            For<IProfileRepository>()
                .Use(factory =>
                {
                    var repository = new ProfileRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IProfileActivityRepository>()
                .Use(factory =>
                {
                    var repository = new ProfileActivityRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IGrunkerRepository>()
                .Use(factory =>
                {
                    var repository = new GrunkerRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IActivityTypeRepository>()
                .Use(factory =>
                {
                    var repository = new ActivityTypeRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IPictureRepository>()
                .Use(factory =>
                {
                    var repository = new PictureRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IGenreRepository>()
                .Use(factory =>
                {
                    var repository = new GenreRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IArtistRepository>()
                .Use(factory =>
                {
                    var repository = new ArtistRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IAlbumRepository>()
                .Use(factory =>
                {
                    var repository = new AlbumRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IPurchaseRepository>()
                .Use(factory =>
                {
                    var repository = new PurchaseRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IReviewRepository>()
                .Use(factory =>
                {
                    var repository = new ReviewRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IReviewLinkRepository>()
                .Use(factory =>
                {
                    var repository = new ReviewLinkRepository(factory.GetInstance<Entities>());
                    return repository;
                });

            For<IStoreDetailsRepository>()
                .Use(factory =>
                {
                    var repository = new StoreDetailsRepository(HttpContext.Current.Server.MapPath("~/App_Data/storedetails.xml"));
                    return repository;
                });

            For<IStaticTextRepository>()
                .Use(factory =>
                {
                    var repository = new StaticTextRepository(factory.GetInstance<Entities>());
                    return repository;
                });
        }
示例#29
0
        /// <summary>
        /// Metodo encargado de interactuar con la capa de datos para realizar las inserciones en la base de datos local
        /// </summary>
        /// <param name="tracksToInsert">Lista de tracks por ingresar</param>
        private void InsertIntoDatabase(List<TrackInfo> tracksToInsert)
         {
            ArtistRepository artistRepo = new ArtistRepository();
            AlbumRepository albumRepo =new AlbumRepository();
            TrackRepository trackRepo =new TrackRepository();
            UserTrackRepository usertracksRepo = new UserTrackRepository();
            foreach (TrackInfo trackInfo in tracksToInsert)
            {
                Artist trackArtist = GetArtistByTitle(trackInfo.ArtistTitle);
                if (trackArtist == null)
                {
                    //Creates new artist and insert into database
                    trackArtist = new Artist() {ArtistID = Guid.NewGuid(), Title = trackInfo.ArtistTitle};
                    artistRepo.Add(trackArtist);
                    artistRepo.SaveChanges();

                }
                else
                {
                    //artistRepo.Attach(trackArtist);
                }
                
                Album trackAlbum = GetAlbumByTitleAndArtistTitle(trackInfo.AlbumTitle,trackArtist.Title);
                if (trackAlbum == null)
                {
                    //Set trackAlbum as new Album
                    trackAlbum= new Album() {AlbumID = Guid.NewGuid(),ArtistID = trackArtist.ArtistID,Title = trackInfo.AlbumTitle, ReleaseYear = trackInfo.Year};
                    albumRepo.Add(trackAlbum);
                    albumRepo.SaveChanges();
                }
                else
                {
                    //albumRepo.Attach(trackAlbum);
                }
                //Creates new track
                Track newTrack=new Track() {AlbumID = trackAlbum.AlbumID,Title = trackInfo.Title, Genre =trackInfo.Genre,Lyrics = trackInfo.Lyric,Path = trackInfo.SongPath,TrackID = trackInfo.TrackId};
                usertracksRepo.Add(new UserTrack() {UserID = SessionManager.Instance.UserId,TrackID = trackRepo.Add(newTrack).TrackID,IsSync = false});
                //artistRepo.SaveChanges();
                
                
                
                trackRepo.SaveChanges();
                
            }
            usertracksRepo.SaveChanges();
            artistRepo.Dispose();
            trackRepo.Dispose();
            usertracksRepo.Dispose();

        }
示例#30
0
        /// <summary>
        /// Determine the type of the gallery object (album, image, video, etc) specified by the ID. The object must exist 
        /// in the data store. If no gallery object is found, or a media object (image, video, etc) is found but 
        /// the file extension does not correspond to a supported MIME type by Gallery Server, 
        /// <see cref="GalleryObjectType.Unknown"/> is returned. If both a media object and an album exist with the 
        /// <paramref name="id"/>, the media object reference is returned.
        /// </summary>
        /// <param name="id">An integer representing a gallery object that exists in the data store (album, video,
        /// image, etc).</param>
        /// <returns>Returns a GalleryObjectType enum indicating the type of gallery object specified by ID.</returns>
        public static GalleryObjectType DetermineGalleryObjectType(int id)
        {
            if (id == Int32.MinValue)
                return GalleryObjectType.Unknown;

            #region Is ID a media object?

            GalleryObjectType goType = DetermineMediaObjectType(id);

            #endregion

            #region Is ID an album?

            if (goType == GalleryObjectType.Unknown)
            {
                // The ID does not represent a known MediaObject. Check to see if it's an album.
                using (var repo = new AlbumRepository())
                {
                    if (repo.Find(id) != null)
                    {
                        // If we get here, we found an album.
                        goType = GalleryObjectType.Album;
                    }
                }
            }

            #endregion

            // If ID is not a media object or album that exists in the data store, return GalleryObjectType.Unknown.
            return goType;
        }