Пример #1
0
        public IHttpActionResult PutHotDog(int id, HotDog hotdog)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != hotdog.HotDogId)
            {
                return(BadRequest());
            }

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

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #2
0
        public IHttpActionResult PutUser(long id, User user)
        {
            if (id != user.Id)
            {
                return(BadRequest());
            }

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

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #3
0
        public IHttpActionResult PutRole(int id, Role role)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

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

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

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #4
0
        public IHttpActionResult PutPaymentDetail(int id, PaymentDetail paymentDetail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != paymentDetail.PMId)
            {
                return(BadRequest());
            }

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

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public IHttpActionResult PutPrato(string id, Prato prato)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != prato.PNome)
            {
                return(BadRequest());
            }

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

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
 public IActionResult Create([FromBody] Kisi kisi)
 {
     if (ModelState.IsValid)
     {
         _context.Kisi.Add(kisi);
         _context.SaveChanges();
         return(Created("GetByID", new { id = kisi.ID }));
     }
     return(BadRequest(kisi));
 }
Пример #7
0
        public void Add_Loan()
        {
            //ARRANGE: Create a new in memory DB for testing Add_Loans
            var options = new DbContextOptionsBuilder <WebAPIContext>()
                          .UseInMemoryDatabase(databaseName: "TestDb")
                          .Options;

            //ACT: Using one instance of the context
            using (var context = new WebAPIContext(options))
            {
                var service = new LoanRepository <Loan>(context);
                service.Add(new Loan
                {
                    BorrowerFirstName = "Hello",
                    BorrowerLastName  = "Test",
                    RepaymentAmount   = 500.7,
                    FundingAmount     = 250.55
                });
                context.SaveChanges();
            }

            //ASSERT: Using a seperate instance of the context, verify
            using (var context = new WebAPIContext(options))
            {
                Assert.Equal("Hello",
                             context.Loans.Single().BorrowerFirstName);
            }
        }
Пример #8
0
        public StuffsController(WebAPIContext context)
        {
            _context = context;
            if (!_context.Stuff.Any())
            {
                _context.Stuff.Add(new Stuff {
                    FirstName = "Иван", LastName = "Иванов", CreatedDateTime = DateTime.Now, DivisionId = 1
                });
                _context.Stuff.Add(new Stuff {
                    FirstName = "Яна", LastName = "Константинова", CreatedDateTime = DateTime.Now, DivisionId = 1
                });
                _context.Stuff.Add(new Stuff {
                    FirstName = "Петр", LastName = "Васильев", CreatedDateTime = DateTime.Now, DivisionId = 2
                });
                _context.Stuff.Add(new Stuff {
                    FirstName = "Мария", LastName = "Стронцева", CreatedDateTime = DateTime.Now, DivisionId = 2
                });

                _context.Division.Add(new Division {
                    Name = "Краснодар", CreatedDateTime = DateTime.Now
                });
                _context.Division.Add(new Division {
                    Name = "Москва", CreatedDateTime = DateTime.Now
                });

                _context.SaveChanges();
            }
        }
Пример #9
0
 public HttpResponseMessage Post([FromUri] Brand brand)
 {
     using (WebAPIContext conn = new WebAPIContext())
     {
         conn.Brands.Add(brand);
         conn.SaveChanges();
         var msg = Request.CreateResponse(HttpStatusCode.Created, brand);
         return(msg);
     }
 }
Пример #10
0
 public HttpResponseMessage Post([FromBody] Course course)
 {
     using (WebAPIContext con = new WebAPIContext())
     {
         con.Courses.Add(course);
         con.SaveChanges();
         var msg = Request.CreateResponse(HttpStatusCode.Created, course);
         return(msg);
     }
 }
Пример #11
0
        /// <summary>
        /// Create and stores a new refresh token in database
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private Guid CreateRefreshToken(User user)
        {
            user.RefreshToken       = Guid.NewGuid();
            user.RefreshTokenExpire = DateTime.UtcNow.AddMonths(6);

            _context.Update <User>(user);
            _context.SaveChanges();

            // return RefreshToken
            return(user.RefreshToken);
        }
Пример #12
0
        public async Task <ActionResult <ShoppingCart> > PostShoppingCart(ShoppingCart shoppingCart)
        {
            // Get product form database
            Product product = _context.Products.Find(shoppingCart.ProductId);

            // Cart Id
            Guid cartId = shoppingCart.CartId;

            ShoppingCart cart = new ShoppingCart();

            // Does product allready exist in shoppingcart??
            var cartItem = _context.ShoppingCart.Where(x => x.CartId == cartId && x.ProductId == product.Id).FirstOrDefault();

            if (cartItem != null)
            {
                cartItem.Amount++;
            }
            else
            {
                // Instantiate a new schoppingcart SQ:-model with the selected prodcut id
                cart = new ShoppingCart()
                {
                    CartId    = cartId,
                    ProductId = shoppingCart.ProductId,
                    Amount    = 1
                };

                // All good, put item in shoppingcart
                _context.Add <ShoppingCart>(cart);
            }

            // Update timestamp
            List <ShoppingCart> carts = await _context.ShoppingCart.Where(x => x.CartId == cartId).ToListAsync();

            carts.ForEach(x => x.TimeStamp = DateTime.Now);

            _context.SaveChanges();

            return(Ok());
        }
Пример #13
0
        public void Post([FromBody] ResultData value)
        {
            User   currentUser   = gameContext.Users.Where(x => x.Login == value.Login).FirstOrDefault();
            Result currentResult = new Result
            {
                Score  = value.Score,
                Time   = value.Time,
                UserId = currentUser.UserId
            };

            gameContext.Results.Add(currentResult);
            gameContext.SaveChanges();
        }
        public WebApplicationController(WebAPIContext context)
        {
            _context = context;

            if (_context.Spies.Count() == 0)
            {
                // Create a new TodoItem if collection is empty,
                // which means you can't delete all TodoItems.
                _context.Spies.Add(new Spies {
                    Name = "James Bond"
                });
                _context.SaveChanges();
            }
        }
        public IHttpActionResult ToggleFeature(long id)
        {
            Feature feature = db.Features.Find(id);

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


            //Create the subclass
            Feature featureModel = CreateFeature(feature, false);

            //Toggles accordingly the subclass permissions
            featureModel.Toggle();

            db.Entry(feature).State      = EntityState.Detached;
            db.Entry(featureModel).State = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FeatureExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Ok());
        }
        public bool AddItem(Item obj)
        {
            bool status;

            try
            {
                db.Items.Add(obj);
                db.SaveChanges();
                status = true;
            }
            catch (Exception)
            {
                status = false;
            }
            return(status);
        }
Пример #17
0
 public int AddSupplier(Supplier obj)
 {
     db.Suppliers.Add(obj);
     db.SaveChanges();
     return(obj.SuplNo);
 }
Пример #18
0
        public async Task <ActionResult <Order> > PostOrder(string Id, OrderViewModel orderView)
        {
            // Cart Id
            var cartId = Guid.Parse(Id);

            User user = await _context.Users.AsNoTracking()
                        .Where(x => x.Email == orderView.UserEmail)
                        .FirstOrDefaultAsync();

            // Create order
            Order newOrder = new Order()
            {
                UserId          = user.Id,
                PaymentMethodId = orderView.PaymentMethodId,
                StatusId        = 1
            };

            try
            {
                // Keep data consistant! Begin transaction!
                using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    // Add order to Entity Framework
                    _context.Orders.Add(newOrder);
                    await _context.SaveChangesAsync();

                    // Get productinformation from shoppingcart
                    var productOrders = await _context.ShoppingCart.Include(x => x.Product)
                                        .Where(x => x.CartId == cartId && x.Amount > 0)
                                        .Select(x => new ProductOrder
                    {
                        OrderId   = newOrder.Id,
                        Price     = x.Product.Price,
                        Amount    = x.Amount,
                        ProductId = x.Product.Id,
                        Discount  = (decimal)x.Product.Discount,
                    })
                                        .ToListAsync();

                    // Add all products to the ProductOrders-table
                    _context.ProductOrders.AddRange(productOrders);
                    await _context.SaveChangesAsync();

                    // Update product quantity
                    foreach (var item in productOrders)
                    {
                        var product = _context.Products.Find(item.ProductId);

                        product.Quantity = (product.Quantity - item.Amount >= 0) ?
                                           product.Quantity -= item.Amount : 0;

                        _context.Entry(product).State = EntityState.Modified;
                        await _context.SaveChangesAsync();
                    }

                    // Empty cart.
                    List <ShoppingCart> cartProducts = await _context.ShoppingCart.Where(x => x.CartId == cartId).ToListAsync();

                    _context.ShoppingCart.RemoveRange(cartProducts);
                    _context.SaveChanges();

                    // Keep cart clean by removing carts older than 3 days
                    List <ShoppingCart> oldCarts = await _context.ShoppingCart.Where(x => x.TimeStamp.AddDays(3) <= DateTime.Now).ToListAsync();

                    _context.ShoppingCart.RemoveRange(oldCarts);
                    _context.SaveChanges();

                    // Send order-confirmation mail to customer
                    //MailService mail = new MailService();
                    bool test = await _mailService.SendOrderConfirmationMailAsync(user.Email, user.FirstName, "Orderbekräftelse", newOrder.Id);

                    // Flag that the SQL-transaction has completed successfully
                    transaction.Complete();

                    return(CreatedAtAction("GetOrderById", new { id = newOrder.Id }, newOrder));
                }
            }
            catch (Exception ex)
            {
                return(new Order());
            }
        }
Пример #19
0
 public int Save()
 {
     return(mContext.SaveChanges());
 }
Пример #20
0
 public void Save()
 {
     context.SaveChanges();
 }
Пример #21
0
 public void Post([FromBody] City value)
 {
     db.Cities.Add(value);
     db.SaveChanges();
 }
        public static void Seed(this WebAPIContext dbContext)
        {
            // Add entities for DbContext instance

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 1,
                StockItemName          = "USB missile launcher (Green)",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 25.00m,
                RecommendedRetailPrice = 37.38m,
                TypicalWeightPerUnit   = 0.300m,
                MarketingComments      = "Complete with 12 projectiles",
                CustomFields           = "{ \"CountryOfManufacture\": \"China\", \"Tags\": [\"USB Powered\"] }",
                Tags          = "[\"USB Powered\"]",
                SearchDetails = "USB missile launcher (Green) Complete with 12 projectiles",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 2,
                StockItemName          = "USB rocket launcher (Gray)",
                SupplierID             = 12,
                ColorID                = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 25.00m,
                RecommendedRetailPrice = 37.38m,
                TypicalWeightPerUnit   = 0.300m,
                MarketingComments      = "Complete with 12 projectiles",
                CustomFields           = "{ \"CountryOfManufacture\": \"China\", \"Tags\": [\"USB Powered\"] }",
                Tags          = "[\"USB Powered\"]",
                SearchDetails = "USB rocket launcher (Gray) Complete with 12 projectiles",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 3,
                StockItemName          = "Office cube periscope (Black)",
                SupplierID             = 12,
                ColorID                = 3,
                UnitPackageID          = 7,
                OuterPackageID         = 6,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 10,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 18.50m,
                RecommendedRetailPrice = 27.66m,
                TypicalWeightPerUnit   = 0.250m,
                MarketingComments      = "Need to see over your cubicle wall? This is just what's needed.",
                CustomFields           = "{ \"CountryOfManufacture\": \"China\", \"Tags\": [] }",
                Tags          = "[]",
                SearchDetails = "Office cube periscope (Black) Need to see over your cubicle wall? This is just what's needed.",
                LastEditedBy  = 1,
                ValidFrom     = Convert.ToDateTime("5.1.2016 11:00:00 PM"),
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 4,
                StockItemName          = "USB food flash drive - sushi roll",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 32.00m,
                RecommendedRetailPrice = 47.84m,
                TypicalWeightPerUnit   = 0.050m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"32GB\",\"USB Powered\"] }",
                Tags          = "[\"32GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - sushi roll ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 5,
                StockItemName          = "USB food flash drive - hamburger",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 32.00m,
                RecommendedRetailPrice = 47.84m,
                TypicalWeightPerUnit   = 0.050m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"16GB\",\"USB Powered\"] }",
                Tags          = "[\"16GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - hamburger ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 6,
                StockItemName          = "USB food flash drive - hot dog",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 32.00m,
                RecommendedRetailPrice = 47.84m,
                TypicalWeightPerUnit   = 0.050m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"32GB\",\"USB Powered\"] }",
                Tags          = "[\"32GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - hot dog ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 7,
                StockItemName          = "USB food flash drive - pizza slice",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 32.00m,
                RecommendedRetailPrice = 47.84m,
                TypicalWeightPerUnit   = 0.050m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"16GB\",\"USB Powered\"] }",
                Tags          = "[\"16GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - pizza slice ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 8,
                StockItemName          = "USB food flash drive - dim sum 10 drive variety pack",
                SupplierID             = 12,
                UnitPackageID          = 9,
                OuterPackageID         = 9,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 240.00m,
                RecommendedRetailPrice = 358.80m,
                TypicalWeightPerUnit   = 0.500m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"32GB\",\"USB Powered\"] }",
                Tags          = "[\"32GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - dim sum 10 drive variety pack ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 9,
                StockItemName          = "USB food flash drive - banana",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 32.00m,
                RecommendedRetailPrice = 47.84m,
                TypicalWeightPerUnit   = 0.050m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"16GB\",\"USB Powered\"] }",
                Tags          = "[\"16GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - banana ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 10,
                StockItemName          = "USB food flash drive - chocolate bar",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 32.00m,
                RecommendedRetailPrice = 47.84m,
                TypicalWeightPerUnit   = 0.050m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"32GB\",\"USB Powered\"] }",
                Tags          = "[\"32GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - chocolate bar ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 11,
                StockItemName          = "USB food flash drive - cookie",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 32.00m,
                RecommendedRetailPrice = 47.84m,
                TypicalWeightPerUnit   = 0.050m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"16GB\",\"USB Powered\"] }",
                Tags          = "[\"16GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - cookie ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.StockItems.Add(new StockItem
            {
                StockItemID            = 12,
                StockItemName          = "USB food flash drive - donut",
                SupplierID             = 12,
                UnitPackageID          = 7,
                OuterPackageID         = 7,
                LeadTimeDays           = 14,
                QuantityPerOuter       = 1,
                IsChillerStock         = false,
                TaxRate                = 15.000m,
                UnitPrice              = 32.00m,
                RecommendedRetailPrice = 47.84m,
                TypicalWeightPerUnit   = 0.050m,
                CustomFields           = "{ \"CountryOfManufacture\": \"Japan\", \"Tags\": [\"32GB\",\"USB Powered\"] }",
                Tags          = "[\"32GB\",\"USB Powered\"]",
                SearchDetails = "USB food flash drive - donut ",
                LastEditedBy  = 1,
                ValidFrom     = DateTime.Now,
                ValidTo       = DateTime.Now.AddYears(5)
            });

            dbContext.SaveChanges();
        }