Ejemplo n.º 1
0
 public async Task <List <ProviderDTO> > GetProvider()
 {
     using (MarketContext context = new MarketContext())
     {
         return(await context.Providers.ToListAsync());
     }
 }
Ejemplo n.º 2
0
        public PriceAction Dep_GetPriceAction(DateTime dt)
        {
            PriceAction pa = new PriceAction(PriceActionType.UnKnown, new Volatility(-1, -1, -1, -1));

            //int key_date = GetDateByDateTime(dt);
            string        key_date = GetDateStrByDateTime(dt);
            int           t        = dt.Hour * 100 + dt.Minute;
            MarketContext mkt_ctxs = null;

//			Dictionary<int,PriceAction> mkt_ctxs = null;
//			if(Dict_SpvPR != null)
//				Dict_SpvPR.TryGetValue(key_date, out mkt_ctxs);
//			if(Dict_SpvPR2 != null)
//				Dict_SpvPR2.TryGetValue(key_date, out mkt_ctxs);

//			Print("key_date, time, Dict_SpvPR, mkt_ctxs=" + key_date
//			+ "," + t.ToString() + "," + Dict_SpvPR2.Count + "," + mkt_ctxs);
            if (mkt_ctxs != null)
            {
//				foreach(var mkt_ctx in mkt_ctxs) {
//					Print("time, start, end, mkt_ctx=" + t + "," +
//					mkt_ctx.Key + "," + mkt_ctx.Value);
//					int start = mkt_ctx.Key/10000;
//					int end = mkt_ctx.Key % 10000;

//					if(t >= start && t <= end) {
//						pa = mkt_ctx.Value;
//						break;
//					}
//				}
            }
            return(pa);
        }
 public DeleteItemPipeline(ILogger <ItemParameters> logger, MarketContext marketContext) : base(logger)
 {
     this.logger = logger;
     Add(new ValidateProcess(logger));
     Add(new GetMarketEntityProcess(logger, marketContext));
     Add(new CommitProcess(logger, marketContext));
 }
Ejemplo n.º 4
0
        public void ParseAllXml(string directory)
        {
            var fileExtractor = new FileExtractor();

            fileExtractor.DecompressGzFiles(directory, "PriceFull");

            var storesXmls = fileExtractor.GetXmlFilePaths(directory, "Stores");

            foreach (var storeXml in storesXmls)
            {
                using (var context = new MarketContext())
                {
                    ParseStoresXml(context, storeXml);
                }
            }

            var priceFullXmls = fileExtractor.GetXmlFilePaths(directory, "PriceFull");

            foreach (var priceFullXml in priceFullXmls)
            {
                using (var context = new MarketContext())
                {
                    ParsePricesXml(context, priceFullXml);
                }
            }
        }
Ejemplo n.º 5
0
 public async Task <List <BrandDTO> > GetBrands()
 {
     using (MarketContext context = new MarketContext())
     {
         return(await context.Brands.ToListAsync());
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// 搜索合同信息
        /// </summary>
        /// <param name="content">搜索条件</param>
        /// <returns></returns>
        public static ResultDTO GetSearchData(string content)
        {
            var db     = new MarketContext();
            var result = new Dictionary <string, object>();

            //按客户搜索
            var sql       = @"select PartyA as ID,PartyAName as Name,count(PartyA) as Count from dbo.S_C_ManageContract
group by PartyA,PartyAName having PartyAName like '%{0}%'";
            var customers = db.Database.SqlQuery <ContractStatisticsDTO>(string.Format(sql, content));

            result.Add(ContractSearchEnum.Customers.ToString(), new Dictionary <string, object> {
                { "Count", customers.Count() }, { "Data", customers }
            });

            //按合同搜索
            sql = @"select ID,Name from dbo.S_C_ManageContract where Name like '%{0}%'";
            var contracts = db.Database.SqlQuery <ContractStatisticsDTO>(string.Format(sql, content)).Select(p => new { ID = p.ID, Name = p.Name });

            result.Add(ContractSearchEnum.Contracts.ToString(), new Dictionary <string, object> {
                { "Count", contracts.Count() }, { "Data", contracts }
            });

            //按销售负责人搜索
            sql = @"select BusinessManager as ID,BusinessManagerName as Name,count(BusinessManager) as Count 
from dbo.S_C_ManageContract 
group by BusinessManagerName,BusinessManager 
having BusinessManagerName like '%{0}%'";
            var users = db.Database.SqlQuery <ContractStatisticsDTO>(string.Format(sql, content));

            result.Add(ContractSearchEnum.Users.ToString(), new Dictionary <string, object> {
                { "Count", users.Count() }, { "Data", users }
            });
            return(WebApi.Success(result));
        }
Ejemplo n.º 7
0
 public async Task <List <EmployeeDTO> > GetEmployee()
 {
     using (MarketContext context = new MarketContext())
     {
         return(await context.Employees.ToListAsync());
     }
 }
Ejemplo n.º 8
0
        public void InitializeCartWithKnownCustomerStoresValueInCustomerId()
        {
            //will add mocking later ...

            using (var separateContext = new MarketContext())
            {
                if (!separateContext.Customers.Any(c => c.CustomerCookie == "CustomerCookieABCDE"))
                {
                    separateContext.Customers.Add(new Customer
                    {
                        CustomerCookie = "CustomerCookieABCDE",
                        DateOfBirth    = DateTime.Now,
                        FirstName      = "Julie",
                        LastName       = "Lerman"
                    });
                    separateContext.SaveChanges();
                }
            }
            var service = new WebSiteOrderingService(new WebSiteOrderData(_context));

            SetupLogging();
            RevisitedCart cart = service.ItemSelected(1, 1, 9.99m, theUri, "CustomerCookieABCDE", 0);

            WriteLog();
            Assert.AreNotEqual(0, _context.Carts.Find(cart.CartId).CustomerId);
        }
 public GenericRepositoryIntegrationTests()
 {
     Database.SetInitializer(new NullDatabaseInitializer <MarketContext>());
     _context            = new MarketContext();
     _customerRepository = new GenericRepository <Customer>(_context);
     SetupLogging();
 }
Ejemplo n.º 10
0
        static void Purchase(User user)
        {
            Console.Clear();
            ShowAssortimentsList();
            Console.WriteLine("*********************************\n" +
                              "Добавьте в корзину товар для пoкупки по его номеру: ");
            int choice = 0;

            Market market = new Market();

            using (var context = new MarketContext())
            {
                while (choice == 0)
                {
                    int.TryParse(Console.ReadLine(), out choice);
                    if (choice < 0 || choice > context.Markets.Count())
                    {
                        choice = 0;
                    }
                    else
                    {
                        market = context.Markets.FirstOrDefault(m => m.Id == choice);
                        break;
                    }
                }


                Basket basket = new Basket
                {
                    UserId   = user.Id,
                    User     = user,
                    MarketId = market.Id,
                    Market   = market
                };

                context.Baskets.Add(basket);
                context.SaveChanges();

                List <Basket> baskets = new List <Basket>();

                Console.WriteLine("Просмотр корзины: ");
                foreach (var b in context.Baskets.ToList())
                {
                    Console.WriteLine($"Пользователь: {b.User.Email}," +
                                      $" Товар: {b.Market.Product}," +
                                      $" Цена: {b.Market.Price}," +
                                      $" Вес(кг.): {b.Market.Quantity},");
                    baskets.Add(b);
                }

                foreach (var b in baskets)
                {
                    if (b != null)
                    {
                        context.Baskets.Remove(b);
                        context.SaveChanges();
                    }
                }
            }
        }
Ejemplo n.º 11
0
 public async Task <IEnumerable <Company> > GetCompanies()
 {
     using (var context = new MarketContext())
     {
         return(await context.Companies.ToListAsync());
     }
 }
Ejemplo n.º 12
0
        public static ResultDTO GetData(string type)
        {
            var    dt    = DateTime.Now;
            var    year  = dt.Year;
            var    month = dt.Month;
            var    db    = new MarketContext();
            string sql   = "";

            if (type == EnumBusiness.Receipt.ToString())
            {
                sql = @"SELECT BelongYear,BelongMonth,
                        Convert(decimal(18,2),isnull(SUM(Amount),0)/10000) AS SumAmount 
                        FROM S_C_Receipt
                        WHERE BelongYear > (year(getdate())-5) and BelongMonth<=datepart(month,getdate())
                        GROUP BY BelongMonth,BelongYear
                        ORDER BY BelongYear DESC,BelongMonth ASC";
            }
            else
            {
                sql = @"select BelongYear,BelongMonth,
                        Convert(decimal(18,2),isnull(Sum(ContractRMBAmount),0)/10000) AS SumAmount  from S_C_ManageContract
                        WHERE BelongYear > (year(getdate())-5) and BelongMonth<=datepart(month,getdate()) and IsSigned='Signed'
                        GROUP BY BelongMonth,BelongYear
                        ORDER BY BelongYear DESC,BelongMonth ASC";
            }

            var list = db.Database.SqlQuery <BusinessOverviewBll>(sql);

            var single     = new List <Dictionary <string, object> >();
            var cumulation = new List <Dictionary <string, object> >();

            for (var i = year; i > year - 5; i--)
            {
                var     temp           = list.Where(p => p.BelongYear == i);
                var     singledata     = new List <decimal>();
                var     cumulationdata = new List <decimal>();
                decimal sum            = 0;

                for (var j = 1; j <= month; j++)
                {
                    var item    = temp.FirstOrDefault(p => p.BelongMonth == j);
                    var account = item == null ? 0 : item.SumAmount;
                    sum += account;
                    singledata.Add(account);
                    cumulationdata.Add(sum);
                }

                single.Add(new Dictionary <string, object> {
                    { "year", i }, { "data", singledata }
                });
                cumulation.Add(new Dictionary <string, object> {
                    { "year", i }, { "data", cumulationdata }
                });
            }
            var result = new Dictionary <string, object> {
                { "single", single }, { "cumulation", cumulation }
            };

            return(WebApi.Success(result));
        }
Ejemplo n.º 13
0
 public GetAllItemPipeline(ILogger <ItemParameters> logger, IMapper mapper, MarketContext marketContext) : base(logger)
 {
     this.logger = logger;
     Add(new ValidateProcess(logger));
     Add(new GetProcess(logger, marketContext));
     Add(new MapDtoProcess(logger, mapper));
 }
Ejemplo n.º 14
0
        public IHttpActionResult GetChains()
        {
            var context = new MarketContext();
            var chains  = context.Chains.Select(c => new
            {
                name    = c.Name,
                chainId = c.ChainID,
                stores  = c.Stores.Select(s => new
                {
                    storeId = s.StoreID,
                    name    = s.Name,
                    adress  = s.Address,
                    city    = s.City,
                    prices  = s.Prices.Where(p => p.Item.Prices.Count > 8).Select(p => new
                                                                                  //Prices = s.Prices.Where(p => p.Item.Prices.Count > 8).Select(p => new
                    {
                        productPrice = p.ItemPrice,
                        product      = new
                        {
                            name             = p.Item.Name,
                            id               = p.ItemID,
                            units            = p.Item.Units,
                            unitsQuantity    = p.Item.UnitsQuantity,
                            selectedQuantity = 1
                        }
                    })
                })
            });

            return(Json(chains));
        }
Ejemplo n.º 15
0
 public async Task <IEnumerable <Stock> > GetStocks(Company company)
 {
     using (var context = new MarketContext())
     {
         return(await context.Stocks.Where(s => s.CompanyId == company.Id).ToListAsync());
     }
 }
Ejemplo n.º 16
0
        public static void Initialize(MarketContext context)
        {
            context.Database.EnsureCreated();

            if (context.Set <ProductEntity>().Any())
            {
                return;   // DB has been seeded
            }

            var products = new ProductEntity[]
            {
                new ProductEntity {
                    Code = "39533028", Name = "Elcykel Allegro", Description = "En smart och tillförlitlig elcykel för dam från Batavus utmärkt både för långa och kortare turer.", Category = "Sport", Price = 18499 / 1.125
                },
                new ProductEntity {
                    Code = "40266837", Name = "Lapierre Overvolt Urban 300", Description = "Praktisk och bekväm elcykel med upprätt körställning.", Category = "Sport", Price = 20990 / 1.125
                },
                new ProductEntity {
                    Code = "p35372817", Name = "Chrome cast 2nd generationen", Description = "Visar film eller annan media från mobilen på TV:n", Category = "Hemelektronik", Price = 390 / 1.125
                },
                new ProductEntity {
                    Code = "35552289", Name = "Apple TV 64GB 4th generation", Description = "Nu kommer App Store till din tv. Du kan förvänta dig massor av spännande spel.", Category = "Hemelektronik", Price = 1990 / 1.125
                },
                new ProductEntity {
                    Code = "40151785", Name = "Big Foot truck 2wd", Description = "Det här är bilen som startade alltihop och skapade den idag enorma monster-truck trenden.", Category = "Leksaker", Price = 2795 / 1.125
                }
            };

            foreach (var prod in products)
            {
                context.Set <ProductEntity>().Add(prod);
            }
            context.SaveChanges();
        }
        private void btnPesquisar_Click(object sender, EventArgs e)
        {
            if (double.Parse(txbPrecoMin.Text) > double.Parse(txbPrecoMax.Text))
            {
                MessageBox.Show("Preço mínimo não pode ser maior que preço máximo. ");
            }
            else if (double.Parse(txbPrecoMax.Text) < double.Parse(txbPrecoMin.Text))
            {
                MessageBox.Show("Preço máximo não pode ser menor que preço mínimo. ");
            }
            else
            {
                using (MarketContext _context = new MarketContext())
                {
                    var consulta = from Acao a in _context.Acoes
                                   where a.CotacaoAtual >= double.Parse(txbPrecoMin.Text) &&
                                   a.CotacaoAtual <= double.Parse(txbPrecoMax.Text)
                                   select a;

                    List <Acao> acoes = new List <Acao>();
                    foreach (var cons in consulta)
                    {
                        acoes.Add(cons);
                    }

                    dataGridView1.DataSource = acoes;
                }
            }
        }
 private void frmListarPreco_Load(object sender, EventArgs e)
 {
     using (MarketContext _context = new MarketContext())
     {
         dataGridView1.DataSource = _context.Acoes.ToList();
     }
 }
Ejemplo n.º 19
0
 public async Task Insert(CategoryDTO category)
 {
     using (MarketContext context = new MarketContext())
     {
         context.Categories.Add(category);
         await context.SaveChangesAsync();
     }
 }
Ejemplo n.º 20
0
 public void CadastratAcao(Acao a)
 {
     using (DbContext _context = new MarketContext())
     {
         _context.Add(a);
         _context.SaveChanges();
     }
 }
Ejemplo n.º 21
0
 public async Task Insert(BrandDTO brand)
 {
     using (MarketContext context = new MarketContext())
     {
         context.Brands.Add(brand);
         await context.SaveChangesAsync();
     }
 }
Ejemplo n.º 22
0
        /// <summary>
        /// 获取实际收款(当季、当月、本周)
        /// </summary>
        /// <param name="type">查询条件</param>
        /// <param name="date"></param>
        /// <returns></returns>
        public static ResultDTO GetCurrentActualReceipt(string type, DateEnum date)
        {
            string sql, condition = "";

            switch (date)
            {
            case DateEnum.Month:
                condition = "BelongYear = YEAR(getDate()) AND BeLongMonth = MONTH(getDate())";
                break;

            case DateEnum.Quarter:
                condition = "BelongYear = YEAR(getDate()) AND BelongQuarter = datepart(quarter,getdate())";
                break;

            case DateEnum.Week:
                condition = "(ArrivedDate between dateadd(wk, datediff(wk,0,getdate()), 0)  and getdate())";
                break;
            }

            var db = new MarketContext();

            EnumQueryType con = (EnumQueryType)System.Enum.Parse(typeof(EnumQueryType), type);

            switch (con)
            {
            case EnumQueryType.Customer:
                sql = @"select CustomerID as ID,CustomerName AS Name
                            ,Convert(decimal(18,2),isnull(SUM(Amount),0)/10000) AS TotalMoney
                            ,count(distinct ContractInfoID)  as ContractCount
                            ,COUNT(DISTINCT ID) AS RecordNum from S_C_Receipt WHERE {0} 
                            GROUP BY CustomerName,CustomerID
                            ORDER BY TotalMoney DESC";
                break;

            case EnumQueryType.Department:
                sql = @"SELECT ReceiptMasterUnitID as ID,ReceiptMasterUnit as Name
                            ,Convert(decimal(18,2),isnull(SUM(Amount),0)/10000) AS TotalMoney
                            ,count(distinct ContractInfoID) as ContractCount
                            ,COUNT(DISTINCT CustomerID) AS RecordNum  
                            FROM S_C_Receipt WHERE {0} 
                            GROUP BY ReceiptMasterUnit,ReceiptMasterUnitID
                            ORDER BY TotalMoney DESC";
                break;

            case EnumQueryType.NotGroup:
                sql = @"select ContractInfoID as ID,ContractName as Name,
                            COUNT(ContractName) AS RecordNum,
                            Convert(decimal(18,2),isnull(SUM(Amount)/10000,0)) AS ReceiptValue,
                            MAX(ArrivedDate) AS LastTime from S_C_Receipt WHERE {0}
                            GROUP BY ContractName,ContractInfoID
                            ORDER BY ReceiptValue DESC";
                return(WebApi.Success(db.Database.SqlQuery <ContractBll>(string.Format(sql, condition))));

            default:
                return(WebApi.Error(EnumException.请求参数不合法));
            }
            return(WebApi.Success(db.Database.SqlQuery <BusinessDetailBll>(string.Format(sql, condition))));
        }
Ejemplo n.º 23
0
        public Cart(IMemoryCache cache, IHttpContextAccessor contextAccessor, MarketContext db)
        {
            this.cache = cache;
            this.db    = db;
            var sessionId = contextAccessor.HttpContext.Request.Cookies[".AspNetCore.Session"];

            id = $"Goods-Card-{sessionId}";
            InitializeGoodsSets();
        }
 public UpdateItemPipeline(ILogger <ItemParameters> logger, IMapper mapper, MarketContext marketContext) : base(logger)
 {
     this.logger = logger;
     Add(new MapToDomainProcess(logger, mapper));
     Add(new ValidateProcess(logger));
     Add(new GetMarketEntityProcess(logger, marketContext));
     Add(new CommitProcess(logger, marketContext));
     Add(new MapFromProductProcess(logger));
     Add(new MapDtoProcess(logger, mapper));
 }
Ejemplo n.º 25
0
        public int CreateShop(Shop shop)
        {
            using (MarketContext db = new MarketContext())
            {
                Shop entity = db.Shops.Add(shop);
                db.SaveChanges();

                return(entity.ShopId);
            }
        }
Ejemplo n.º 26
0
 static void ShowAssortimentsList()
 {
     using (var context = new MarketContext())
     {
         Console.WriteLine("Ассортимент:");
         foreach (var p in context.Markets.ToList())
         {
             Console.WriteLine($"{p.Id}. {p.Product}: цена - {p.Price}, колличество - {p.Quantity}");
         }
     }
 }
Ejemplo n.º 27
0
 public string Configuration(MarketContext key)
 {
     if (_configurations.ContainsKey(key))
     {
         return(_configurations[key]);
     }
     else
     {
         return(Market.DefaultConfiguration);
     }
 }
Ejemplo n.º 28
0
 public virtual void Update()
 {
     try
     {
         dbContext = dbContext ?? new MarketContext();
         dbContext.SaveChanges(); //GetByID ile ürünü başka yerlerde çekip REFERANSTAN değişir. Sonra orada değişiklikleri yap. Sonra sadece update etmen gerekir.
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 29
0
 public virtual T GetByID(ID id)
 {
     try
     {
         dbContext = new MarketContext();
         return(dbContext.Set <T>().Find(id));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 30
0
 protected internal static MarketContext dbContext; //bulunduğu projeden erişilir.Bulunduğu projeden kalıtım alırsa kullanabilir.
 public virtual List <T> GetAll()
 {
     try
     {
         dbContext = new MarketContext();
         return(dbContext.Set <T>().ToList());
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 31
0
 public MarketService()
 {
     _context = new MarketContext();
 }