public static void WorkC() { ISalesRepository rp = new SalesRepository(); IPurchaseRepository rp1 = new PurchaseRepository(); Random ran = new Random(); Purchase p = new Purchase() { purchaseperson = "Cong lo" }; Sales s = new Sales() { Salesperson = "qua duong" }; object ob = new object(); Stopwatch st = Stopwatch.StartNew(); //Task t1 = Task.Run(() => // { // rp1.Add(p); // rp.Add(s); // rp1.Add(p); // rp1.Add(p); // rp.Add(s); // }); //Task t2 = Task.Run(() => // { // int randomID = ran.Next(1, 1000000); // rp.GetById(randomID); // rp1.GetById(randomID+100); // rp1.Add(p); // rp.Add(s); // }); //Task.WaitAll(t1,t2); var tasks = new Task[3]; for (int i = 0; i < tasks.Length; i++) { tasks[0] = Task.Run(() => { rp.Add(s); rp1.Add(p); rp1.Add(p); }); tasks[1] = Task.Run(() => { int randomID = ran.Next(1, 1000000); rp.GetById(randomID); rp1.GetById(randomID + 100); }); tasks[2] = Task.Run(() => { rp1.Add(p); rp.Add(s); }); } Task.WaitAll(tasks); st.Stop(); Console.WriteLine(st.Elapsed); }
public void TestCanAddNewOrder() { // prepare var order = new Purchase() { Date = "testPurchase" }; IPurchaseRepository repository = new PurchaseRepository(); // run repository.Add(order); // validate // use session to try to load the product using (ISession session = _sessionFactory.OpenSession()) { var fromDb = session.Get <Purchase>(order.Id); // Test that the product was successfully inserted Assert.IsNotNull(fromDb); Assert.AreNotSame(order, fromDb); Assert.AreEqual(order.Id, fromDb.Id); Assert.AreEqual(order.Date, fromDb.Date); } }
protected void AddButton_Click(object sender, EventArgs e) { try { PurchaseDetails _PurchaseDetails = new PurchaseDetails(); _PurchaseDetails.ProductCode = txtCode.Text; _PurchaseDetails.ManufacturedDate = Convert.ToDateTime(txtManufacturedDate.Text).ToShortDateString(); _PurchaseDetails.ExpireDate = Convert.ToDateTime(txtExpireDate.Text).ToShortDateString(); _PurchaseDetails.Qty = Convert.ToDecimal(txtQty.Text); _PurchaseDetails.UnitPrice = Convert.ToDecimal(txtUnitPrice.Text); _PurchaseDetails.TotalPrice = Convert.ToDecimal(txtTotalPrice.Text); _PurchaseDetails.NewMrp = Convert.ToDecimal(txtMrp.Text); _PurchaseDetails.Invoice = txtInvoice.Text; int successAdd = _PurchaseRepository.Add(_PurchaseDetails); if (successAdd > 0) { LoadPurchaseDetails(); } else { } } catch { } }
public void Post([FromBody] Purchase Purchase) { if (ModelState.IsValid) { PurchaseRepository.Add(Purchase); } }
public IHttpActionResult PostPurchases(Purchase purchase) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { _purchaseRepository.Add(purchase); } catch (DbUpdateException) { if (PurchaseExist(purchase.Id)) { return(Conflict()); } else { throw; } } return(CreatedAtRoute("DefaultApi", new { id = purchase.Id }, purchase)); }
private void btnComprar_Click(object sender, System.EventArgs e) { var purchases = new List <Purchase>(); if (string.IsNullOrEmpty(txtQtd.Text) || Convert.ToDecimal(txtQtd.Text, CultureInfo.InvariantCulture) <= 0) { MessageBox.Show("Informe uma quantidade maior que zero!", "Atenção", MessageBoxButtons.OK); return; } var qtd = string.IsNullOrEmpty(txtQtd.Text) ? 0 : Convert.ToInt32(txtQtd.Text); var totalSucesso = 0; var amount = Convert.ToInt32(Convert.ToDecimal(txtValor.Text, CultureInfo.InvariantCulture) * 100); var batch = Convert.ToInt32(ConfigurationManager.AppSettings["EPayBatchPurchase"]); Parallel.For(0, qtd, new ParallelOptions { MaxDegreeOfParallelism = batch }, (i) => { try { var result = proxy.Sale(amount, txtEAN.Text); Interlocked.Increment(ref totalSucesso); var purchase = new Purchase { Receipt = result.Receipt.ToString(), PartnerId = 3, PurchaseDate = DateTime.Now, TransactionId = result.TXID, Serial = result.PINCredentials.Serial, Token = result.PINCredentials.PIN, PaidPrice = (Convert.ToDecimal(result.Amount) / 100).ToString(CultureInfo.InvariantCulture), SuggestedPrice = (Convert.ToDecimal(result.Amount) / 100).ToString(CultureInfo.InvariantCulture), Sku = txtSku.Text, Cancelled = false, Limit = (Convert.ToDecimal(result.Limit) / 100).ToString(CultureInfo.InvariantCulture) }; repository.Add(purchase); lock (objLock) purchases.Add(purchase); } catch (Exception ex) { var responseLog = $"ERRO: {ex.Message}"; purchases.Add(new Purchase { Token = "", Serial = responseLog, PurchaseDate = DateTime.Now, Sku = "ERRO" }); } }); var sucess = purchases.Where(d => d.Sku != "ERRO"); lblValor.Text = $"{sucess.Sum(d => Convert.ToDecimal(d.PaidPrice, CultureInfo.InvariantCulture)):C}"; lblSucesso.Text = $"{sucess.Count()}/{qtd}"; dgvCompras.DataSource = purchases; }
public void Purchases_Repository_Should_Add_Sucessfully() { //Action var purchase = _repository.Add(_purchase); //Assert purchase.Should().NotBeNull(); purchase.Id.Should().NotBe(0); var expectedPurchase = _context.Purchases.Find(purchase.Id); expectedPurchase.Should().NotBeNull(); }
// GET: Checkout public ActionResult CheckOutCart() { var context = GlobalHost.ConnectionManager.GetHubContext <ProductPageHub>(); CartModel cart = carts.FindByUserId(User.Identity.GetUserId()); // Create Purchase PurchaseModel purchase = new PurchaseModel(); purchase.PurchaseItems = new List <PurchaseItemModel>(); purchase.PriceShipping = 12.99; purchase.PurchaseDate = DateTime.Now; purchase.UserId = User.Identity.GetUserId(); purchase.EMail = User.Identity.GetUserName(); CustomerProfileModel profile = customerProfiles.FindByUserId(purchase.UserId); purchase.FullName = profile.FullName; purchase.PhoneNumber = profile.PhoneNumber; purchase.AdrAtt = profile.AdrAtt; purchase.AdrStreet1 = profile.AdrStreet1; purchase.AdrStreet2 = profile.AdrStreet2; purchase.AdrPostal = profile.AdrPostal; purchase.AdrCity = profile.AdrCity; purchase.AdrState = profile.AdrState; purchase.AdrCountry = profile.AdrCountry; foreach (CartItemModel item in cart.CartItems) { purchase.PurchaseItems.Add(new PurchaseItemModel { ProductId = item.Product.Id, Name = item.Product.Name, ProductNumber = item.Product.ProductNumber, Price = item.Product.Price, Count = item.Count }); // Update InStock and purchases item.Product.InStock = -item.Count; item.Product.TimesPuchased = +item.Count; products.Edit(item.Product); // SignalR context.Clients.All.ReadyToBuy(item.Product.Id, carts.ProductCountInCarts(item.Product)); context.Clients.All.TimesPurchased(item.Product.Id, item.Product.TimesPuchased, item.Product.InStock); context.Clients.All.ReadyToBuy(item.Product.Id, carts.ProductCountInCarts(item.Product)); } purchases.Add(purchase); // Delete cart after successful purchase carts.Remove(cart); return(View("Success")); }
public void AddOrder() { Dictionary <string, OrdersProduct> dict = ReturnOrderedCart(); IPurchaseRepository repository0 = new PurchaseRepository(); IProductRepository repository1 = new ProductRepository(); IOrdersProductRepository repository2 = new OrdersProductRepository(); var order = new Purchase(); repository0.Add(order); foreach (string key in dict.Keys) { var product = repository1.GetByBarcode(key); dict[key].Item_id = product.Id; dict[key].Order_id = order.Id; repository2.Add(dict[key]); } cart.Clear(); }
public void PurchaseMenu(int productId) { Product product = productDb.Read(productId); Purchase purchase = new Purchase { PurchaseGuid = Guid.NewGuid(), PurchaseDate = DateTime.Now, ProductId = product.Id }; purchase.PriceKZT = product.PriceUsd * purchase.ExchangeRate; string purchaseInfoPath = string.Empty; string shippingInfoPath = string.Empty; string message = string.Empty; Console.Clear(); Console.WriteLine("Форма покупки"); Console.WriteLine("================================="); Console.WriteLine($"Вы покупате {product.Name}.\nСумма покупки составляет {purchase.PriceKZT} по текущему курсу"); Console.WriteLine("---------------------------------"); Console.Write("Введите свое имя: "); purchase.CustomerName = Console.ReadLine(); purchase.PurchaseQr = qr.GetQrCodePurchaseInfo(purchase, out purchaseInfoPath); purchase.ShippingQr = qr.GetQrCodeShippingInfo(purchase, out shippingInfoPath); purchaseDb.Add(purchase, out message); //покупка добавлена в базу данных Console.Write("Введите свой e-mail: "); string email = Console.ReadLine(); MailAddress from = new MailAddress("*****@*****.**", "Korean Shop"); MailAddress to = new MailAddress(email); MailMessage mess = new MailMessage(from, to); mess.Subject = message; mess.Attachments.Add(new Attachment(purchaseInfoPath)); mess.Attachments.Add(new Attachment(shippingInfoPath)); SmtpClient smtp = new SmtpClient("smtp.mail.ru", 587); smtp.Credentials = new NetworkCredential("*****@*****.**", "Step123$"); smtp.EnableSsl = true; smtp.Send(mess); Console.WriteLine("Информация о покупке и месте выдачи заказа отправлены Вам на почту"); Thread.Sleep(2000); }
public void AddPurchase() { DateTime startingHour = DateTime.Today; DateTime finishingHour = DateTime.Today; startingHour = startingHour.AddHours(13); finishingHour = finishingHour.AddHours(14); Purchase purchase = new Purchase { LicensePlate = "ABA 1234", StartingHour = startingHour, FinishingHour = finishingHour, AmountOfMinutes = 60, CountryTag = "AR" }; purchaseRepository.Add(purchase); Assert.IsTrue(purchaseRepository.GetAll().Contains(purchase)); Assert.AreEqual(purchaseRepository.Context.Purchases.Count(), 1); }
public async Task <int> Add(AddPurchaseDto addPurchaseDto) { var purchase = new Purchase { Count = addPurchaseDto.Count, InvoiceNumber = addPurchaseDto.InvoiceNumber, PurchaseDate = addPurchaseDto.PurchaseDate, ProductId = addPurchaseDto.ProductId }; var warehouseItem = await _warehouseItemRepository.FindByProductId(addPurchaseDto.ProductId); ThrowExceptionIfWarehouseItemNotExists(addPurchaseDto.ProductId, warehouseItem); await ThrowExceptionIfInvoiceNumberAlreadyExists(addPurchaseDto.InvoiceNumber); warehouseItem.Stock += purchase.Count; _repository.Add(purchase); await _unitOfWork.CompleteAsync(); return(purchase.Id); }
public bool Add(Purchase purchase) { return(_purchaseRepository.Add(purchase)); }
private void btnCompar_Click(object sender, EventArgs e) { var qtd = string.IsNullOrEmpty(txtQtd.Text) ? 0 : Convert.ToInt32(txtQtd.Text); if (qtd == 0) { MessageBox.Show("A quantidade deve ser maior que ZERO", "Atenção"); return; } var resultList = new List <PurchaseDetails>(); var proxy = new AquiPagaProxy(); var totalSucesso = 0; Parallel.For(0, qtd, (x) => { PurchaseDetails data; try { double preco = 0; if (productDetails.Preco.HasValue) { preco = productDetails.Preco.Value; } else if (double.TryParse(txtPreco.Text, out preco)) { preco = Convert.ToDouble(txtPreco.Text, new CultureInfo("pt-BR")); } else { MessageBox.Show("Informe o preço do produto", "Atenção"); return; } var result = proxy.DoTransaction(productDetails.ProductTypeCode, productDetails.ProviderCode, productDetails.ProductCode, productDetails.ProductOptionCode, preco); data = new PurchaseDetails { Date = result.Date.ToString("dd/MM/yyyy hh:mm:ss"), ProviderTransactionId = result.ProviderTransactionId.ToString(), Amount = result.Amount.ToString("C"), Reference = result.Reference.ToString(), SerialNumber = result.SerialNumber.ToString(), Message = string.Join(Environment.NewLine, result.Receipt) }; Interlocked.Increment(ref totalSucesso); repository.Add(new Purchase { PaidPrice = result.Amount.ToString(CultureInfo.InvariantCulture), PartnerId = 2, SuggestedPrice = result.Amount.ToString(CultureInfo.InvariantCulture), Token = result.Reference, Serial = result.SerialNumber, PurchaseDate = DateTime.Now, Sku = productDetails.Descricao, TransactionId = result.ProviderTransactionId.ToString(), Receipt = string.Join(Environment.NewLine, result.Receipt), Cancelled = false }); } catch (Exception ex) { data = new PurchaseDetails { Message = "Error - " + ex.Message }; } lock (objLock) resultList.Add(data); }); dgResult.DataSource = resultList; lblSucesso.Text = $"{totalSucesso}/{qtd}"; lblValor.Text = $"{totalSucesso * (productDetails.Preco ?? 0):C}"; }
public void AddPurchaseTest() { //delete Purchasing.PurchaseOrderDetail from Purchasing.PurchaseOrderDetail a left join Purchasing.PurchaseOrderHeader b on (a.PurchaseOrderID = b.PurchaseOrderID) where b.VendorID=1500 //delete Purchasing.PurchaseOrderheader from Purchasing.PurchaseOrderHeader where VendorID=1500 //delete Purchasing.PurchaseOrderDetail from Purchasing.PurchaseOrderDetail a left join Purchasing.PurchaseOrderHeader b on (a.PurchaseOrderID = b.PurchaseOrderID) where b.VendorID=1502 //delete Purchasing.PurchaseOrderheader from Purchasing.PurchaseOrderHeader where VendorID=1502 //IUnitOfWork unit = new UnitOfWork(); IPurchaseRepository repo = new PurchaseRepository(); var header = new PurchaseOrderHeader(); header.EmployeeID = 1; header.RevisionNumber=10; header.Status=1; header.VendorID=1699; header.ShipMethodID = 1; header.OrderDate=DateTime.Now.Date; header.ShipDate=DateTime.Now.Date; header.SubTotal=555; header.TaxAmt=10; header.Freight=4; header.ModifiedDate = DateTime.Now.Date; header.PurchaseOrderDetails.Add(new PurchaseOrderDetail() { DueDate = DateTime.Now.Date , OrderQty = 15 , ProductID = 998 , UnitPrice = 100 , LineTotal = 100 , ReceivedQty = 15 , RejectedQty = 0 , StockedQty = 0 , ModifiedDate = DateTime.Now.Date }); header.PurchaseOrderDetails.Add(new PurchaseOrderDetail() { DueDate = DateTime.Now.Date , OrderQty = 25 , ProductID = 999 , UnitPrice = 600 , LineTotal = 700 , ReceivedQty = 25 , RejectedQty = 0 , StockedQty = 0 , ModifiedDate = DateTime.Now.Date }); repo.Add(header); header = repo.Single(x => x.ModifiedDate.Day == DateTime.Now.Day && x.ModifiedDate.Month == DateTime.Now.Month && x.ModifiedDate.Year == DateTime.Now.Year && x.VendorID == 1699); Assert.IsNotNull(header); Assert.IsTrue(header.PurchaseOrderDetails.Count() >= 2); }
public int Add(List <PurchaseProduct> purchaseProducts) { return(_purchaseRepository.Add(purchaseProducts)); }
internal bool Add(Purchase purchase) { return(_purchaseRepository.Add(purchase)); }
private void btnComprar_Click(object sender, System.EventArgs e) { if (string.IsNullOrEmpty(txtSku.Text)) { MessageBox.Show("Informe o SKU", "Atenção", MessageBoxButtons.OK); return; } if (string.IsNullOrEmpty(txtQtd.Text)) { MessageBox.Show("Informe a quantidade", "Atenção", MessageBoxButtons.OK); return; } var data = new List <Purchase>(); var qtd = Convert.ToInt32(txtQtd.Text.Trim()); for (int i = 0; i < qtd; i++) { string responseLog; try { using (var client = new WebClient()) { var signature = ConfigurationManager.AppSettings["RixtySignature"]; var sku = txtSku.Text; var url = $"{ConfigurationManager.AppSettings["RixtyApi"]}?METHOD=GetSku&SIGNATURE={signature}&SKU={System.Net.WebUtility.UrlEncode(sku)}"; string reply = client.DownloadString(url); var desc = string.Empty; var precoSugerido = string.Empty; var ack = string.Empty; var seuPreco = string.Empty; var errMsg = string.Empty; var values = reply.Split(new[] { '&' }); var token = string.Empty; var serial = string.Empty; foreach (var v in values) { var vUpper = v.ToUpper().Split(new[] { '=' }); if (vUpper[0] == "DESC") { desc = vUpper[1]; } else if (vUpper[0] == "AMT") { precoSugerido = vUpper[1]; } else if (vUpper[0] == "SETTLEAMT") { seuPreco = vUpper[1]; } else if (vUpper[0] == "ACK") { ack = vUpper[1]; } else if (vUpper[0] == "ERRORMESSAGE") { errMsg = vUpper[1]; } else if (vUpper[0] == "TOKEN") { token = vUpper[1]; } else if (vUpper[0] == "SERIALNUMBER") { serial = vUpper[1]; } } if (ack.Equals("Success", StringComparison.InvariantCultureIgnoreCase)) { responseLog = $"SUCESSO | PREÇO COMPRA: {seuPreco} | TOKEN: {token} | SERIAL: {serial}"; var p = new Purchase { PaidPrice = seuPreco, PartnerId = 1, SuggestedPrice = precoSugerido, Token = token, Serial = serial, PurchaseDate = DateTime.Now, Sku = sku, Cancelled = false }; data.Add(p); repository.Add(p); } else { responseLog = $"ERRO: {System.Net.WebUtility.UrlDecode(errMsg)}"; data.Add(new Purchase { Token = responseLog, Serial = "ERRO", PurchaseDate = DateTime.Now, Sku = "ERRO", PaidPrice = "ERRO", SuggestedPrice = "ERRO", }); } } } catch (Exception exception) { responseLog = $"ERRO: {exception.Message}"; data.Add(new Purchase { Token = responseLog, Serial = "ERRO", PurchaseDate = DateTime.Now, Sku = "ERRO", PaidPrice = "ERRO", SuggestedPrice = "ERRO", }); } } var sucess = data.Where(d => d.Serial != "ERRO"); lblValor.Text = $"{sucess.Sum(d => Convert.ToDecimal(d.PaidPrice, CultureInfo.InvariantCulture)):C}"; lblSucesso.Text = $"{sucess.Count()}/{qtd}"; //BindListItem(data); dgvCompras.DataSource = data; }
public bool Add(List <PurchaseProduct> purchaseProducts) { return(purchaseRepository.Add(purchaseProducts)); }