public void UploadDiamond_Replace()
        {
            ProductServiceTestHelper.UploadDiamond("product_diamond_1.csv", ProductFileUploadType.Replace);
            ProductServiceTestHelper.UploadDiamond("product_diamond_3.csv", ProductFileUploadType.Replace);
            var imports = default(IEnumerable<ProductDiamondImport>);
            var diamonds = default(IEnumerable<ProductDiamond>);
            using (var db = new ProductDbContext())
            {
                imports = db.DiamondImports.OrderBy(d => d.Created).ToArray();
                diamonds = db.Diamonds.ToArray();
            }

            Assert.AreEqual(2, imports.Count());
            Assert.AreEqual(1, diamonds.Count());

            {
                var import = imports.ElementAt(0);
                Assert.AreEqual(2, import.Count);
            }

            {
                var import = imports.ElementAt(1);
                Assert.AreEqual(1, import.Count);
            }

            ValidateDiamond(diamonds, 3, false);
        }
 public static void CleanupDatabase()
 {
     using (var db = new ProductDbContext())
     {
         db.Database.ExecuteSqlCommand("DELETE tc_product_diamond");
         db.Database.ExecuteSqlCommand("DELETE tc_product_diamond_import");
         db.SaveChanges();
     }
 }
 public void GetDiamondImportById()
 {
     var import = default(ProductDiamondImport);
     using (var db = new ProductDbContext())
     {
         import = db.DiamondImports.First();
     }
     var token = ODataClientHelper.InvokeGet(string.Format("{0}DiamondImports({1})", ProductServiceRootUrl, import.Id));
     Compare(import, token);
 }
 public void GetDiamondImportProperty()
 {
     var import = default(ProductDiamondImport);
     using (var db = new ProductDbContext())
     {
         import = db.DiamondImports.First();
     }
     var token = ODataClientHelper.InvokeGet(string.Format("{0}DiamondImports({1})/Count", ProductServiceRootUrl, import.Id));
     Assert.AreEqual(import.Count, (int)token);
 }
Beispiel #5
0
        static async Task Main(string[] args)
        {
            DbContextOptions   options           = new DbContextOptionsBuilder().UseInMemoryDatabase("products").Options;
            ProductDbContext   context           = new ProductDbContext(options);
            IProductRepository productRepository = new DatabaseProductRepository(context);

            IProductWriter productWriter = new FileProductWriter(new FileWriter(), "products.txt");

            await Run(productRepository, productWriter);
        }
Beispiel #6
0
 private void _getData()
 {
     //显示数据
     using (var context = new ProductDbContext())
     {
         var productList = context.Products.OrderBy(x => x.SN).ToList();
         GridView1.DataSource = productList;
         GridView1.DataBind();
     }
 }
Beispiel #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ProductDbContext productDbContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
            productDbContext.Database.EnsureCreated();
        }
 public void GetDiamondById()
 {
     var diamond = default(ProductDiamond);
     using (var db = new ProductDbContext())
     {
         diamond = db.Diamonds.First();
     }
     var token = ODataClientHelper.InvokeGet(string.Format("{0}Diamonds({1})", ProductServiceRootUrl, diamond.Id));
     Compare(diamond, token);
 }
        public ProductRepository(ProductDbContext product)
        {
            _db = product;
            MapperConfiguration cofiguration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <ProductDto, ProductModel>().ReverseMap();
            });

            _mapper = cofiguration.CreateMapper();
        }
 public void TestGetProductByNameNotFound()
 {
     using (var context = new ProductDbContext(builder.Options))
     {
         SetUpTestData(context);
         IProductRepository productRepository = new ProductRepository(context);
         var p = productRepository.GetProductsByName("NonExisting");
         p.Result.Should().BeEmpty();
         context.Database.EnsureDeleted();
     }
 }
 public void TestGetProductOptionByProductIdNotFound()
 {
     using (var context = new ProductDbContext(builder.Options))
     {
         SetUpTestData(context);
         IProductOptionRepository productOptionRepository = new ProductOptionRepository(context);
         var p = productOptionRepository.GetProductOptionsByProductId(new Guid());
         p.Result.Should().BeEmpty();
         context.Database.EnsureDeleted();
     }
 }
 public void TestGetProductOptionByIdNotFound()
 {
     using (var context = new ProductDbContext(builder.Options))
     {
         SetUpTestData(context);
         IProductOptionRepository productOptionRepository = new ProductOptionRepository(context);
         ProductOption            po = productOptionRepository.GetById(new Guid());
         po.Should().BeNull();
         context.Database.EnsureDeleted();
     }
 }
Beispiel #13
0
        public UnitOfWork(ProductDbContext dbContext, IMapper mapper, IProductRepository productRepository)
        {
            if (dbContext == null)
            {
                throw new ArgumentNullException("dbContext can not be null.");
            }

            _dbContext         = dbContext;
            _mapper            = mapper;
            _productRepository = productRepository;
        }
Beispiel #14
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (context != null)
         {
             context.Dispose();
             context = null;
         }
     }
 }
        public async Task <int> Execute(OutputParameters parameters)
        {
            string configFile        = parameters.ConfigFilePath ?? DefaultConfigFile;
            string configFileContent = File.ReadAllText(configFile);

            var    configuration    = JsonConvert.DeserializeObject <Configuration>(configFileContent);
            string databaseServer   = parameters.DatabaseServer ?? configuration.DatabaseServer;
            string databaseName     = parameters.DatabaseName ?? configuration.DatabaseName;
            string username         = parameters.Username ?? configuration.Username;
            string password         = parameters.Password ?? configuration.Password;
            int    checkInterval    = parameters.CheckInterval ?? configuration.CheckInterval;
            int    topAmount        = parameters.TopAmount ?? configuration.TopAmount;
            int    minutesToInclude = parameters.MinutesToInclude ?? configuration.MinutesToInclude;
            int    secondsToWait    = parameters.SecondsToWait ?? configuration.SecondsToWait;

            Console.TreatControlCAsInput = true;

            var cancellationTokenSource = new CancellationTokenSource();

            var logConfiguration = new LoggingConfiguration();

            var now     = DateTime.Now;
            var logfile = new FileTarget {
                FileName = $"generated-{now:yyyyMMddHHmmss}.log"
            };
            var logconsole = new ConsoleTarget();

            logConfiguration.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            logConfiguration.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

            LogManager.Configuration = logConfiguration;

            var logger = LogManager.GetCurrentClassLogger();

            logger.Log(LogLevel.Info, $"Waiting {secondsToWait}s for database startup...");

            await Task.Delay(TimeSpan.FromSeconds(secondsToWait));

            logger.Log(LogLevel.Info, "To quit the application, press [CTRL]+[C]");
            logger.Log(LogLevel.Info, $"Connecting to {databaseServer}; Database name {databaseName}; User: {username}");

            using (var dbcontext = new ProductDbContext(databaseServer, databaseName, username, password))
            {
                dbcontext.Database.Migrate();
                var timeoutLoopTask = TimeoutLoop(checkInterval, cancellationTokenSource);
                var fetchLoopTask   = FetchLoop(topAmount, TimeSpan.FromMilliseconds(minutesToInclude), dbcontext, cancellationTokenSource);
                var inputLoopTask   = InputLoopAsync(cancellationTokenSource);

                Task.WaitAll(timeoutLoopTask, fetchLoopTask, inputLoopTask);
            }


            return(0);
        }
        public void GetDiamondImports()
        {
            var tokens = ODataClientHelper.GetServerPaging(ProductServiceRootUrl + "DiamondImports");
            Assert.AreEqual(2, tokens.Count);
            var imports = default(IList<ProductDiamondImport>);
            using (var db = new ProductDbContext())
            {
                imports = db.DiamondImports.ToArray();
            }

            CompareCollection(imports, tokens, Compare);
        }
 public Product UpdateProductById(int productIdToEdit, Product productEditValues)
 {
     using (var db = new ProductDbContext())
     {
         var productToEdit = db.Products.First(product => product.ProductId == productIdToEdit);
         productToEdit.Price = productEditValues.Price;
         productToEdit.Name  = productEditValues.Name;
         db.Products.Update(productToEdit);
         db.SaveChanges();
         return(productToEdit);
     }
 }
 public TransactionsController(ILogger <TransactionsController> logger,
                               ProductDbContext dbContext,
                               CancellationTaskRabbitMqMessageSender messageSender,
                               IdentityGenerator generator,
                               IConfiguration configuration)
 {
     Logger        = logger;
     DbContext     = dbContext;
     MessageSender = messageSender;
     Generator     = generator;
     Configuration = configuration;
 }
 public ProductUnitTestDb()
 {
     scope = new TransactionScope(TransactionScopeOption.Required,
       new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },
       TransactionScopeAsyncFlowOption.Enabled);
   
     productDbContext = new ProductDbContext(ConnectionString); 
     factoryMock = new Mock<IDBContextFactory>();
     productRepo = new ProductRepo(factoryMock.Object);
     factoryMock.Setup(o => o.createDbContext<IProductDbContext>(It.IsAny<String>()))
         .Returns(productDbContext);
 }
Beispiel #20
0
 public List <Product> GetAllProduct()
 {
     try
     {
         pro = new ProductDbContext();
     }
     catch (Exception ex)
     {
         string r = ex.Message;
     }
     return(pro.Products.ToList());
 }
Beispiel #21
0
        public ProductDbContext CreateContextForSqlServer()
        {
            var connection = new SqlConnection("Data Source=(localdb)\\mssqlLocaldb;Initial Catalog=EcommerceDbTest;Integrated Security=True;Pooling=False");

            connection.Open();

            var option = new DbContextOptionsBuilder <ProductDbContext>().UseSqlServer(connection).Options;

            var context = new ProductDbContext(option);

            return(context);
        }
        private static async Task SeedData(ProductDbContext dbContext)
        {
            var categoryBlue = new Category
            {
                Name        = "Blue",
                Description = "This is the Blue Category"
            };

            var categoryRed = new Category
            {
                Name        = "Red",
                Description = "This is the Red Category"
            };

            var productRed1 = new Product
            {
                Name        = "Product Red 1",
                Description = "This is the Product Red 1",
                Image       = "This is the Image for Product Red 1",
                Price       = 333.33m,
                Category    = categoryRed
            };

            var productRed2 = new Product
            {
                Name        = "Product Red 2",
                Description = "This is the Product Red 2",
                Image       = "This is the Image for Product Red 2",
                Price       = 444.44m,
                Category    = categoryRed
            };

            var productBlue1 = new Product
            {
                Name        = "Product Blue 1",
                Description = "This is the Product Blue 1",
                Image       = "This is the Image for Product Blue 1",
                Price       = 222.22m,
                Category    = categoryBlue
            };

            await dbContext.Categories.AddAsync(categoryRed);

            await dbContext.Categories.AddAsync(categoryBlue);

            await dbContext.Products.AddAsync(productRed1);

            await dbContext.Products.AddAsync(productRed2);

            await dbContext.Products.AddAsync(productBlue1);

            await dbContext.SaveChangesAsync();
        }
Beispiel #23
0
        /// <summary>
        /// 更新商品库存,并返回商品售卖简要信息
        /// </summary>
        /// <param name="transIdentity">分布式事务标识</param>
        /// <param name="buyItems">购买的商品精简信息</param>
        /// <returns></returns>
        public List <SellProductDto> UpdateProductOnhand(string transIdentity, IEnumerable <BuyProductDto> buyItems)
        {
            ProductDbContext context    = new ProductDbContext();
            DTController     controller = new DTController(transIdentity);

            return(controller.DistTrans3PCRequest <List <SellProductDto> >(DTS_Proxy,
                                                                           context.CurrentDataBase,
                                                                           c =>
            {
                return InnerUpdateProductOnhand(context, buyItems);
            }));
        }
Beispiel #24
0
 public ProductListWidgetService(IWidgetBasePartService widgetService,
                                 IProductService productService,
                                 IProductCategoryService productCategoryService,
                                 IApplicationContext applicationContext,
                                 IPageService pageService,
                                 ProductDbContext dbContext)
     : base(widgetService, applicationContext, dbContext)
 {
     _productService         = productService;
     _productCategoryService = productCategoryService;
     _pageService            = pageService;
 }
Beispiel #25
0
        public void Init()
        {
            var options = new DbContextOptionsBuilder <ProductDbContext>()
                          .UseInMemoryDatabase(databaseName: "Product_Context_Mock")
                          .Options;

            _productDbContext = new ProductDbContext(options);

            // TODO: move db helper in Web.API to this project after Web.API have been refactored to use persistence db
            _productDbContext.EnsureDbSeeded();
            _productService = new ProductService(_productDbContext);
        }
Beispiel #26
0
        private void CreateProducts(ProductDbContext db)
        {
            for (int i = 1; i < 11; i++)
            {
                db.ProductDtos.Add(new ProductDto()
                {
                    Id = i, Name = Guid.NewGuid().ToString(), Inventory = i + 5, Price = (decimal)(i * 3.14)
                });
            }

            db.SaveChanges();
        }
Beispiel #27
0
        public int Update(Product product)
        {
            using (ProductDbContext _db = new ProductDbContext())
            {
                Product p = _db.Products.First(e => e.ID == product.ID);

                p.Name        = product.Name;
                p.Price       = product.Price;
                p.Description = product.Description;
                _db.Entry <Product>(p).State = System.Data.Entity.EntityState.Modified;
                return(_db.SaveChanges());
            }
        }
Beispiel #28
0
 public static void Seed(ProductDbContext context)
 {
     for (int s = 0; s < 10; s++)
     {
         var c1 = new Category()
         {
             Name     = "商品" + s.ToString(),
             SortCode = s.ToString()
         };
         context.Categorys.Add(c1);
     }
     context.SaveChanges();
 }
        public void TestDeleteProductOptionOK()
        {
            using (var context = new ProductDbContext(builder.Options))
            {
                SetUpTestData(context);
                IProductOptionRepository productOptionRepository = new ProductOptionRepository(context);

                productOptionRepository.DeleteAsync(productOptions[0]);
                var currentProductOptions = productOptionRepository.GetProductOptions();
                currentProductOptions.Result.Should().BeEmpty();
                context.Database.EnsureDeleted();
            }
        }
Beispiel #30
0
        static void Main(string[] args)
        {
            using ProductDbContext context = new ProductDbContext();
            IProductRepository repository = new ProductRepository(context);

            var categoryies = repository.GetAllCategories();

            foreach (var category in categoryies)
            {
                var products = repository.GetProducts(category);
                Console.WriteLine($"{category.Name}:{products.Count}");
            }
        }
Beispiel #31
0
 public Recommender(
     // PredictionEnginePool<CourseRatingMl, RatingPrediction> predictionEnginePool,
     ProductDbContext dbContext, MLContext mlContext, ModelHolder modelHolder)
 {
     // _predictionEnginePool = predictionEnginePool;
     _dbContext        = dbContext;
     _mlContext        = mlContext;
     _modelHolder      = modelHolder;
     maxRating         = 5.0;
     maxAttempts       = 3;
     coursesPerAttempt = 52;
     requiredCourses   = 5;
 }
Beispiel #32
0
        /// <inheritdoc/>
        public void DeleteProduct(int id)
        {
            using (var context = new ProductDbContext())
            {
                var targetProduct = context.Products.FirstOrDefault(p => p.Id == id);

                if (targetProduct != null)
                {
                    context.Products.Remove(targetProduct);
                    context.SaveChanges();
                }
            }
        }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        var id = Guid.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());

        using (var context = new ProductDbContext())
        {
            //删除这条记录
            var delProduct = context.Products.Find(id);
            context.Products.Remove(delProduct);
            context.SaveChanges();
        }
        _getData();
    }
Beispiel #34
0
 public Product GetProduct(int id)
 {
     using (ProductDbContext db = new ProductDbContext())
     {
         if (db.Products.Find(id) == null)
         {
             return(null);
         }
         else
         {
             return(db.Products.Find(id));
         }
     }
 }
 private void CreateProducts(ProductDbContext dbContext)
 {
     for (int i = 1; i <= 10; i++)
     {
         dbContext.Products.Add(new Product()
         {
             Id        = i,
             Name      = Guid.NewGuid().ToString(),
             Inventory = i + 10,
             Price     = (decimal)(i * 31.3)
         });
         dbContext.SaveChanges();
     }
 }
Beispiel #36
0
        public ProductDbContext CreateContextForInMemory()
        {
            var option = new DbContextOptionsBuilder <ProductDbContext>().UseInMemoryDatabase(databaseName: "Test_Database").Options;

            var context = new ProductDbContext(option);

            if (context != null)
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            return(context);
        }
 public void AddToDb(Product product)
 {
     using (var db = new ProductDbContext())
     {
         if (product != null)
         {
             if (!db.Products.Any(p => p.Code.Equals(product.Code)))
             {
                 db.Products.Add(product);
                 db.SaveChanges();
             }
         }
     }
 }
 public void GetDiamondProperty()
 {
     var diamond = default(ProductDiamond);
     using (var db = new ProductDbContext())
     {
         diamond = db.Diamonds.First();
     }
     var token = ODataClientHelper.InvokeGet(string.Format("{0}Diamonds({1})/Cost", ProductServiceRootUrl, diamond.Id));
     Assert.AreEqual(diamond.Cost, (decimal)token);
 }