Ejemplo n.º 1
0
        private void InitContext()
        {
            var builder = new DbContextOptionsBuilder <BooksContext>()
                          .UseInMemoryDatabase("BooksDB");

            var context = new BooksContext(builder.Options);
            var books   = Enumerable.Range(1, 10)
                          .Select(i => new Book {
                BookId = i, Title = $"Sample{i}", Publisher = "Wrox Press"
            });

            context.Books.AddRange(books);
            int changed = context.SaveChanges();

            _booksContext = context;
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Create(ArticleModel model, IFormFile file)
        {
            if (!ModelState.IsValid)
            {
            }

            var path = "/ArticleCovers/" + file.FileName;

            using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            model.CoverPath = path;
            db.Articles.Add(model);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public static void PopulateDatabase()
        {
            using var context = new BooksContext(quiet: true);

            context.AddRange(
                new User {
                PhoneNumber = 4255551234, Username = "******"
            },
                new User {
                PhoneNumber = 5155552234, Username = "******"
            },
                new User {
                PhoneNumber = 18005525123, Username = "******"
            });

            context.SaveChanges();
        }
Ejemplo n.º 4
0
        private static void AddAuthor()
        {
            Console.WriteLine("Agregando un autor.");
            Console.Write("Nombres: ");
            string firstName = Console.ReadLine();

            Console.Write("Apellidos: ");
            string lastName = Console.ReadLine();
            var    author   = new BooksApp.Data.Author
            {
                FirstName = firstName,
                LastName  = lastName
            };

            context.Authors.Add(author);
            context.SaveChanges();
        }
Ejemplo n.º 5
0
 public ActionResult Create(Editora ed)
 {
     //Valido que el registro es valido
     if (ModelState.IsValid)
     {
         //Añado el registro a las editoras disponibles
         db.Editoras.Add(ed);
         //Guardo los cambios en la base de datos
         db.SaveChanges();
         //Enviame a la pagina de inicio
         return(RedirectToAction("Index"));
     }
     else
     {
         //Si paso algun error, vuelve a la pagina con la informacion del registro para que la comprueben
         return(View(ed));
     }
 }
Ejemplo n.º 6
0
        public async Task <IActionResult> Create(BookModel model, IFormFile file)
        {
            if (!ModelState.IsValid)
            {
                return(this.View());
            }

            var path = "/img/BookCovers/" + file.FileName;

            using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            model.CoverPath = "~/img/BookCovers/" + file.FileName;
            db.Books.Add(model);
            db.SaveChanges();
            return(this.RedirectToAction("Index"));
        }
Ejemplo n.º 7
0
 public ActionResult Create(CreateAutoresVM _viewModel)
 {
     //Chequeamos el estado del modelo
     if (ModelState.IsValid)
     {
         //Agregamos el registro a los autores existentes
         db.Autores.Add(_viewModel._autor);
         //Guardamos los datos
         db.SaveChanges();
         //Mandamos al usuario a la lista
         return(RedirectToAction("Index"));
     }
     else
     {
         //Si algo salio mal, lo devolvemos
         return(View(_viewModel));
     }
 }
Ejemplo n.º 8
0
        public Author CreateAuthor([Service] BooksContext context, AuthorAndBook authorAndBook)
        {
            var author = new Author()
            {
                Name  = authorAndBook.AuthorName,
                Books = new List <Book>
                {
                    new Book {
                        Title = authorAndBook.Title
                    }
                }
            };

            context.Authors.Add(author);
            context.SaveChanges();

            return(author);
        }
Ejemplo n.º 9
0
        public static void Initialize(BooksContext context)
        {
            if (!context.Books.Any())
            {
                context.Books.AddRange(
                    new Book
                {
                    name      = "Цивилизация с нуля",
                    pages     = 150,
                    price     = 150.5,
                    image     = "testImage",
                    author    = "testAuthor",
                    kolvo     = 10,
                    publisher = new Publisher("firstPublisher"),
                    category  = new Category("Художественная литература")
                },
                    new Book
                {
                    name      = "Spring in Action",
                    pages     = 1500,
                    price     = 1500.5,
                    image     = "testImage2",
                    author    = "testAuthor2",
                    kolvo     = 10,
                    publisher = new Publisher("secondPublisher"),
                    category  = new Category("Учебная литература")
                },
                    new Book
                {
                    name      = "Энциклопедия",
                    pages     = 120,
                    price     = 1240.5,
                    image     = "testImage3",
                    author    = "testAuthor3",
                    kolvo     = 10,
                    publisher = new Publisher("thirdPublisher"),
                    category  = new Category("Справочник")
                }

                    );
                context.SaveChanges();
            }
        }
        public static void PopulateDatabase()
        {
            using var context = new BooksContext(quiet: true);

            context.AddRange(
                new Shard
            {
                Token1          = "A",
                Token2          = "B",
                Token3          = "C",
                TokensProcessed = "ABC"
            },
                new Shard
            {
                Token1          = "D",
                Token2          = "H",
                Token3          = "C",
                TokensProcessed = "DH"
            },
                new Shard
            {
                Token1 = "A",
                Token2 = "B",
                Token3 = "C"
            },
                new Shard
            {
                Token1          = "D",
                Token2          = "E",
                Token3          = "F",
                TokensProcessed = "DEF"
            },
                new Shard
            {
                Token1          = "J",
                Token2          = "A",
                Token3          = "M",
                TokensProcessed = "JAM"
            });

            context.SaveChanges();
        }
Ejemplo n.º 11
0
        public Author CreateAuthorWithArgumentDescription([Service] BooksContext context,
                                                          [GraphQLDescription("Argument description: Author with a book description")]
                                                          AuthorAndBook authorAndBook)
        {
            var author = new Author()
            {
                Name  = authorAndBook.AuthorName,
                Books = new List <Book>
                {
                    new Book {
                        Title = authorAndBook.Title
                    }
                }
            };

            context.Authors.Add(author);
            context.SaveChanges();

            return(author);
        }
Ejemplo n.º 12
0
        public void UpdateCover(Book book)
        {
            using (var ctx = new BooksContext())
            {
                var updateBook = ctx.Books
                                 .Include(x => x.Covers)
                                 .First(x => x.Id == book.Id);

                var newCovers = book.Covers.Where(x => !updateBook.Covers.Any(y => y.FilePath == x.FilePath));

                foreach (var cover in newCovers)
                {
                    updateBook.Covers.Add(new Cover {
                        FilePath = cover.FilePath
                    });
                }

                ctx.SaveChanges();
            }
        }
Ejemplo n.º 13
0
        private User FindUserOrAdd(Google.Apis.Auth.GoogleJsonWebSignature.Payload payload)
        {
            var u = _context.Users.Where(x => x.Email == payload.Email).FirstOrDefault();

            if (u == null)
            {
                u = new User()
                {
                    UserId       = Guid.NewGuid(),
                    Name         = payload.Name,
                    Picture      = payload.Picture,
                    Email        = payload.Email,
                    oauthSubject = payload.Subject,
                    oauthIssuer  = payload.Issuer,
                };
                _context.Users.Add(u);
                _context.SaveChanges();
            }

            return(u);
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            var booksContext = new BooksContext();

            booksContext.Add(new Book()
            {
                Title = "Mein erstes Buch", BookId = 1, Publisher = "Selbstpublizierer"
            });
            booksContext.Add(new Book()
            {
                Title = "Mein zweites Buch", BookId = 2, Publisher = "Pakito"
            });
            booksContext.Add(new Book()
            {
                Title = "Mein drittes Buch", BookId = 3, Publisher = "Pako"
            });
            booksContext.Add(new Book()
            {
                Title = "Mein viertes Buch", BookId = 4, Publisher = "Selbstpublizierer"
            });
            booksContext.SaveChanges();
        }
Ejemplo n.º 15
0
        // Register button logic
        private void registerButton_Click(object sender, EventArgs e)
        {
            if (context.Readers.ToList().Where(r => r.nickname == nicknameTextBox.Text).Count() == 0) // Сheck nick's uniqueness
            {
                if (passwordTextBox.Text.Equals(confirmPasswordTextBox.Text))                         // Check the password
                {
                    // Creating a new user
                    Reader reader = new Reader();
                    reader.name           = nameTextBox.Text;
                    reader.nickname       = nicknameTextBox.Text;
                    reader.password       = PasswordManager.HashPassword(passwordTextBox.Text);
                    reader.spentPoints    = 0;
                    reader.receivedPoints = 0;

                    using (var ctx = new BooksContext())
                    {
                        ctx.Readers.Add(reader);
                        ctx.SaveChanges();
                    }

                    // Open Main Form
                    MessageBox.Show("User was successfully created", "Congrats");
                    LoginForm loginForm = new LoginForm();
                    loginForm.Show();
                    Hide();
                }
                else // If passwords dont match
                {
                    MessageBox.Show("Passwords don't match", "Pay attention");
                    passwordTextBox.Text        = "";
                    confirmPasswordTextBox.Text = "";
                }
            }
            else  // If user already exists
            {
                MessageBox.Show("User already exists", "Something went wrong :c");
            }
        }
Ejemplo n.º 16
0
 public void DbEntityValidationException()
 {
     DoTest(DbEntityValidationExceptionExpectation, () =>
     {
         using (var dbContext = new BooksContext())
         {
             dbContext.Books.Add(new Book
             {
                 Id   = Guid.Parse("240B10F4-11DC-4E75-B268-DA922FA6D781"),
                 Name = "Foo"
             });
             try
             {
                 dbContext.SaveChanges();
             }
             catch (DbEntityValidationException ex)
             {
                 return(ex);
             }
         }
         Assert.Fail();
         return(null);
     });
 }
Ejemplo n.º 17
0
 public void IncCountBooks(Book book)
 {
     book.Count++;
     _context.Update(book);
     _context.SaveChanges();
 }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, BooksContext db)
        {
            if (db.Database.EnsureCreated())
            {
                db.Authors.Add(new Author
                {
                    Name        = "Jane Austen",
                    DateOfBirth = new DateTime(1775, 12, 16),
                    Books       = new List <Book>
                    {
                        new Book {
                            Title = "Emma", YearOfPublication = 1815
                        },
                        new Book {
                            Title = "Persuasion", YearOfPublication = 1818
                        },
                        new Book {
                            Title = "Mansfield Park", YearOfPublication = 1814
                        }
                    }
                });

                db.Authors.Add(new Author
                {
                    Name        = "Ian Fleming",
                    DateOfBirth = new DateTime(1908, 5, 28),
                    Books       = new List <Book>
                    {
                        new Book {
                            Title = "Dr No", YearOfPublication = 1958
                        },
                        new Book {
                            Title = "Goldfinger", YearOfPublication = 1959
                        },
                        new Book {
                            Title = "From Russia with Love", YearOfPublication = 1957
                        }
                    }
                });

                db.Authors.Add(new Author
                {
                    Name        = "George Eliot",
                    DateOfBirth = new DateTime(1819, 11, 22),
                    Books       = new List <Book>
                    {
                        new Book {
                            Title = "Silas Marner", YearOfPublication = 1815
                        },
                        new Book {
                            Title = "Middlemarch", YearOfPublication = 1871
                        }
                    }
                });

                db.SaveChanges();
            }

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Books}/{action=Index}/{id?}");
            });
        }
Ejemplo n.º 19
0
 public void AddElem(Genre elem)
 {
     _context.Genres.Add(elem);
     _context.SaveChanges();
 }
Ejemplo n.º 20
0
 public void Create(Book book)
 {
     db.Books.Add(book);
     db.SaveChanges();
 }
 public void AddMenuElement(MenuElement elem)
 {
     _context.MenuElements.Add(elem);
     _context.SaveChanges();
 }
Ejemplo n.º 22
0
 public void Save()
 {
     _context.SaveChanges();
 }
 public void AddBook(Book book)
 {
     _booksContext.Books.Add(book);
     _booksContext.SaveChanges();
 }
Ejemplo n.º 24
0
 public Book CreateBook(Book createdBook)
 {
     _context.Books.Add(createdBook);
     _context.SaveChanges();
     return(createdBook);
 }
Ejemplo n.º 25
0
 public void AddElem(Book elem)
 {
     _context.Books.Add(elem);
     _context.SaveChanges();
 }
Ejemplo n.º 26
0
 public Book AddBook(Book book)
 {
     _booksContext.Books.Add(book);
     _booksContext.SaveChanges();
     return(book);
 }
Ejemplo n.º 27
0
 public void Save()
 {
     booksContext.SaveChanges();
 }
Ejemplo n.º 28
0
 public ActionResult PostCategory(Category category)
 {
     _booksContext.Categories.Add(category);
     _booksContext.SaveChanges();
     return(Ok("added"));
 }
Ejemplo n.º 29
0
 public void Save()
 {
     db.SaveChanges();
 }
Ejemplo n.º 30
0
 public void Post([FromBody] Book value)
 {
     _booksContext.Books.Add(value);
     _booksContext.SaveChanges();
 }