Esempio n. 1
0
        public UnitOfWork(MovieDBContext context)
        {
            _context = context;

            Movies = new MovieRepository(_context);
            Users  = new UserRepository(_context);
        }
        public MovieControllerTests()
        {
            _dbContext   = new MovieDBContext();
            _transaction = _dbContext.Database.BeginTransaction();

            _dbContext.Movies.RemoveRange(_dbContext.Movies.ToList());

            var aRomanceMovie = new Movie {
                ID = 1, Genre = "Romance", Price = 1.00m, Rating = "A+", ReleaseDate = DateTime.Now, Title = "A Romance Movie"
            };
            var romeoAndJuliet = new Movie {
                ID = 2, Genre = "Romance", Price = 1.00m, Rating = "A+", ReleaseDate = DateTime.Now, Title = "Romeo and Juliet"
            };
            var zoolander = new Movie {
                ID = 3, Genre = "Comedy", Price = 1.00m, Rating = "A+", ReleaseDate = DateTime.Now, Title = "Romeo and Juliet"
            };
            var aComedyMovie = new Movie {
                ID = 4, Genre = "Comedy", Price = 1.00m, Rating = "A+", ReleaseDate = DateTime.Now, Title = "A Comedy Movie"
            };

            _dbContext.Movies.Add(aRomanceMovie);
            _dbContext.Movies.Add(romeoAndJuliet);
            _dbContext.Movies.Add(zoolander);
            _dbContext.Movies.Add(aComedyMovie);

            _sut = new MoviesController(_dbContext);
        }
Esempio n. 3
0
        public static void EnsurePopulated(IApplicationBuilder application)
        {
            MovieDBContext context = application.ApplicationServices.
                                     CreateScope().ServiceProvider.GetRequiredService <MovieDBContext>();

            if (context.Database.GetPendingMigrations().Any())
            {
                context.Database.Migrate();
            }
            if (!context.Movies.Any())
            {
                context.Movies.AddRange(
                    new Movie
                {
                    Rating   = "PG-13",
                    Category = "Action Adventure",
                    Title    = "Indiana Jones and the Raiders of the Lost Ark",
                    Year     = 1981,
                    Director = "Steven Spielberg",
                    LentTo   = "",
                    Edited   = false,
                    Notes    = ""
                }
                    );

                //save all changes
                context.SaveChanges();
            }
        }
Esempio n. 4
0
        public async Task <ActionResult <Movie> > PostMovie([FromBody] URLDTO URL)
        {
            String movieID  = Helper.MovieHelper.GetMovieFromLink(URL.URL);
            Movie  newMovie = Helper.MovieHelper.GetMovieFromID(movieID);


            _context.Movie.Add(newMovie);
            await _context.SaveChangesAsync();


            // We are creating a new context so that loading realted movies don't block the api.
            MovieDBContext          tempContext             = new MovieDBContext();
            RelatedMoviesController realtedMoviesController = new RelatedMoviesController(tempContext);

            //// This will be executed in the background.
            Task addCaptions = Task.Run(async() =>
            {
                List <RelatedMovie> relatedMovies = Helper.MovieHelper.GetRelatedMovies(movieID);

                for (int i = 0; i < relatedMovies.Count; i++)
                {
                    RelatedMovie relatedMovie = relatedMovies.ElementAt(i);
                    relatedMovie.MovieId      = newMovie.MovieId;
                    // posting related movies to the database
                    await realtedMoviesController.PostRelatedMovie(relatedMovie);
                }
            });

            return(CreatedAtAction("GetMovie", new { id = newMovie.MovieId }, newMovie));
        }
Esempio n. 5
0
 public AdminForm(MovieDBContext db)
 {
     InitializeComponent();
     Users = db.Users.ToList();
     _db   = db;
     objectListView1.SetObjects(Users);
     this.FormClosed += AdminForm_FormClosed;
 }
Esempio n. 6
0
 // GET: Movie
 public ActionResult Index()
 {
     using (var db = new MovieDBContext())
     {
         var movies = db.Movies.ToList();
         return(View(movies));
     }
 }
Esempio n. 7
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options,
                                                    IOwinContext context)
        {
            MovieDBContext         db      = context.Get <MovieDBContext>();
            ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(db));

            return(manager);
        }
Esempio n. 8
0
        public MovieProvider(MovieDBContext dbContext, ILogger <Db.Movie> logger, IMapper mapper)
        {
            this.dbContext = dbContext;
            this.logger    = logger;
            this.mapper    = mapper;

            SeedData();
        }
 public void SimpleCodeFirstSelect()
 {
   MovieDBContext db = new MovieDBContext();
   db.Database.Initialize(true);
   var l = db.Movies.ToList();
   foreach (var i in l)
   {
   }
 }
 public FirstLoginForm(MovieDBContext db, User user)
 {
     _db    = db;
     _user  = user;
     genres = _db.MovieGenres.ToList();
     InitializeComponent();
     this.FormClosed += FirstLoginForm_FormClosed;
     favoriteGenresSelect.Items.AddRange(genres.Select(g => g.Name).ToArray());
 }
Esempio n. 11
0
        public void Store(MovieModel movieModel, MovieDBContext _context)
        {
            var newMovie = new Movies();

            newMovie.Title = movieModel.Title;
            newMovie.Genre = movieModel.Genre.ToString();
            _context.Movies.Add(newMovie);
            _context.SaveChanges();
        }
Esempio n. 12
0
File: Program.cs Progetto: jmf991/EF
 static void Main(string[] args)
 {
     using (var db = new MovieDBContext())
     {
         Movie movie = new Movie {
             Rank = 1, Title = "The Shawshank Redemption", Year = 1994
         };
         db.Movies.Add(movie);
         db.SaveChanges();
     }
 }
Esempio n. 13
0
 public Users GetUsers(string username)
 {
     try
     {
         MovieDBContext db = new MovieDBContext();
         return(db.Users.Where(o => o.Mobile == username || o.Email == username).Select(o => o).First());
     }
     catch (Exception e)
     {
         return(null);
     }
 }
Esempio n. 14
0
 public List <MovieList> GetRecommandedMovies(string customerID)
 {
     try
     {
         MovieDBContext db = new MovieDBContext();
         return(db.UserIntrestedGenerics.Where(o => o.UserId == customerID).Select(o => o.UserIntrest.MovieList).Single().ToList());
     }
     catch (Exception e)
     {
         return(null);
     }
 }
 public UserDashboardForm(MovieDBContext db, User user)
 {
     InitializeComponent();
     _db   = db;
     _user = user;
     if (_user.Age > 60)
     {
         SetAllControlsFont(this.Controls, 4);
     }
     this.FormClosed += UserDashboardForm_FormClosed;
     goToDashboard();
 }
Esempio n. 16
0
 public List <MovieList> GetMovieLists()
 {
     try
     {
         MovieDBContext db = new MovieDBContext();
         return(db.MovieList.Select(o => o).ToList());
     }
     catch (Exception e)
     {
         return(null);
     }
 }
Esempio n. 17
0
        //static StreamReader f;
        static void Main(string[] args)
        {
            ReadMovie      rm      = new ReadMovie();
            MovieDBContext context = new MovieDBContext();
            int            cpt     = rm.readAnddecodeline();

            Console.WriteLine("Nombre de films inseres = " + cpt);


            //Lecture + affichage de 5 premiers films

            /*int[] tabIdFilm = { 2, 3, 5, 6, 9 };
             * foreach(int FilmId in tabIdFilm)
             * {
             *
             *   Film film = context.Films.Find(FilmId);
             *   List<Actor> listeActors = film.Actors.ToList();
             *   Console.WriteLine(film);
             *   foreach (Actor actor in listeActors)
             *       Console.WriteLine(actor);
             * }*/

            //affichage des Star Wars

            /* List<Film> listeStarWars = (from film in context.Films where film.FilmTitle.Equals("Star Wars") select film).ToList();
             * foreach (Film f in listeStarWars)
             *   Console.WriteLine(f);*/

            //Affichage des films dans lesquels joue Harrison Ford ou Tom Hanks

            /*Actor a = context.Actors.SingleOrDefault(aa =>aa.ActorName.Equals("Harrison") && aa.ActorSurname== "Ford");
             * Console.WriteLine(a);
             * if (a != null)
             * {
             *  List<Film> listeFilms = a.Films.ToList();
             *  foreach (Film ff in listeFilms)
             *      Console.WriteLine(ff);
             * }
             * else
             *  Console.WriteLine("Aucun film trouve");*/

            //Mrs Doubtfire (dans lequel Robin Williams joue plusieurs rôles).

            /*
             * select Films.*, Actors.*,Characters.*
             * from Films join CharacterActors on Films.FilmId=CharacterActors.FilmId
             *  join Actors on Actors.ActorId=CharacterActors.ActorId
             *  join Characters on Characters.CharacterId=CharacterActors.CharacterId
             *  where Films.FilmTitle='Mrs. Doubtfire' and Actors.ActorName='Robin' and Actors.ActorSurname='Williams';
             */
            Console.ReadKey();
        }
Esempio n. 18
0
 public ActionResult Delete(int id = 0)
 {
     using (var db = new MovieDBContext())
     {
         Movie movie = db.Movies.Find(id);
         // Find the movie from db
         if (movie == null) // There is no movie with the passed id
         {
             return(HttpNotFound());
         }
         return(View(movie));
     }
 }
Esempio n. 19
0
        private async Task asynctask(ThreadParam p)
        {
            //return await Task.Run(() => {
            MovieDBContext tmpdb = new MovieDBContext();

            p.to = tmpdb.Movies.ToList();
            tmpdb.Dispose();
            ViewBag.asyncThreadid2 = Thread.CurrentThread.ManagedThreadId;
            await Task.Delay(100);

            // return 0;
            // });
        }
Esempio n. 20
0
        public static void Seed()
        {
            MovieDBContext context = new MovieDBContext();


            try
            {
                context.Movies.AddOrUpdate(i => i.Title,
                                           new Movie
                {
                    Title       = "When Harry Met Sally",
                    ReleaseDate = DateTime.Parse("1989-1-11"),
                    Genre       = "Romantic Comedy",
                    Price       = 7.99M,
                    Rating      = "PG"
                },
                                           new Movie
                {
                    Title       = "Ghostbusters ",
                    ReleaseDate = DateTime.Parse("1984-3-13"),
                    Genre       = "Comedy",
                    Price       = 8.99M,
                    Rating      = "PG"
                },

                                           new Movie
                {
                    Title       = "Ghostbusters 2",
                    ReleaseDate = DateTime.Parse("1986-2-23"),
                    Genre       = "Comedy",
                    Price       = 9.99M,
                    Rating      = "PG"
                },

                                           new Movie
                {
                    Title       = "Rio Bravo",
                    ReleaseDate = DateTime.Parse("1959-4-15"),
                    Genre       = "Western",
                    Price       = 3.99M,
                    Rating      = "PG"
                }
                                           );
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
 public void AlterTableTest()
 {
   ReInitDb();
   MovieDBContext db = new MovieDBContext();      
   db.Database.Initialize(true);
   var l = db.MovieFormats.ToList();
   foreach (var i in l)
   {
   }
   MovieFormat m = new MovieFormat();
   m.Format = 8.0f;
   db.MovieFormats.Add(m);
   db.SaveChanges();
 }
Esempio n. 22
0
        static void Main()
        {
            var connString = ConfigurationManager
                             .ConnectionStrings["MovieDB"]
                             .ConnectionString;
            MovieDBContext movieDB = new MovieDBContext(connString);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var loginForm = new LoginForm(movieDB);

            loginForm.Show();
            Application.Run();
        }
Esempio n. 23
0
 public ActionResult Edit(Movie movieToUpdate)
 {
     if (ModelState.IsValid)
     {
         //Update the data in db and show the list of movies
         using (var db = new MovieDBContext())
         {
             db.Entry(movieToUpdate).State = System.Data.Entity.EntityState.Modified;
             db.SaveChanges();
         }
         return(RedirectToAction("Index"));
     }
     return(View(movieToUpdate));
 }
Esempio n. 24
0
        public ActionResult Add(Movie movieFromView)
        {
            if (ModelState.IsValid)
            {
                //Save the data in db and show the list of movies
                using (var db = new MovieDBContext())
                {
                    db.Movies.Add(movieFromView);
                    db.SaveChanges();
                }
                return(RedirectToAction("Index"));
            }

            return(View(movieFromView));
        }
        public void AddingEmptyRow()
        {
            using (MovieDBContext ctx = new MovieDBContext())
              {
            ctx.Database.Initialize(true);
            ctx.EntitySingleColumns.Add(new EntitySingleColumn());
            ctx.SaveChanges();
              }

              using (MovieDBContext ctx2 = new MovieDBContext())
              {
            var q = from esc in ctx2.EntitySingleColumns where esc.Id == 1 select esc;
            Assert.AreEqual(1, q.Count());
              }
        }
Esempio n. 26
0
        public async Task GetMoviesBySearchText()
        {
            var options   = new DbContextOptionsBuilder <MovieDBContext>().UseInMemoryDatabase(nameof(GetMoviesBySearchText)).Options;
            var dbContext = new MovieDBContext(options);

            CreateProducts(dbContext);

            var productProfile = new MovieProfile();
            var configuration  = new MapperConfiguration(cfg => cfg.AddProfile(productProfile));
            var mapper         = new Mapper(configuration);
            var movieProvider  = new MovieProvider(dbContext, null, mapper);

            var result = await movieProvider.SeachMovieAsync("Siddarth");

            Assert.True(result.IsSucess);
        }
Esempio n. 27
0
        //Returns all Genres currently in the database
        public JsonResult GetAvailableGenres()
        {
            using (MovieDBContext db = new MovieDBContext())
            {
                var genres = from genre in db.Genres
                             select new { id = genre.TmdbGenreId, name = genre.Name };

                //Expected JSON is in format: {[{}, {}, {}]}, i.e. array fo objects wrapped in an object
                var returnObj = new
                {
                    genres = genres.ToList()
                };

                return(Json(returnObj, JsonRequestBehavior.AllowGet));
            }
        }
        public void WriteAllMovies()
        {
            var movieDbContext = new MovieDBContext();
            var controller     = new MoviesController(movieDbContext);

            for (var i = 1; i <= NumberOfSearches; i++)
            {
                var result = controller.Index(movieGenre: null, searchString: null) as ViewResult;

                var model = result.Model as IEnumerable <Movie>;

                foreach (var movie in model)
                {
                    Console.WriteLine($"Result {movie.Title}");
                }
            }
        }
    public void ConcurrencyCheck()
    {
      using (MovieDBContext db = new MovieDBContext())
      {
        db.Database.ExecuteSqlCommand(
@"DROP TABLE IF EXISTS `test3`.`MovieReleases`");

        db.Database.ExecuteSqlCommand(
@"CREATE TABLE `MovieReleases` (
  `Id` int(11) NOT NULL,
  `Name` varbinary(45) NOT NULL,
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=binary");
        MySqlTrace.Listeners.Clear();
        MySqlTrace.Switch.Level = SourceLevels.All;
        GenericListener listener = new GenericListener();
        MySqlTrace.Listeners.Add(listener);
        try
        {
          MovieRelease mr = db.MovieReleases.Create();
          mr.Id = 1;
          mr.Name = "Commercial";
          db.MovieReleases.Add(mr);
          db.SaveChanges();
          mr.Name = "Director's Cut";
          db.SaveChanges();
        }
        finally
        {
          db.Database.ExecuteSqlCommand(@"DROP TABLE IF EXISTS `MovieReleases`");
        }
        // Check sql        
        Regex rx = new Regex(@"Query Opened: (?<item>UPDATE .*)", RegexOptions.Compiled | RegexOptions.Singleline);
        foreach (string s in listener.Strings)
        {
          Match m = rx.Match(s);
          if (m.Success)
          {
            CheckSql(m.Groups["item"].Value, SQLSyntax.UpdateWithSelect);
            Assert.Pass();
          }
        }
        Assert.Fail();
      }
    }
Esempio n. 30
0
 private void CreateProducts(MovieDBContext dbContext)
 {
     dbContext.Movies.Add(new Db.Movie
     {
         MovieId            = 1,
         Title              = "180",
         Release_Year       = "2011",
         Locations          = "Randall Museum",
         Production_Company = "SPI Cinemas",
         Director           = "Jayendra",
         Writer             = "Hemant",
         Actor_1            = "Siddarth",
         Actor_2            = "Nithya Menon",
         Actor_3            = "Priya Anand"
     });
     dbContext.SaveChanges();
     dbContext.Movies.Add(new Db.Movie
     {
         MovieId            = 2,
         Title              = "180",
         Release_Year       = "2012",
         Locations          = "Randall Museum",
         Production_Company = "SPI Cinemas",
         Director           = "Rajendra",
         Writer             = "Hemant",
         Actor_1            = "Siddarth",
         Actor_2            = "Anushka",
         Actor_3            = "Urmila"
     });
     dbContext.SaveChanges();
     dbContext.Movies.Add(new Db.Movie
     {
         MovieId            = 3,
         Title              = "180",
         Release_Year       = "2013",
         Locations          = "Singapore",
         Production_Company = "SPI Cinemas",
         Director           = "Upendra",
         Writer             = "Ramakant",
         Actor_1            = "Anil Kapur",
         Actor_2            = "Katrina",
         Actor_3            = "Tapsee"
     });
     dbContext.SaveChanges();
 }
Esempio n. 31
0
        private static int testMethodDelegate(int tm, MoviesController ctl)
        {
            if (!ctl.ms.mClient.KeyExists("xxxxxx2"))
            {
                MovieDBContext tmpdb = new MovieDBContext();
                Movie          mv    = tmpdb.Movies.Find(6);
                tmpdb.Dispose();
            }

            int tmp = 1;

            for (int i = 0; i < tm * 1000; i++)
            {
                Random rnd = new Random();
                int    rd  = rnd.Next(1, 1000);
                tmp = (tmp * rd) % 999999999;
            }
            ctl.ViewBag.asyncThreadid2 = Thread.CurrentThread.ManagedThreadId;
            return(tmp);
        }
        public string ShopCategoryTest()
        {
            using (var db = new MovieDBContext())
            {
                var generalCategory        = db.ShopCategories.Single(c => c.CategoryId == 1);
                var computerPeriphCategory = db.ShopCategories.Single(c => c.CategoryId == 3);
                var miceCategory           = db.ShopCategories.Where(c => c.CategoryId == 4).Single();

                if (miceCategory.ParentCategory != null)
                {
                    miceCategory.ParentCategory = miceCategory.ParentCategory.CategoryId == 3
                                                      ? generalCategory
                                                      : computerPeriphCategory;
                }

                db.SaveChanges();

                return("ShopCategoryTest complete");
            }
        }
Esempio n. 33
0
 public bool SaveCustomer(Customer req)
 {
     try
     {
         Users user_obj = new Users();
         user_obj.Id         = Guid.NewGuid().ToString();
         user_obj.Email      = req.Email;
         user_obj.IsVerified = false;
         user_obj.Mobile     = req.MobileNumber;
         user_obj.Name       = req.Name;
         MovieDBContext db = new MovieDBContext();
         db.Users.Add(user_obj);
         db.SaveChanges();
         return(true);
     }
     catch (Exception e)
     {
         return(false);
     }
 }
Esempio n. 34
0
        /// <summary>
        /// Initiate a new todo list for new user
        /// </summary>
        /// <param name="userName"></param>
        private static void InitiateDatabaseForNewUser(string userName)
        {
            var      db       = new MovieDBContext();
            TodoList todoList = new TodoList();

            todoList.UserId = userName;
            todoList.Title  = "My Todo List #1";
            todoList.Todos  = new List <TodoItem>();
            db.TodoLists.Add(todoList);
            db.SaveChanges();

            todoList.Todos.Add(new TodoItem()
            {
                Title = "Todo item #1", TodoListId = todoList.TodoListId, IsDone = false
            });
            todoList.Todos.Add(new TodoItem()
            {
                Title = "Todo item #2", TodoListId = todoList.TodoListId, IsDone = false
            });
            db.SaveChanges();
        }
 public void TestPrecisionNscale()
 {
     MovieDBContext db = new MovieDBContext();
       db.Database.Initialize(true);
       var l = db.Movies.ToList();
       IDataReader r = execReader(string.Format(
     @"select numeric_precision, numeric_scale from information_schema.columns
     where table_schema = '{0}' and table_name = 'movies' and column_name = 'Price'", conn.Database));
       r.Read();
       Assert.AreEqual(16, r.GetInt32(0));
       Assert.AreEqual(2, r.GetInt32(1));
 }
 public void FirstOrDefaultNested()
 {
     ReInitDb();
       using (MovieDBContext ctx = new MovieDBContext())
       {
     ctx.Database.Initialize(true);
     int DirectorId = 1;
     var q = ctx.Movies.Where(p => p.Director.ID == DirectorId).Select(p =>
       new
       {
     Id = p.ID,
     FirstMovieFormat = p.Formats.Count == 0 ? 0.0 : p.Formats.FirstOrDefault().Format
       });
     string sql = q.ToString();
     foreach (var r in q)
     {
     }
       }
 }
 public void CheckByteArray()
 {
     MovieDBContext db = new MovieDBContext();
       db.Database.Initialize(true);
       string dbCreationScript =
     ((IObjectContextAdapter)db).ObjectContext.CreateDatabaseScript();
       Regex rx = new Regex(@"`Data` (?<type>[^\),]*)", RegexOptions.Compiled | RegexOptions.Singleline);
       Match m = rx.Match(dbCreationScript);
       Assert.AreEqual("longblob", m.Groups["type"].Value);
 }
        public void CallStoredProcedure()
        {
            using (MovieDBContext context = new MovieDBContext())
              {
            context.Database.Initialize(true);
            int count = context.Database.SqlQuery<int>("GetCount").First();

            Assert.AreEqual(5, count);
              }
        }