public SimpleMembershipInitializer()
            {
                //TODO: Had to change this to my DB context to get the db to autocreate!
                Database.SetInitializer<MovieDbContext>(null);

                try {
                    using (var context = new MovieDbContext()) {
                        if (!context.Database.Exists()) {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }
                    //TODO: had to change this to match my database connection name, DB name and identify user id and username for simple role membership providers.
                    WebSecurity.InitializeDatabaseConnection("MovieDbContext",
                                                             "UserProfile",
                                                             "UserID",
                                                             "Username",
                                                             autoCreateTables:
                                                                 true);
                SeedUserDatabaseTables();
                }
                catch (Exception ex) {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        public static IEnumerable<FullViewModel> FindPageOfMovies(IQueryable<FullViewModel> res,
                                                    int page,
                                                    int movie_count,
                                                    MovieDbContext db,
                                                    bool verbose=false)
        {
            var page_start = Tools.WriteTimeStamp(writeTime:false);
            if (verbose) { Tools.TraceLine("  Retrieving paginated results"); }

            int movies_to_skip = movie_count * (page - 1);
            var ids = res.Select(nit => nit.Movie.movie_ID).ToArray();

            if (verbose) { Tools.TraceLine("  sorting movie ids"); }
            //take all the movie_id up to and including the ones you'll show
            // on page, then only take the last set of movie_ids you'll show
            var sortedIds =
                ids.OrderBy(movie_id => movie_id)
                   .Skip(movies_to_skip)
                   .Take(movie_count)
                   .ToArray();

            if (verbose) { Tools.TraceLine("  grabbing matched movies"); }
            var nit_qry =
                Tools.GetFullDbQuery(db)
                     .Where(
                         viewModel =>
                         sortedIds.Any(
                             movie_id => movie_id == viewModel.Movie.movie_ID));
            IEnumerable<FullViewModel> nit_list = nit_qry.ToList();
            if (verbose) { Tools.TraceLine("  done matching movies, returning"); }
            var page_end = Tools.WriteTimeStamp(writeTime:false);
            if (verbose) { Tools.TraceLine("  Taking first page of movies {0}", (page_end - page_start).ToString()); }
            return nit_list;
        }
        public static BoxArt BoxArts(int movieID)
        {
            MovieDbContext db = new MovieDbContext();
            BoxArt boxArts = new BoxArt();

            var boxArtList = db.BoxArts.Where(
                    item => item.movie_ID == movieID).ToList();
            boxArts = boxArtList[0];
            return boxArts;
        }
 public static IQueryable<FullViewModel> ByRating(string searchTerm, MovieDbContext db)
 {
     IQueryable<FullViewModel> res;
     // check both TV rating and MAturity rating
     //TODO: get dropdown of available ratings to let users search by that in the search box, then match exactly
     var movies = from movie in db.Movies
                  where movie.tv_rating.ToUpper().Contains(searchTerm.ToUpper())
                  select movie;
     res = CreateFullView(movies, db);
     return res;
 }
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            base.OnResultExecuting(context);
            //Trace.WriteLine("Starting filter");
            //save url, userId from session, etc...

            //create a Userlog for this request
            var request = context.HttpContext.Request;

            UserLog userLog = TrackingCreate.CreateUserLog(request);

            //TrackingDbContext db = new TrackingDbContext();
            MovieDbContext db = new MovieDbContext();

            db.UserLogs.Add(userLog);
            db.SaveChanges();

            //Trace.WriteLine("raw > url > filepath");
            //Trace.WriteLine(context.HttpContext.Request.RawUrl);
            //Trace.WriteLine(context.HttpContext.Request.Url);
            //Trace.WriteLine(context.HttpContext.Request.FilePath);

            context.Controller.ViewBag.filtered = true;

            //write out all headers
            //var headers = context.HttpContext.Request.Headers;
            //string[] keys =
            //    context.HttpContext.Request.Headers.AllKeys;
            //foreach (string key in keys) {
            //    string msg = string.Format("{0} : {1}", key, headers[key]);
            //    Trace.WriteLine(msg);
            //}

            //write out the user agent
            //string userAgent = context.HttpContext.Request.UserAgent;
            //Trace.WriteLine(userAgent);

            //var model = context.Controller.ViewData.Model;
            //if (model.GetType() == typeof(List<NextFlicksMVC4.Controllers.MoviesController.MovieWithGenreViewModel>))
            //{
            //    Trace.WriteLine("List of models");
            //}

            //test for the custom cookie
            //HttpCookie cookie = context.HttpContext.Request.Cookies.Get("TestCookie");
            //if (cookie != null) {
            //    Trace.WriteLine(cookie.Value);
            //}
            //else {
            //    Trace.WriteLine("Cookie does not exist");
            //}

            //Trace.WriteLine("Ending filter");
        }
        public static void PopulateGenresTable()
        {
            Tools.TraceLine("In PopulateGenresTable");

            var db = new MovieDbContext();

            //if genre table is not empty, its probably full and don't do anything

            //var db = NextFlicksMVC4.Controllers.MoviesController.db;
            //if (db.Genres.Count() != 0)
            //{
            //    Trace.WriteLine("Genre table already is not empty, assuming it's full, so no action was taken");
            //    return;
            //}

            //returns a dict of id to genres
            Dictionary<string, string> dict = NetFlixAPI.PopulateGenres.CreateDictofGenres(System.Web.HttpContext.Current.Server.MapPath("~/dbfiles/genres.NFPOX"));
            //create all the genre models
            List<Genre> genres = new List<Genre>();
            foreach (KeyValuePair<string, string> keyValuePair in dict)
            {
                //create genres
                var id = keyValuePair.Key;
                var genre_string = keyValuePair.Value;
                Genre genre = NetFlixAPI.PopulateGenres.CreateGenreModel(id,
                                                                         genre_string);
                //add to list
                var genreExists = from gen in db.Genres
                                  where gen.genre_ID == genre.genre_ID
                                  select gen;

                if(!genreExists.Any())
                    genres.Add(genre);

            }

            //add to and save table
            Trace.WriteLine(" starting to add genres to the database");
            foreach (Genre genre in genres)
            {
                db.Genres.Add(genre);
            }

            Trace.WriteLine("  starting to savechanges() ");
            try {
                db.SaveChanges();
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException ex) {
                Tools.TraceLine("  caught error while saving Genres Table. It probably already exists:\n***{0}", ex.Message);
            }

            Tools.TraceLine("Out PopulateGenresTable");
        }
 public static void AddGenres(int movieID, Title title)
 {
     MovieDbContext db = new MovieDbContext();
     db.Configuration.AutoDetectChangesEnabled = false;
     //genres to database
     foreach (Genre genre in title.ListGenres)
     {
         MovieToGenre movieToGenre = CreateMovieMovieToGenre(movieID, genre);
         db.MovieToGenres.Add(movieToGenre);
     }
     db.SaveChanges();
 }
Esempio n. 8
0
        public void TestFilterByRating()
        {
            string desired_tvrating = "PG-13";

            //want to make sure that the return IQueryable has only movies that match the given tvrating
            MovieDbContext db = new MovieDbContext();
            IQueryable<FullViewModel> actual_res = Tools.FilterByTvRating(db,
                                                                          desired_tvrating).Take(100);

            foreach (FullViewModel fullViewModel in actual_res) {
                Assert.AreEqual(desired_tvrating, fullViewModel.Movie.tv_rating);
                Assert.AreNotEqual("ASD", fullViewModel.Movie.tv_rating);
            }
        }
        public ActionResult Feedback()
        {
            MovieDbContext db = new MovieDbContext();
            FeedbackModel feedback = new FeedbackModel();

            if (WebSecurity.IsAuthenticated)
            {
                int userID = WebSecurity.CurrentUserId;
                var email = from user in db.Users
                        where user.userID == userID
                        select user.email;
                feedback.Email = email.FirstOrDefault();
            }
            return View("Feedback", feedback);
        }
 public static int[] GetAllReleaseYears(MovieDbContext db)
 {
     //fill the years for the dropdox list
     //get all the years in the db
     IQueryable<FullViewModel> year_res = Tools.GetFullDbQuery(db, true);
     int[] all_years = (from fmv in year_res
                        where fmv.Movie.year >= 0
                        where fmv.Movie.year < 3000
                        //No upper limit needed right?
                        select fmv.Movie.year).Distinct()
                                              .OrderBy(item => item)
                                              .ToArray();
     Tools.TraceLine("Done all years int");
     return all_years;
 }
        public static OmdbEntry Omdb(int movieID)
        {
            MovieDbContext db = new MovieDbContext();
            OmdbEntry omdb = new OmdbEntry();

            omdb = Tools.MatchMovieIdToOmdbEntry(movieID);
            return omdb;
            /* for posterity in case Tools.Cs changes
             *  public static OmdbEntry MatchMovieIdToOmdbEntry(int movie_ID)
                {
                    MovieDbContext db = new MovieDbContext();
                    var omdbEntry = db.Omdb.FirstOrDefault(omdb => omdb.movie_ID == movie_ID);

                   return omdbEntry;
                }*/
        }
        public ActionResult Details(string tagName)
        {
            MovieDbContext db = new MovieDbContext();
            TagDetailViewModel tagDetail = new TagDetailViewModel() { TagName = tagName };

            //get the tagId off the name, there should only be one tag by the same name
            var tagID = from tag in db.MovieTags
                        where tag.Name == tagName
                        select tag.TagId;
            //thjis checks to see if it can return any result and if it cannot return 404
            if (!tagID.Any())
                return HttpNotFound();

            int t_ID = tagID.First();
            tagDetail.TaggedMovies = MoviesTagged(t_ID);
            tagDetail.TaggedByUsers = TaggedByUsers(t_ID);
            return View(tagDetail);
        }
        public static IEnumerable<string> Genres(int movieID)
        {
            MovieDbContext db = new MovieDbContext();
            List<string> genreList = new List<string>();

            var movieGenres = from mtg in db.MovieToGenres
                              join genre in db.Genres
                                  on mtg.genre_ID equals genre.genre_ID
                              group genre.genre_string by mtg.movie_ID
                                  into gs
                                  where gs.Key == movieID
                                  select gs;
            genreList = movieGenres.First().ToList();
            //put the list in an IEnumerable<String> so it can go into the full view model. Don't want to change the model
            //to take a List<String> because tankorsmash may need it that way for some reason.
            IEnumerable<string> genreEnum = genreList;

            return genreEnum;
        }
Esempio n. 14
0
        public static IQueryable<FullViewModel> ByRottenTomatoMeter(string searchTerm, MovieDbContext db)
        {
            int rating;
            Int32.TryParse(searchTerm, out rating);

            if (rating != null)
            {
                IQueryable<FullViewModel> res = Tools.GetFullDbQuery(db);

                var rt_res = (from fmv in res
                              where fmv.OmdbEntry.t_Meter >= rating
                              select fmv);

                return rt_res;
            }

            else
                return null;
        }
        private List<Movie> MoviesTagged(int tagID)
        {
            MovieDbContext db = new MovieDbContext();

            var tagToMovieID = from movieId in db.UserToMovieToTags
                               where movieId.TagId == tagID
                               select movieId.movie_ID;

            var movieTitles = from movieTitle in db.Movies
                              from movieID in tagToMovieID
                              where movieTitle.movie_ID == movieID
                              select movieTitle.short_title;

            var movies = from movie in db.Movies
                         from movieID in tagToMovieID
                         where movie.movie_ID == movieID
                         select movie;

            return movies.Distinct().ToList();
        }
Esempio n. 16
0
        public static IQueryable<FullViewModel> ByStars(string searchTerm, MovieDbContext db)
        {
            double searchStars;
            double movieStars;
            Double.TryParse(searchTerm, out searchStars);

            if(searchStars!=null)
            {
                IQueryable<FullViewModel> res;

                var movies = from movie in db.Movies
                             where movie.avg_rating >= searchStars
                             select movie;

                res = CreateFullView(movies, db);
                return res;
            }

            return null;
        }
        public static void Api(string term = "Jim Carrey")
        {
            MovieDbContext db = new MovieDbContext();
            //grab new movies, turn one into a Movie and view it
            var data =
                OAuth1a.GetNextflixCatalogDataString(
                    "catalog/titles/streaming", term, max_results: "100",
                    outputPath: System.Web.HttpContext.Current.Server.MapPath("~/dbfiles/fixedAPI.NFPOX"));
            /*var titles =
                NetFlixAPI.Create.ParseXmlForCatalogTitles(data);

            List<Movie> movies = new List<Movie>();

            foreach (Title title in titles)
            {
                //create a  movie from the title, and add it to a list of movies and
                // the database
                Movie movie = NetFlixAPI.Create.CreateMovie(title);
                movies.Add(movie);
                db.Movies.Add(movie);

                //create a boxart object from the movie and title object
                BoxArt boxArt =
                    NetFlixAPI.Create.CreateMovieBoxartFromTitle(movie, title);
                db.BoxArts.Add(boxArt);

                //for all the genres in a title, create the linking MtG
                // and then add that object to the db
                foreach (Genre genre in title.ListGenres)
                {
                    MovieToGenre movieToGenre =
                        NetFlixAPI.Create.CreateMovieMovieToGenre(movie,
                                                                  genre);
                    db.MovieToGenres.Add(movieToGenre);

                }
            }

            db.SaveChanges(); */
        }
        private Dictionary<Users, int> TaggedByUsers(int tagID)
        {
            MovieDbContext db = new MovieDbContext();
            Dictionary<Users, int> returnDict = new Dictionary<Users,int>();

            var tagRows = from rows in db.UserToMovieToTags
                          where rows.TagId == tagID
                          select rows;

            var userRows = from userRow in db.UserToMovieToTags
                           where userRow.TagId == tagID
                           from user in db.Users
                           where user.userID == userRow.UserID
                           group userRow.TagId by user into grouping
                           select grouping;
            foreach(IGrouping<Users,int> result in userRows)
            {
                returnDict.Add(result.Key, result.Count());
            }

            return returnDict;
        }
Esempio n. 19
0
        public static IQueryable<FullViewModel> ByGenre(string searchTerm, MovieDbContext db)
        {
            IQueryable<FullViewModel> res;

            //get genres that match search term
            var genres = from genre in db.Genres
                         where genre.genre_string.ToUpper().Contains(searchTerm.ToUpper())
                         select genre;
            //get genre to movie ids
            var genToMov = from gtm in db.MovieToGenres
                           from genre in genres
                           where gtm.genre_ID == genre.genre_ID
                           select gtm;
            //use genre to movie ids to collect list of movies
            var movies = from movie in db.Movies
                         from gtm in genToMov
                         where movie.movie_ID == gtm.movie_ID
                         select movie;

            res = CreateFullView(movies, db);
            return res;
        }
        public static Dictionary<int, List<string>> GetDictOfMovieIdsToGenreStrings(MovieDbContext db,
                                                                 List<MovieToGenre> MtG_list)
        {
            //find all the genre strings for the MtGs from the list
            var genreid_list = MtG_list.Select(item => item.genre_ID).ToList();
            Dictionary<int, string> genre_definitions = new Dictionary<int, string>();

            //find the definitions loop over all the genre ids, and if it's not
            // already defined, find the string name for it
            foreach (int id in genreid_list) {
                if (!genre_definitions.ContainsKey(id)) {
                    string definition =
                        db.Genres.Where(item => item.genre_ID == id)
                          .Select(item => item.genre_string).First();
                    genre_definitions[id] = definition;
                }
            }

            //associate movies with lists of genre defs
            Dictionary<int, List<string>> movie_to_genre_string_dict =
                                        new Dictionary<int, List<string>>();

            foreach (MovieToGenre movieToGenre in MtG_list) {
                //if dict does not contain an entry for the key, make one, and inst
                // a list for it too
                if (!movie_to_genre_string_dict.ContainsKey(movieToGenre.movie_ID)) {
                    movie_to_genre_string_dict[movieToGenre.movie_ID] =
                        new List<string>();
                }

                movie_to_genre_string_dict[movieToGenre.movie_ID].Add(
                    genre_definitions[movieToGenre.genre_ID]);
            }

            return movie_to_genre_string_dict;
        }
        /// <summary>
        /// Takes a list of movies and finds the boxart and genres to return a 
        /// List of MovieWithGenreViewModel
        /// </summary>
        /// <param name="movie_list"></param>
        /// <returns>a list of MovieWithGenreViewModels </returns>
        public static List<MovieWithGenreViewModel> CreateListOfMwGVM(MovieDbContext db,
            List<Movie> movie_list)
        {
            //find all MtGs with movie_id matching movie_list
            var MtG_list = GetListOfMatchingMTGs(db, movie_list);
            //find all genre strings from a list of MtGs
            var movie_to_genre_string_dict = GetDictOfMovieIdsToGenreStrings(db, MtG_list);

            //select all boxarts that match a movie_id from the list
            var boxart_list = GetListOfBoxarts(db, movie_list);

            //add all the genre definitions and boxarts
            //  to the appropriate movie and return that

            ///fill a list with new MwGVMs based on the movie, genre_strings and boxarts
            var MwG_list =
                movie_list.Select(
                    movie => new MovieWithGenreViewModel
                                 {
                                     //movie
                                     movie = movie,
                                     genre_strings = getDictValueOrDefault(
                                         movie_to_genre_string_dict,
                                             movie.movie_ID),
                                     //boxart
                                     boxart =
                                         boxart_list.FirstOrDefault(

                                             item =>
                                             item.movie_ID == movie.movie_ID)
                                 }).ToList();

            //Trace.WriteLine(MtG_list.Count.ToString());

            return MwG_list;
        }
 public ActionResult Edit(Movie movie)
 {
     MovieDbContext db = new MovieDbContext();
     if (ModelState.IsValid)
     {
         db.Entry(movie).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("oldIndex");
     }
     return View(movie);
 }
        /*

        /// <summary>
        /// Main action for this controller. Offers searching by title, genre and tag
        /// </summary>
        /// <param name="movie_title">movie title to look for</param>
        /// <param name="genre_select">selected genre to search for</param>
        /// <param name="tag_string">selected tag to search for</param>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Index(
             string source, string search_term="", string year="", string movie_title = "", string genre_select = "0",
                                    string tag_string = "0", string mat_rating="", string tv_rating = "",
                                    string min_tmeter = "",
                                    int page = 1)
        {
            //var omdbTXT = System.Web.HttpContext.Current.Server.MapPath("~/dbfiles/omdb.txt");
            //var tomatoesTXT = System.Web.HttpContext.Current.Server.MapPath("~/dbfiles/tomatoes.txt");
            //TSVParse.OptimizedPopulateOmdbTableFromTsv(omdbTXT, tomatoesTXT);
            var test = source;
            var start = Tools.WriteTimeStamp(writeTime:false);

            Tools.TraceLine("Creating db context");

            var db = new MovieDbContext();
            db.Configuration.AutoDetectChangesEnabled = false;
            //Tools.TraceLine(db.Database.Connection.ConnectionString);
            //db.Configuration.AutoDetectChangesEnabled = true;

            Tools.TraceLine("Done creating db context");

            Tools.TraceLine("About to raise if no movies");
            //make sure there's movies in the db
            RaiseIfNoMoviesInDb(db);
            Tools.TraceLine("Done about to raise if no movies");

            //make sure the title isn't the default text set in the _FilterMenu
            //TODO:make the default text in the search boxes a ViewBag value for easier editing
            if (movie_title == "Enter a title") {
                movie_title = "";
            }
            if (tag_string == "Enter a tag") {
                tag_string = "0";
            }

            //TODO:create a FilterMenuInit() so I can just call this everytime. It'll be easier on us all
            //Assign values to a ViewBag, so the Filtermenu can use them
            FilterMenuInit(db);

            //choose which set of movies I want to filter down to
            IQueryable<FullViewModel> res;

             //if the movie title isn't null, search movies
            if (movie_title != "") {
                res = Tools.FilterMoviesAndGenres(movie_title, db, genre_select);
            }
            //if the tag string isn't empty, then search through tags
            else if (tag_string != "0") {
                res = Tools.FilterTags(tag_string, db);
            }
            //sort by RT rating
            else if (min_tmeter != "") {
                res = Tools.FilterByMinTmeter(db, min_tmeter);
            }
            //sort by maturity rating
            else if (mat_rating != "") {
                res = Tools.FilterByMaturityRating(db, mat_rating);
            }
            else if (tv_rating != "") {
                res = Tools.FilterByTvRating(db, tv_rating);
            }
            //sort by year
            else if (year != "") {
                res = Tools.FilterByYear(db, year);
            }

            //otherwise return the entire db and return that
            else {
                res = Tools.GetFullDbQuery(db);
            }

            //sometimes the first call to the db times out. I can't reliably repro it, so I've just created a try catch for it.
            try
            {
                //count all the movies possible
                int totalMovies = res.Count();
                Tools.TraceLine("  found {0} movies", totalMovies);
                //set it to the viewbag so the view can display it
                ViewBag.TotalMovies = totalMovies;
                ViewBag.movies_per_page = 28;
                Tools.TraceLine("  Found a total possible results of {0}", totalMovies);

                int movie_count = 28;
                var nit_list = FindPageOfMovies(res, page, movie_count, db, true);
                //var nit_list = FindPageOfMovies(res, page, movie_count, new MovieDbContext(), true);

                //prepare certain variables for the pagination
                PrepareIndexViewBagForPagination();

                var end = Tools.WriteTimeStamp(writeTime:false);
                Tools.TraceLine("  Index took: {0} to complete",((end - start).ToString()));
                Tools.TraceLine("**********END OF INDEX***********");

            db.Configuration.AutoDetectChangesEnabled = true;
                return View("Results", nit_list);
            }

            catch (StackOverflowException ex) //bogus error
            //catch (System.Data.EntityCommandExecutionException ex)
            {
                Tools.TraceLine(
                    "The ToList() call probably timed out, it happens on first call to db a lot, I don't know why:\n  ***{0}",
                    ex.GetBaseException().Message);

                db.Configuration.AutoDetectChangesEnabled = true;
                return View("Error");
            }

        }
           */
        public void FilterMenuInit(MovieDbContext db)
        {
            ViewBag.genre_dict = Tools.CreateSortedGenreDictionary(db);
            ViewBag.tag_dict = Tools.CreateSortedTagDictionary(db);

            var all_years = GetAllReleaseYears(db);
            //convert the years to SelectListItems
            ViewBag.DropDownYears = Tools.IEnumToSelectListItem(all_years);

            var all_tvratings = GetAllTvRatings(db);
            ViewBag.DropDownTvRating = Tools.IEnumToSelectListItem(all_tvratings);

            var tmeterArray = GetAllTmeters(db);
            ViewBag.DropDownTmeter = Tools.IEnumToSelectListItem(tmeterArray);
        }
        public static TagCountViewModel TagsAndCount(int movieID)
        {
            MovieDbContext db = new MovieDbContext();
            TagCountViewModel tagView = new TagCountViewModel(){ TagAndCount = new Dictionary<string, int>()};

            //find the ids of the tags related to the movie
            var tagsForMovie = from MtT in db.UserToMovieToTags
                               where MtT.movie_ID == movieID
                               select MtT.TagId;

            //find the tag string based on the id of the strings
            var tagStrings = from tag in db.MovieTags
                             from tag_id in tagsForMovie
                             where tag.TagId == tag_id
                             select tag.Name;

            var tagCounts = from tagString in db.MovieTags
                            where tagStrings.Contains(tagString.Name)
                            from MtT in db.UserToMovieToTags
                            where MtT.TagId == tagString.TagId
                            group MtT.TagId by tagString.Name
                            into grouping
                            select grouping;

            foreach (IGrouping<string, int> result in tagCounts)
            {
                tagView.TagAndCount.Add(result.Key, result.Count());
            }

            return tagView;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"> this is the "searchType" named sourc eis css, when i try to change it, breaks</param>
        /// <param name="sortOrder">this is a string that will sort the list by different params, need to add a Case for it</param>
        /// <param name="currentFilter"> current filter and search string seem to interchange with one another</param>
        /// <param name="searchString">see above</param>
        /// <param name="page">what page to display of list</param>
        /// <returns></returns>
        public ActionResult Index(string source, string sortOrder, 
            string currentFilter, string searchString, int page = 1)
        {
            //using this: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

            var start = Tools.WriteTimeStamp(writeTime: false);
            var db = new MovieDbContext();
            IQueryable<FullViewModel> res;

            ViewBag.SearchType = String.IsNullOrEmpty(source) ? "title" : source;
            ViewBag.CurrentSort = sortOrder;

            /*loading the page is GET
             * clicking on a page line forward back etc is GET
             * clcikign the search button is POST
             */

            if (Request.HttpMethod == "GET")
                searchString = currentFilter;
            else //POST or other method clear the HttpContext.Cache
                page = 1;

            ViewBag.CurrentFilter = searchString;

            var startQuery = Tools.WriteTimeStamp(writeTime: false);
            if (source == "title")
                res = MovieSearch.ByTitle(searchString, db);
            else if (source == "genre")
                res = MovieSearch.ByGenre(searchString, db);
            else if (source == "tag")
                res = MovieSearch.ByTag(searchString, db);
            else if (source == "rt")
                res = MovieSearch.ByRottenTomatoMeter(searchString, db);
            else if (source == "rating")
                res = MovieSearch.ByRating(searchString, db);
            else if (source == "year")
                res = MovieSearch.ByYear(searchString, db);
            else if (source == "stars")
                res = MovieSearch.ByStars(searchString, db);
            else
                res = Tools.GetFullDbQuery(db);

            //count all the movies possible
            int totalMovies = res.Count();
            Tools.TraceLine("  found {0} movies", totalMovies);
            //set it to the viewbag so the view can display it
            ViewBag.TotalMovies = totalMovies;
            ViewBag.movies_per_page = 28;
            Tools.TraceLine("  Found a total possible results of {0}", totalMovies);

            //how many results to display per page
            int movie_count = 28;

            var pagedList = FindPageOfMovies(res, page, movie_count, db, true);

            switch (sortOrder)
            {
                //add cases her ewhen we add sort by methods to sort by title id etc
                // right now defualt is just to sort by name
                default:
                    pagedList = pagedList.OrderBy(m => m.Movie.short_title);
                    break;
            }

            //prepare certain variables for the pagination
            PrepareIndexViewBagForPagination();
            ViewBag.Page = page;
            return View("Results", pagedList);
        }
 public static int[] GetAllTmeters(MovieDbContext db)
 {
     //fill the TV Ratings for the dropdown list
     //get all the tv ratings from the db
     IQueryable<FullViewModel> min_tmeter_res = Tools.GetFullDbQuery(db);
     int[] all_tmeters = (from fmv in min_tmeter_res
                          where fmv.OmdbEntry.t_Meter != null
                          select fmv.OmdbEntry.t_Meter).OrderBy(
                              item => item).ToArray();
     int[] tmeterArray = all_tmeters.Distinct().ToArray();
     return tmeterArray;
 }
 protected override void Dispose(bool disposing)
 {
     MovieDbContext db = new MovieDbContext();
     db.Dispose();
     base.Dispose(disposing);
 }
        ////Creates a cookie
        //public ActionResult Cookies()
        //{
        //    //create a cookie
        //    var cookie_name = "TestCookie";
        //    HttpCookie cookie = new HttpCookie(cookie_name);
        //    cookie.Value = "Test Cookie Value";
        //    //add the cookie
        //    Response.Cookies.Add(cookie);
        //    Trace.WriteLine("Cookie Added");
        //    //test for the cookie creation, change ViewBag
        //    if (Request.Cookies.Get(cookie_name) != null) {
        //        ViewBag.cookies = true;
        //    }
        //    return View();
        //}
        ////Expires a cookie
        //public ActionResult Jar()
        //{
        //    var cookie_name = "TestCookie";
        //    //if cookie exists, remove it
        //    if (Request.Cookies.AllKeys.Contains(cookie_name)) {
        //        //get the cookie from the request, expire the time so it gets
        //        // deleted
        //        var cookie = Request.Cookies.Get(cookie_name);
        //        cookie.Expires = DateTime.Now.AddDays(-1);
        //        Response.Cookies.Add(cookie);
        //        ViewBag.cookies = false;
        //        Trace.WriteLine("Cookie removed");
        //    }
        //    else {
        //        Trace.WriteLine("Cookie didn't exist, no action");
        //        ViewBag.cookies = true;
        //    }
        //    return View("Cookies");
        //}
        //[HttpGet]
        //public ActionResult Filter()
        //{
        //    MovieDbContext db = new MovieDbContext();
        //    //grab the lowest year in Catalog
        //    var min_qry = "select  top(1) * from Movies where year != \'\' order by year ASC";
        //    var min_res = db.Movies.SqlQuery(min_qry);
        //    var min_list = min_res.ToList();
        //    string min_year = min_list[0].year;
        //    ViewBag.min_year = min_year;
        //    //grab the highest year in catalog
        //    var max_qry = "select  top(1) * from Movies order by year DESC ";
        //    var max_res = db.Movies.SqlQuery(max_qry);
        //    var max_list = max_res.ToList();
        //    string max_year = max_list[0].year;
        //    ViewBag.max_year = max_year;
        //    //Create a list of SelectListItems
        //    List<SelectListItem> years = new List<SelectListItem>();
        //    for (int i = Int32.Parse(min_year); i <= Int32.Parse(max_year); i++)
        //    {
        //        years.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
        //    }
        //    //Create a selectList, but since it's looking for an IEnumerable,
        //    // tell it what is the value and text parts
        //    SelectList slist = new SelectList(years, "Value", "Text");
        //    //give the Viewbag a property for the SelectList
        //    ViewBag.years = slist;
        //    return View();
        //}
        //[Obsolete("shouldn't be needed anymore", true)]
        //public ActionResult FilterHandler(string year_start, string year_end)
        //{
        //    ViewData["year_start"] = year_start;
        //    ViewData["year_end"] = year_end;
        //    Trace.WriteLine(ViewData["pet"]);
        //    return View("FilterHandler");
        //}
        public ActionResult TagSearch(string term="scary")
        {
            MovieDbContext db = new MovieDbContext();

               //validate tag
            if (term == "") {
                term = "scary";
            }

            //get the tag id for the term
            var tag_res = from tag in db.MovieTags
                      where tag.Name == term
                      select tag.TagId;
            int tag_id = tag_res.FirstOrDefault();

            //find the movies that are tagged with tag_id
            var movie_res = from umt in db.UserToMovieToTags
                            where umt.TagId == tag_id
                            select umt.movie_ID;

            //tODO: build a FullView for each of the movies in the movie_ids list,
            // should almost be done, but I can't quite add any tags to the db to test
            var res_db = Tools.GetFullDbQuery(db);
            var res = from nit in res_db
                      from movie_id in movie_res
                      where nit.Movie.movie_ID == movie_id
                      select nit;
            IEnumerable<FullViewModel> matched_list = res.ToList();

            //Assign it to a ViewBag, so the Filtermenu can use it
            ViewBag.genre_dict = Tools.CreateSortedGenreDictionary(db);

            //Assign it to a ViewBag, so the Filtermenu can use it
            ViewBag.tag_dict = Tools.CreateSortedTagDictionary(db);

            //Count the total movies and add that to the Viewbag
            ViewBag.TotalMovies = matched_list.Count();

            return View("Results", matched_list);
        }
 public void RaiseIfNoMoviesInDb(MovieDbContext db)
 {
     // so if NOT any movies => movies == true, meaning any movie will == true,
     // so if it's false, the condition will be met
     if (!db.Movies.Any()) {
         Tools.TraceLine("ERROR: No movies in DB, have you ran Full yet? Throwing error now");
         //TODO: use a different class of Exception, too broad
         throw new Exception("ERROR: No movies in DB, have you ran Full yet?");
     }
 }
        /// <summary>
        /// Sloppy return random set of movies. redirects to Index with a random start and count of 10
        /// </summary>
        /// <returns></returns>
        public ActionResult Random()
        {
            MovieDbContext db = new MovieDbContext();

            int rand_title_int = new Random().Next(1, db.Movies.Count());
            return RedirectToAction("oldIndex",
                                    new {count = 1, start = rand_title_int});
        }