Exemplo n.º 1
0
        public ActionResult Product(int?id, string name, string email, int?rating, string comments)
        {
            // Initialize an object of ProductReview from the DB
            ProductReview review = db.ProductReviews.Create();

            //If any of the fields are null then we have to stop, collaborate and listen.
            if (id == null || id.Equals("") || name == null || name.Equals("") || email == null || email.Equals("") || rating == null || rating.Equals("") || comments == null || comments.Equals(""))
            { //reloads the page
                return(View(ProductDetails(id)));
            }

            // add all the attributes of a Product Review to add it to the db
            review.Comments     = comments;
            review.EmailAddress = email;
            review.ModifiedDate = DateTime.Now; // correct the date/time format
            review.ProductID    = (int)id;
            review.Rating       = (int)rating;
            review.ReviewDate   = DateTime.Now;
            review.ReviewerName = name;

            if (ModelState.IsValid)               //error checking to make sure that everything was passed correctly and all the datatypes match
            {
                db.ProductReviews.Add(review);    //add it to the database
                db.SaveChanges();                 //save the database
                return(View(ProductDetails(id))); //reload the page
            }

            return(RedirectToAction("Index")); //if it fails reload the home page
        }
Exemplo n.º 2
0
        public ActionResult Review(FormCollection form, int?id)
        {
            if (id == null)
            {
                return(RedirectToAction("Index"));
            }
            if (form.Get("user") == "" || form.Get("email") == "" || form.Get("comment") == "")
            {
                return(RedirectToAction("Review"));
            }
            var format       = "MM-dd-yyyy HH:mm:ss:fff";
            var stringDate   = DateTime.Now.ToString(format);
            var reviewDate   = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);
            var modifiedDate = DateTime.ParseExact(stringDate, format, CultureInfo.InvariantCulture);

            int rating = Convert.ToInt32(form.Get("rating"));

            var review = new ProductReview
            {
                ProductID    = id.Value,
                ReviewerName = form.Get("user"),
                ReviewDate   = reviewDate,
                EmailAddress = form.Get("email"),
                Rating       = rating,
                Comments     = form.Get("comment"),
                ModifiedDate = modifiedDate
            };

            db.ProductReviews.Add(review);
            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
Exemplo n.º 3
0
        public ActionResult Create([Bind(Include = "ProductID,Name,ProductNumber,MakeFlag,FinishedGoodsFlag,Color,SafetyStockLevel,ReorderPoint,StandardCost,ListPrice,Size,SizeUnitMeasureCode,WeightUnitMeasureCode,Weight,DaysToManufacture,ProductLine,Class,Style,ProductSubcategoryID,ProductModelID,SellStartDate,SellEndDate,DiscontinuedDate,rowguid,ModifiedDate")] Product product)
        {
            if (ModelState.IsValid)
            {
                db.Products.Add(product);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.ProductID             = new SelectList(db.ProductDocuments, "ProductID", "ProductID", product.ProductID);
            ViewBag.ProductModelID        = new SelectList(db.ProductModels, "ProductModelID", "Name", product.ProductModelID);
            ViewBag.ProductSubcategoryID  = new SelectList(db.ProductSubcategories, "ProductSubcategoryID", "Name", product.ProductSubcategoryID);
            ViewBag.SizeUnitMeasureCode   = new SelectList(db.UnitMeasures, "UnitMeasureCode", "Name", product.SizeUnitMeasureCode);
            ViewBag.WeightUnitMeasureCode = new SelectList(db.UnitMeasures, "UnitMeasureCode", "Name", product.WeightUnitMeasureCode);
            return(View(product));
        }
Exemplo n.º 4
0
        public ActionResult Product(int?id, string name, string email, int?rating, string comments)
        {
            // create a new ProductReview object
            ProductReview review = db.ProductReviews.Create();

            if (id == null || id.Equals("") || name == null || name.Equals("") || email == null || email.Equals("") || rating == null || rating.Equals("") || comments == null || comments.Equals(""))
            {
                return(RedirectToAction("Failure"));
            }

            // add all the attributes of a Product Review to add it to the db
            review.Comments     = comments;
            review.EmailAddress = email;
            review.ModifiedDate = DateTime.Now; // correct date/time format
            review.ProductID    = (int)id;
            review.Rating       = (int)rating;
            review.ReviewDate   = DateTime.Now;
            review.ReviewerName = name;

            if (ModelState.IsValid)
            {
                db.ProductReviews.Add(review);
                db.SaveChanges();
                return(RedirectToAction("Success"));
            }

            return(RedirectToAction("Index"));
        }
Exemplo n.º 5
0
        public IActionResult UpdatePerson(Person updatedPerson)
        {
            if (ModelState.IsValid)
            {
                Person person = db.Person.FirstOrDefault(p => p.BusinessEntityId == updatedPerson.BusinessEntityId);
                person.FirstName  = updatedPerson.FirstName;
                person.MiddleName = updatedPerson.MiddleName;
                person.LastName   = updatedPerson.LastName;
                person.Title      = updatedPerson.Title;
                db.Person.Update(person);
                db.SaveChanges();
                return(RedirectToAction("GetPerson", new { num = updatedPerson.BusinessEntityId }));
            }

            return(RedirectToAction("GetPerson", updatedPerson));
        }
Exemplo n.º 6
0
        public Core.Models.Product InsertProduct(Core.Models.Product product)
        {
            var addProduct = Factory.CreateProductEntity(product);

            AdventureWorksContext.Add(addProduct);
            AdventureWorksContext.SaveChanges();
            return(Factory.CreateProductDTO(addProduct));
        }
Exemplo n.º 7
0
        public IActionResult Put([FromRoute] int id, [FromBody] Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != product.ProductId)
            {
                return(BadRequest());
            }

            _context.Entry(product).State = EntityState.Modified;
            _context.SaveChanges();

            return(Ok(product));
        }
Exemplo n.º 8
0
        public IActionResult DeleteComment(int id)
        {
            var review = _context.ProductReviews.Find(id);

            if (review == null)
            {
                return(NotFound());
            }

            if (User == null || !User.IsInRole("Admin"))
            {
                return(Forbid());
            }

            _context.ProductReviews.Remove(review);
            _context.SaveChanges();
            return(Redirect(Request.Headers["Referer"].ToString()));
        }
Exemplo n.º 9
0
        public E Create(E entity)
        {
            try
            {
                E output = _context.Set <E>().Add(entity);
                _context.SaveChanges();

                return(output);
            } catch (DbUpdateException e)
            {
                CheckDbConstraintValidations(e, entity);

                throw e;
            } catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 10
0
        private static void Main()
        {
            using (var db = new AdventureWorksContext())
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                foreach (var accountNumber in GetAccountNumbers(2000))
                {
                    db.Add(new Customer {
                        AccountNumber = accountNumber,
                    });
                }

                db.SaveChanges();
            }

            // Warmup
            using (var db = new AdventureWorksContext())
            {
                var customer = db.Customers.First();
            }

            RunTest(
                accountNumbers =>
            {
                using (var db = new AdventureWorksContext())
                {
                    foreach (var id in accountNumbers)
                    {
                        // Use a regular auto-compiled query
                        var customer = db.Customers.Single(c => c.AccountNumber == id);
                    }
                }
            },
                name: "Regular");

            RunTest(
                accountNumbers =>
            {
                // Create an explicit compiled query
                var query = EF.CompileQuery(
                    (AdventureWorksContext db, string id)
                    => db.Customers.Single(c => c.AccountNumber == id));

                using (var db = new AdventureWorksContext())
                {
                    foreach (var id in accountNumbers)
                    {
                        // Invoke the compiled query
                        query(db, id);
                    }
                }
            },
                name: "Compiled");
        }
Exemplo n.º 11
0
        public void UploadImage(byte[] image, string mimeType, int empNo)
        {
            var employee = _ctx.Employees.Find(empNo);

            if (employee != null)
            {
                employee.Photo = image;
                _ctx.SaveChanges();
            }
        }
Exemplo n.º 12
0
 public ActionResult Review(ProductReview reviews)
 {
     if (ModelState.IsValid)
     {
         db.ProductReviews.Add(reviews);
         db.SaveChanges();
         return(RedirectToAction("Product", new { id = reviews.ProductID }));
     }
     reviews.Product = db.Products.Find(reviews.ProductID);
     return(View(reviews));
 }
Exemplo n.º 13
0
        public void GenerateData()
        {
            var bulkConfig = new BulkConfig {
                SetOutputIdentity = true, BatchSize = 4000
            };

            //var fakeCustomers = new Faker<Customer>()
            //    .RuleFor(c => c.Title, f => f.Name.Prefix())
            //    .RuleFor(c => c.FirstName, f => f.Name.FirstName())
            //    .RuleFor(c => c.LastName, f => f.Name.LastName())
            //    .RuleFor(c => c.CompanyName, f => f.Company.CompanyName())
            //    .RuleFor(c => c.SalesPerson, f => f.Internet.Email())
            //    .RuleFor(c => c.EmailAddress, f => f.Internet.Email())
            //    .RuleFor(c => c.Phone, f => f.Phone.PhoneNumber())
            //    .RuleFor(c => c.PasswordHash, f => f.Random.Hash())
            //    .RuleFor(c => c.PasswordSalt, f => f.Random.AlphaNumeric(8))
            //    .RuleFor(c => c.Rowguid, f => Guid.NewGuid());


            //var customerResult = fakeCustomers.Generate(3000);
            //context.BulkInsert(customerResult, bulkConfig);

            var customerDB = context.Customers.ToList();

            //var fakeAddresses = new Faker<Address>()
            //   .RuleFor(c => c.AddressLine1, f => f.Address.StreetAddress())
            //   .RuleFor(c => c.City, f => f.Address.City())
            //   .RuleFor(c => c.StateProvince, f => "Washington")
            //   .RuleFor(c => c.CountryRegion, f => "United States")
            //   .RuleFor(c => c.Rowguid, f => Guid.NewGuid())
            //   .RuleFor(c => c.PostalCode, f => f.Address.ZipCode());

            //var addressesResult = fakeAddresses.Generate(10000);
            //context.BulkInsert(addressesResult, bulkConfig);
            var addressDB = context.Addresses.ToList();


            var fakeCustomerAddresses = new Faker <CustomerAddress>()
                                        .RuleFor(c => c.Rowguid, f => Guid.NewGuid())
                                        .RuleFor(c => c.AddressType, f => "Office")
                                        .RuleFor(c => c.Address, f => f.PickRandom(addressDB))
                                        .RuleFor(c => c.Customer, f => f.PickRandom(customerDB));

            var customerAddressesResult = fakeCustomerAddresses.Generate(10000);

            //context.BulkInsert(customerAddressesResult, bulkConfig);

            foreach (var item in customerAddressesResult)
            {
                context.CustomerAddresses.Add(item);
                context.SaveChanges();
            }
        }
Exemplo n.º 14
0
        private static AdventureWorksContext InitTestDB()
        {
            var options = new DbContextOptionsBuilder <AdventureWorksContext>()
                          .UseInMemoryDatabase(databaseName: "AWListDatabase" + DateTime.Now.ToFileTimeUtc())
                          .Options;

            var context = new AdventureWorksContext(options);

            context.Products.Add(new Product {
                ProductId = 1, Name = "Prod1", Class = "Class1", ProductSubcategoryId = 1, ListPrice = 2, StandardCost = 3,
            });
            context.Products.Add(new Product {
                ProductId = 2, Name = "Prod2", Class = "Class2", ProductSubcategoryId = 2, ListPrice = 4, StandardCost = 2,
            });
            context.Products.Add(new Product {
                ProductId = 3, Name = "Prod3", Class = "Class3", ProductSubcategoryId = 3, ListPrice = 3, StandardCost = 1,
            });

            context.ProductCategories.Add(new ProductCategory {
                Name = "Cat1", ProductCategoryId = 1,
            });
            context.ProductCategories.Add(new ProductCategory {
                Name = "Cat2", ProductCategoryId = 2,
            });
            context.ProductCategories.Add(new ProductCategory {
                Name = "Cat3", ProductCategoryId = 3,
            });

            context.ProductSubcategories.Add(new ProductSubcategory {
                Name = "SubCat1", ProductSubcategoryId = 1, ProductCategoryId = 1
            });
            context.ProductSubcategories.Add(new ProductSubcategory {
                Name = "SubCat2", ProductSubcategoryId = 2, ProductCategoryId = 2
            });
            context.ProductSubcategories.Add(new ProductSubcategory {
                Name = "SubCat3", ProductSubcategoryId = 3, ProductCategoryId = 3
            });

            context.ProductPhotos.Add(new ProductPhoto {
                ProductPhotoId = 1, ThumbNailPhoto = new byte[] { 1, 2, 3 }
            });
            context.ProductPhotos.Add(new ProductPhoto {
                ProductPhotoId = 2, ThumbNailPhoto = new byte[] { 2, 3, 1 }
            });
            context.ProductPhotos.Add(new ProductPhoto {
                ProductPhotoId = 3, ThumbNailPhoto = new byte[] { 3, 1, 2 }
            });

            context.SaveChanges();

            return(context);
        }
Exemplo n.º 15
0
 public static void AddRecordsAndSave()
 {
     using (var db = new AdventureWorksContext())
     {
         for (int i = 0; i < 1000; i++)
         {
             db.ProductCategories.Add(new ProductCategory {
                 Name = $"Test {Guid.NewGuid()}"
             });
         }
         db.SaveChanges();
     }
 }
        public ProductsController(AdventureWorksContext context)
        {
            _db = context;
            if (context.Products.Count() == 0)
            {
                foreach (var p in adventureworksDataSource.GetProducts())
                {
                    context.Products.Add(p);
                }

                context.SaveChanges();
            }
        }
Exemplo n.º 17
0
 public async Task <IActionResult> FormularioCrearAccionInmediata(AccionInmediataModels AI)
 {
     if (ModelState.IsValid)
     {
         AccionInmediata Accion = new AccionInmediata()
         {
             FechaRegistro = DateTime.Now,
             Descripcion   = AI.Descripcion,
             Removed       = false,
             EventoId      = AI.EventoId,
             RutPersona    = AI.RutPersona,
             Efectivo      = AI.Efectiva,
         };
         db.AccionInmediata.Add(Accion);
         db.SaveChanges();
         return(RedirectToAction("Index", "EventoSecuencia", new { EventoID = AI.EventoId }));
     }
     else
     {
         return(await FormularioCrearAccionInmediata(AI.EventoId.TrimEnd()));
     }
 }
Exemplo n.º 18
0
        public AdventureWorksContext BuildContext(params PurchaseOrderHeader[] purchaseOrders)
        {
            var context = new AdventureWorksContext(GenerateContextOptions());

            if (purchaseOrders.Length == 0)
            {
                return(context);
            }

            context.PurchaseOrderHeader.AddRange(purchaseOrders);
            context.SaveChanges();
            return(context);
        }
        public void Test1()
        {
            using (var transaction = _context.Database.BeginTransaction())
            {
                var catCount    = _context.ProductCategory.Count();
                var subCatCount = _context.ProductSubcategory.Count();

                //Category and SubCategory have Relations
                var productCategory = new ProductCategory()
                {
                    Name = "New ProductCategory",
                    ProductSubcategory = new List <ProductSubcategory>()
                    {
                        new ProductSubcategory()
                        {
                            Name = "New SubCategory 1"
                        },
                        new ProductSubcategory()
                        {
                            Name = "New SubCategory 2"
                        },
                        new ProductSubcategory()
                        {
                            Name = "New SubCategory 3"
                        }
                    }
                };
                _context.ProductCategory.Add(productCategory);
                _context.SaveChanges();
                Assert.Equal(catCount + 1, _context.ProductCategory.Count());
                Assert.Equal(subCatCount + 3, _context.ProductSubcategory.Count());

                _context.ProductSubcategory.RemoveRange(productCategory.ProductSubcategory);
                _context.ProductCategory.Remove(productCategory);
                _context.SaveChanges();

                transaction.Rollback();
            }
        }
        public OrderDetailsController(AdventureWorksContext context)
        {
            _db = context;
            if (context.OrderDetails.Count() == 0)
            {
                foreach (var o in adventureworksDataSource.GetOrderDetails())
                {
                    context.OrderDetails.Add(o);
                }

                context.SaveChanges();
            }
        }
        public void ShouldDeleteEntityUsingState()
        {
            using (var transaction = _context.Database.BeginTransaction())
            {
                //Arrange the test
                var product = TestHelpers.CreateProduct("1");
                _context.Add(product);
                _context.SaveChanges();
                var productId = product.ProductId;
                Assert.Equal(1, _context.Product.Count(p => p.ProductId == productId));

                _context.Entry(product).State = EntityState.Detached;

                //Act
                _context.Entry(product).State = EntityState.Deleted;
                _context.SaveChanges();

                //Assert
                Assert.Equal(0, _context.Product.Count(p => p.ProductId == productId));

                transaction.Rollback();
            }
        }
Exemplo n.º 22
0
            public async Task <IActionResult> FormularioCrearPersona(CreatePersona model)
            {
                if (ModelState.IsValid)
                {
                    string rut = model.rut.TrimEnd().Replace(".", "").ToUpper();
                    rut = rut.Replace(",", "");
                    rut = rut.Replace("-", "");
                    rut = rut.Replace("_", "");

                    if (db.Persona.FirstOrDefault(c => c.Rut.TrimEnd().Equals(rut)) != null)
                    {
                        ModelState.AddModelError("Error", "Ya existe una persona con ese rut, ingresar un rut distinto para continuar");
                        return(await FormularioCrearPersona());
                    }
                    Persona persona = new Persona()
                    {
                        Rut             = rut,
                        Nombre          = model.Nombre,
                        ApellidoPaterno = model.ApellidoPaterno,
                        ApellidoMaterno = model.ApellidoMaterno,
                        Sexo            = model.Sexo,
                        RutSupervisor   = model.RutSupervisor,
                        IdArea          = model.IdArea,
                        IdSubArea       = model.IdSubArea,
                        Removed         = false,
                        Cargo           = model.Cargo,
                    };
                    db.Persona.Add(persona);
                    db.SaveChanges();

                    return(RedirectToAction("CuentasPersonas"));
                }
                else
                {
                    return(await FormularioCrearPersona());
                }
            }
        // PUT: odata/PhoneNumberTypes(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <PhoneNumberType> patch)
        {
            Validate(patch.GetInstance());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            PhoneNumberType phoneNumberType = _db.PhoneNumberTypes.Find(key);

            if (phoneNumberType == null)
            {
                return(NotFound());
            }

            patch.Put(phoneNumberType);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PhoneNumberTypeExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(phoneNumberType));
        }
        internal static void SeedData(AdventureWorksContext ctx)
        {
            try
            {
                if (!ctx.BusinessEntity.Any())
                {
                    ctx.Shift.AddRange(SampleData.GetHumanResourceShifts());
                    ctx.Department.AddRange(SampleData.GetHRDepartments());
                    ctx.SaveChanges();

                    ctx.BusinessEntity.AddRange(SampleData.GetBusinessEntities());
                    ctx.SalesTerritory.AddRange(SampleData.GetSalesTerritories());
                    ctx.SaveChanges();

                    AddAddressesAndContactsToVendor(ctx);
                    AddAddressesToEmployees(ctx);
                    AddEmployeeDeptHistoryToDb(ctx);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"*** SeedData() Error: {ex}");
            }
        }
        // PUT: odata/CountryRegions(5)
        public IHttpActionResult Put([FromODataUri] string key, Delta <CountryRegion> patch)
        {
            Validate(patch.GetInstance());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            CountryRegion countryRegion = _db.CountryRegions.Find(key);

            if (countryRegion == null)
            {
                return(NotFound());
            }

            patch.Put(countryRegion);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CountryRegionExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(countryRegion));
        }
Exemplo n.º 26
0
        public IHttpActionResult PutProduct(int id, Product product)
        {
            Log.Information("Updating product by id={ID}", id);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != product.ProductID)
            {
                return(BadRequest());
            }

            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    Log.Error("Updating failed: product with id={Id} doesn't exist", id);
                    return(NotFound());
                }
                else
                {
                    Log.Information("Updating failed for product by id={ID}", id);
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 27
0
        // PUT: odata/EmailAddresses(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <EmailAddress> patch)
        {
            Validate(patch.GetInstance());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            EmailAddress emailAddress = _db.EmailAddresses.Find(key);

            if (emailAddress == null)
            {
                return(NotFound());
            }

            patch.Put(emailAddress);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmailAddressExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(emailAddress));
        }
        // PUT: odata/BusinessEntities(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <BusinessEntity> patch)
        {
            Validate(patch.GetInstance());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            BusinessEntity businessEntity = _db.BusinessEntities.Find(key);

            if (businessEntity == null)
            {
                return(NotFound());
            }

            patch.Put(businessEntity);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BusinessEntityExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(businessEntity));
        }
Exemplo n.º 29
0
        // PUT: odata/Currencies(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <DimCurrency> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            DimCurrency dimCurrency = db.DimCurrencies.Find(key);

            if (dimCurrency == null)
            {
                return(NotFound());
            }

            patch.Put(dimCurrency);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DimCurrencyExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(dimCurrency));
        }
Exemplo n.º 30
0
        public void Test1()
        {
            var count = _context.Product.Count();

            var product1 = TestHelpers.CreateProduct("1");

            _context.Product.Add(product1);
            var product2 = new Product()
            {
                ProductId = 3
            };

            _context.Product.Add(product2);

            try
            {
                _context.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            Assert.Equal(count, _context.Product.Count());
        }