Example #1
0
		public ActionResult Index()
		{
			List<Customer> customers;

			using (var ctx = new SalesContext())
			{
				ctx.Database.Log = DebugMsg;
				customers = ctx.Customers.ToList();
			}

			return View(customers);
		}
Example #2
0
        public static string CheckManagerEmployeeMatch(SalesContext context, Employee employee)
        {
            Employee manager = context.Employee.Find(employee.ManagerId);

            if (manager != null &&
                manager.FirstName == employee.FirstName &&
                manager.LastName == employee.LastName &&
                manager.DateOfBirth == employee.DateOfBirth)
            {
                return($"Manager and employee cannot be the same");
            }
            return(string.Empty);
        }
        internal static void InitialStoresSeed(SalesContext db)
        {
            for (int i = 0; i < storeNames.Length; i++)
            {
                Store currentStore = new Store()
                {
                    Name = storeNames[i]
                };

                db.Stores.Add(currentStore);
                db.SaveChanges();
            }
        }
Example #4
0
 private static void ProductsMigration(SalesContext context)
 {
     foreach (var sale in context.Sales
              .Include("Product")
              .Include("Customer")
              .Include("StoreLocation"))
     {
         Console.WriteLine($"{sale.Date.ToLocalTime()} - " +
                           $"{sale.StoreLocation.LocationName} sold " +
                           $"{sale.Product.Name} ({sale.Product.Description}) to " +
                           $"{sale.Customer.Email}");
     }
 }
Example #5
0
        private void btnDeleteSale_Click(object sender, EventArgs e)
        {
            using (var context = new SalesContext())
            {
                var saleId = Int32.Parse(tbUpdateID.Text);

                var saleToDelete = context.Sales.SingleOrDefault(p => p.id == saleId);

                context.Sales.Remove(saleToDelete);
                context.SaveChanges();
                MessageBox.Show("Sale deleted", "Notice", MessageBoxButtons.OK);
            }
        }
Example #6
0
 public IHttpActionResult GetPriorities()
 {
     try
     {
         SalesContext _db        = new SalesContext();
         var          priorities = _db.BuyerPriorities.AsQueryable();
         return(Ok(priorities));
     }
     catch (Exception ex)
     {
         return(Ok(ex));
     }
 }
Example #7
0
        private SalesContext CreateAndSeedContext()
        {
            var optionsBuilder = new DbContextOptionsBuilder <SalesContext>();

            optionsBuilder.UseInMemoryDatabase();
            var context = new SalesContext(_config, optionsBuilder.Options);

            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();
            context.CartItem.AddRange(BuildCartItems());
            context.SaveChanges();
            return(context);
        }
Example #8
0
        public IHttpActionResult GetProductsById(int Id)
        {
            try
            {
                SalesContext _db     = new SalesContext();
                var          product = _db.Products.FirstOrDefault(x => x.ID == Id);

                return(Ok(product));
            }
            catch (Exception exception)
            {
                return(InternalServerError(exception));
            }
        }
Example #9
0
        // 非公開方法,單純示範把全部的查詢處理都寫在 controller 動作方法中(分頁、篩選、排序實際上還是在 DB 端執行)。
        public async Task <GetCustomersResponse> GetCustomersV0([FromUri] GetCustomersRequest request)
        {
            // 明白起見,把建立 DbContext 的程式碼放在這裡。實際上不會這樣做。
            SalesContext salesContext = new SalesContext();

            var customersQuery = salesContext.Customers.AsQueryable();

            // 建立篩選條件
            if (!string.IsNullOrWhiteSpace(request.Name))
            {
                customersQuery = customersQuery.Where(c => c.Name.Contains(request.Name));
            }
            if (!string.IsNullOrWhiteSpace(request.Country))
            {
                customersQuery = customersQuery.Where(c => c.Country.Equals(request.Country));
            }

            // 排序
            switch (request.SortOrder.ToLower())
            {
            case "country":
            case "country asc":
                customersQuery = customersQuery.OrderBy(c => c.Country);
                break;

            case "country desc":
                customersQuery = customersQuery.OrderByDescending(c => c.Country);
                break;

            case "name desc":
                customersQuery = customersQuery.OrderByDescending(c => c.Name);
                break;

            default:
                customersQuery = customersQuery.OrderBy(c => c.Name);
                break;
            }

            // 分頁(使用 PagedList.EntityFramework)
            var pagedResult = await customersQuery.ToPagedListAsync(request.Page, request.PageSize);

            // 轉換成 View Model
            var customerModels = pagedResult.Select(ConvertToCustomerViewModel);

            return(new GetCustomersResponse
            {
                Succeeded = true,
                Customers = customerModels.ToArray()
            });
        }
Example #10
0
        public Controller(string directoryPath, string filesFilter)
        {
            _context = new SalesContext();

            _locker = new ReaderWriterLockSlim();

            DirectoryHandler = new DirectoryHandler(directoryPath, filesFilter);

            Unit = new Unit(_context, _locker);

            Parser = new Parser();

            FileHandler = new FileHandler(Unit, Parser, _locker);
        }
        public IActionResult About()
        {
            ViewData["Message"] = "Using this for orders at the moment.";

            using (var context = new SalesContext())
            {
                context.Materials.Load();
                context.Items.Load();
                var orders = context.Orders
                             .Include(x => x.Client)
                             .Include(x => x.OrderLines).ToList();
                return(View(orders));
            }
        }
Example #12
0
 public async static Task DeleteGoodsReceipt(GoodsReceipt itemPara)
 {
     using (var db = new SalesContext())
     {
         //if (itemPara.Store != null)                                   //NOT DELETE - IMPORTANT
         //    db.Stores.Attach(itemPara.Store);
         //if (itemPara.Product != null)                                   //NOT DELETE - IMPORTANT
         //    db.Products.Attach(itemPara.Product);
         db.Entry(itemPara).State = EntityState.Unchanged;                       //NOT DELETE - IMPORTANT
         GoodsReceipts.Remove(itemPara);
         db.Entry(itemPara).State = EntityState.Deleted;
         await UpdateDatabase(db);
     }
 }
Example #13
0
        public async Task <IHttpActionResult> AddToCart(dynamic data)
        {
            var cartId    = (int)data.CartId;
            var productId = (int)data.ProductId;
            var quantity  = (int)data.Quantity;
            var requestId = Request.Headers.GetValues("request-id").Single();

            using (var db = new SalesContext())
            {
                var cart = db.ShoppingCarts
                           .Include(c => c.Items)
                           .Where(o => o.Id == cartId)
                           .SingleOrDefault();
                if (cart == null)
                {
                    cart = new ShoppingCart()
                    {
                        Id = data.CartId
                    };
                    db.ShoppingCarts.Add(cart);
                }

                var alreadyAdded = cart.Items.Any(item => item.RequestId == requestId);
                if (!alreadyAdded)
                {
                    var product = db.ProductsPrices
                                  .Where(o => o.ProductId == productId)
                                  .Single();

                    cart.Items.Add(new ShoppingCartItem()
                    {
                        CartId       = cartId,
                        RequestId    = requestId,
                        ProductId    = productId,
                        ProductPrice = product.Price,
                        Quantity     = quantity
                    });

                    await ServiceBus.Instance.Publish <ProductAddedToCart>(e =>
                    {
                        e.CartId    = cartId;
                        e.ProductId = productId;
                    });
                }

                await db.SaveChangesAsync();
            }

            return(StatusCode(HttpStatusCode.OK));
        }
Example #14
0
        /// <summary>
        /// Get the list of Sales based on the selected Sales Person and Sales Region.
        /// </summary>
        private void GetSales()
        {
            var personId = (int)peopleComboBox.SelectedValue;
            var regionId = (int)regionComboBox.SelectedValue;

            using (var context = new SalesContext())
            {
                saleBindingSource.DataSource = context.Sales
                                               .Where(s => s.PersonId == personId &&
                                                      s.RegionId == regionId)
                                               .OrderBy(s => s.Date)
                                               .ToList();
            }
        }
        public async Task ShouldReturnActiveCart()
        {
            var configBuilder = new ConfigurationBuilder()
                                .AddJsonFile("appsettings.json")
                                .Build();
            var connectionString = configBuilder.GetConnectionString("SalesConnection");
            var optionsBuilder   = new DbContextOptionsBuilder <SalesContext>().UseSqlServer(connectionString).UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug()));
            var db = new SalesContext(optionsBuilder.Options);

            var cartID     = Guid.NewGuid();
            var pID        = Guid.NewGuid();
            var amount     = 10m;
            var currency   = "EUR";
            var lastAmount = 5m;

            db.Database.ExecuteSqlRaw("TRUNCATE TABLE Items");
            db.Database.ExecuteSqlRaw("DELETE FROM Carts");
            db.Carts.Add(new Cart(cartID)
            {
                State = CartState.Active, Items = new List <Item> {
                    new Item(pID, currentPrice: new Price(amount, currency), lastPrice: new Price(lastAmount, currency), 1)
                }
            });
            db.SaveChanges();

            var handler = new ActiveCartHandler(db);

            var expected = new ActiveCart
            {
                CartID = cartID,
                Items  = new List <ActiveCart.Item>
                {
                    new ActiveCart.Item
                    {
                        ProductID    = pID,
                        Quantity     = 1,
                        CurrentPrice = new ActiveCart.Price {
                            Amount = amount, Currency = currency
                        },
                        LastPrice = new ActiveCart.Price {
                            Amount = lastAmount, Currency = currency
                        }
                    }
                }
            };

            var response = await handler.Handle(new ActiveCartQuery(), CancellationToken.None);

            response.Should().Be(expected);
        }
Example #16
0
        private void DatabaseContextCreation(IServiceCollection services)
        {
            var serviceProvider = services.BuildServiceProvider();
            var databaseOptions = new DbContextOptionsBuilder <SalesContext>()
                                  .UseInMemoryDatabase(databaseName: "Fabi_Rest_Api_Db")
                                  .Options;

            var salesContext = new SalesContext(databaseOptions, serviceProvider.GetService <IRestApiLogger>());

            salesContext.Customers.AddRange(CustomerInMemoryData.GetCustomerInMemoryData());
            salesContext.Apps.AddRange(AppInMemoryData.GetAppInMemoryData());
            salesContext.SaveChanges();
            services.AddSingleton <SalesContext>(salesContext);
        }
Example #17
0
        public override void Seed(SalesContext db)
        {
            var rand = new Random();

            var date = RandomDay(rand);

            db.Sales.Add(new Sale
            {
                Date     = date,
                Customer = db.Customers.Find(1),
                Product  = db.Products.Find(1),
                Store    = db.Stores.Find(1),
            });
        }
Example #18
0
        /// <summary>
        ///   Retrieves all orders in the system.
        /// </summary>
        /// <returns></returns>
        public async Task <IEnumerable <Order> > GetOrdersAsync()
        {
            using (var context = new SalesContext())
            {
                context.Materials.Load();
                context.Items.Load();
                var orders = await context.Orders
                             .Include(x => x.Client)
                             .Include(x => x.OrderLines)
                             .ToListAsync();

                return(orders);
            }
        }
Example #19
0
        private void SalesTargetButton_Click(object sender, EventArgs e)
        {
            var personnId = (int)peopleComboBox.SelectedValue;

            using (var context = new SalesContext())
            {
                var person = context.People
                             .SingleOrDefault(p => p.Id == personnId);
                if (person != null)
                {
                    MessageBox.Show($"{person.FullName} has a sales target of {person.SalesTarget:C}");
                }
            }
        }
Example #20
0
        static void Main(string[] args)
        {
            //EX 1,2
//            var ctx = new LocalStoreContext();
//            ctx.Database.Initialize(true);

//            foreach (var product in ctx.Products)
//            {
//                Console.WriteLine(product.Name + " " + product.Quantity);
//            }

            //EX 3
            var ctx = new SalesContext();
        }
Example #21
0
 private void addButton_Click(object sender, EventArgs e)
 {
     if (string.IsNullOrEmpty(firstNbox.Text.ToString()) || string.IsNullOrEmpty(lastNBox.Text.ToString()))
     {
         MessageBox.Show("Enter a First and Last name to continue.");
     }
     else
     {
         string city = null, country = null, phone = null;
         if (string.IsNullOrEmpty(cityBox.Text.ToString()))
         {
             city = null;
         }
         else
         {
             city = cityBox.Text.ToString();
         }
         if (string.IsNullOrEmpty(countryBox.Text.ToString()))
         {
             country = null;
         }
         else
         {
             country = countryBox.Text.ToString();
         }
         if (string.IsNullOrEmpty(phoneBox.Text.ToString()))
         {
             phone = null;
         }
         else
         {
             phone = phoneBox.Text.ToString();
         }
         SalesContext stx     = new SalesContext();
         var          newUser = new Customer
         {
             FirstName = firstNbox.Text.ToString(),
             LastName  = lastNBox.Text.ToString(),
             City      = city,
             Country   = country,
             Phone     = phone
         };
         stx.Add <Customer>(newUser);
         stx.SaveChanges();
         userData.DataSource         = stx.Customers.OrderBy(c => c.Id).ToList();
         userData.Columns[0].Visible = false;
         this.Close();
     }
 }
Example #22
0
        public static string CheckSales(SalesContext context, Sales sale)
        {
            Sales sales = context.Sales.FirstOrDefault(
                s => s.EmployeeId == sale.EmployeeId &&
                s.Year == sale.Year &&
                s.Quarter == sale.Quarter);

            if (sales == null)
            {
                return(string.Empty);
            }
            Employee employee = context.Employee.Find(sale.EmployeeId);

            return($"Sales for {employee.FullName} for {sale.Year}and{sale.Quarter} already exist.");
        }
        public static Customer NewCustomer(SalesContext context)
        {
            var name             = GenerateName(Names);
            var domain           = GenerateDomain(Domains);
            var creditCardNumber = GenerateCreditCardNumber(CreditCardNumber);

            var customer = new Customer
            {
                Name             = name,
                CreditCardNumber = creditCardNumber,
                Email            = domain
            };

            return(customer);
        }
Example #24
0
 public async Task <dynamic> Get(int orderNumber)
 {
     using (var sales = new SalesContext())
     {
         return(await sales.Orders
                .Include(order => order.Items)
                .Where(order => order.OrderNumber == orderNumber)
                .Select(order => new
         {
             OrderNumber = order.OrderNumber,
             ItemsCount = order.Items.Count,
         })
                .SingleOrDefaultAsync());
     }
 }
        public void CanDetachFromDbSetAndAttachToAnotherContext()
        {
            Person person;

            using (var sC = new SalesContext())
            {
                person = sC.People.FirstOrDefault(p => p.FirstName == "Dave");
            }
            using (var tC = new TripPlanningContext())
            {
                tC.People.Attach(person);
                tC.Entry(person).Collection(p => p.PrimaryContactFor).Load();
            }
            Assert.IsTrue(person.PrimaryContactFor.Count > 0);
        }
Example #26
0
        private void btnTargetSales_Click(object sender, EventArgs e)
        {
            var personId = (int)cbSalesPeople.SelectedValue;
            var regionId = (int)cbSalesRegion.SelectedValue;

            using (var context = new SalesContext())
            {
                var person = context.SalesPeople.SingleOrDefault(p => p.id == personId);

                if (person != null)
                {
                    MessageBox.Show(string.Format("{0} has a target of {1}", person.FullName, person.SalesTarget));
                }
            }
        }
Example #27
0
 private void GetLists()
 {
     using (var context = new SalesContext())
     {
         salesPersonBindingSource.DataSource = context.People
                                               .Where(e => e.Active)
                                               .OrderBy(e => e.FirstName)
                                               .ThenBy(e => e.LastName)
                                               .ToList();
         salesRegionBindingSource.DataSource = context.Regions
                                               .Where(e => e.Active)
                                               .OrderBy(e => e.Name)
                                               .ToList();
     }
 }
Example #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <SalesContext>(opt =>
                                                 opt.UseInMemoryDatabase("SalesList"));
            //I called this method here to fill the context just once
            var options = new DbContextOptionsBuilder <SalesContext>().UseInMemoryDatabase(databaseName: "SalesList").Options;

            using (var context = new SalesContext(options))
            {
                PopulateDB.Populate(context);
            }

            services.AddScoped <SalesContext, SalesContext>();
            services.AddControllersWithViews();
        }
Example #29
0
        /// <summary>
        /// Display the Sales Target for a single Sales Person.
        /// </summary>
        private void GetSalesTarget()
        {
            var personId = (int)peopleComboBox.SelectedValue;

            using (var context = new SalesContext())
            {
                var person = context.People.SingleOrDefault(p => p.Id == personId);

                if (person != null)
                {
                    MessageBox.Show(string.Format("{0} has a sales target of {1:C}",
                                                  person.FullName, person.SalesTarget));
                }
            }
        }
Example #30
0
      public IHttpActionResult GetDesignations()
      {
          try
          {
              SalesContext _db          = new SalesContext();
              var          Designations = _db.BuyerDesignations.AsQueryable();
              return(Ok(Designations));
          }


          catch (Exception ex)
          {
              return(InternalServerError(ex));
          }
      }
Example #31
0
        private void salesTargetButton_Click(object sender, EventArgs e)
        {
            var personId = (int)peopleComboBox.SelectedValue;

            using (var context = new SalesContext())
            {
                var person = context.People.SingleOrDefault(p => p.Id == personId);

                if (person != null)
                {
                    MessageBox.Show(string.Format("{0} has a sales target of {1:C}",
                                                  person.Fullname, person.SalesTarget));
                }
            }
        }
		public Example()
        {
            InitializeComponent();

			ColumnSortDescriptor salesSortDescriptor = new ColumnSortDescriptor();
			salesSortDescriptor.Column = this.radGridView.Columns[1];
			salesSortDescriptor.SortDirection = System.ComponentModel.ListSortDirection.Descending;
			this.radGridView.SortDescriptors.Add(salesSortDescriptor);
			
			SalesContext context = new SalesContext();
			EntityQuery<Year> distinctOrderYearsQuery = context.GetDistinctOrderYearsQuery();
			context.Load<Year>(distinctOrderYearsQuery
				, LoadBehavior.RefreshCurrent
				, this.OnDistinctOrderYearsLoaded
				, null);

			this.loadTimer = new DispatcherTimer();
			loadTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
			loadTimer.Tick += this.OnLoadTimerTick;
			loadTimer.Start();
        }
Example #33
0
        static void Main(string[] args)
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SalesContext>());

            using (var context = new SalesContext())
            {
                Customer customer = new Customer
                {
                    Name = "Michael Tsai"
                };
                context.Customers.Add(customer);
                context.SaveChanges();

                Console.WriteLine(context.Customers.First().Name);
            }

            //BankAccount wallet = new BankAccount
            //{
            //    Balance = 100
            //};

        }
 public CustomersController()
 {
     objContext = new SalesContext();
 }
Example #35
0
 public CustomerCommand(SalesContext context)
 {
     _salesContext = context;
 }
Example #36
0
 public CustomerQueries(SalesContext context)
 {
     _salesContext = context;
 }
 public OrdersController()
 {
     objContext = new SalesContext();
 }