// GET: Auctions public ActionResult Index() { AuctionContext db = new AuctionContext(); List <Auction> auctions = db.Auctions.ToList(); return(View(auctions)); }
public async Task <IEnumerable <LotModel> > GetLotByNameAndDate(string name, DateTime start, DateTime end) { if (name == null) { throw new ArgumentNullException(nameof(name)); } using (var db = new AuctionContext()) { var lots = db.Lots .Where(L => L.AuctionDate >= start && L.AuctionDate <= end && L.Name == name) .Select(L => new LotModel { Id = L.Id, Name = L.Name, Description = L.Description, Quantity = L.Quantity, Unit = L.Unit, StartingPrice = L.StartingPrice, CurrentPrice = L.CurrentPrice, MinimalBid = L.MinimalBid, BidCount = L.BidCount, AuctionDate = L.AuctionDate }) .ToList(); return(lots); } }
public async Task <IEnumerable <LotModel> > GetLots() { using (var db = new AuctionContext()) { try { var lots = db.Lots.Select(L => new LotModel { Id = L.Id, Name = L.Name, Description = L.Description, Quantity = L.Quantity, Unit = L.Unit, StartingPrice = L.StartingPrice, CurrentPrice = L.CurrentPrice, MinimalBid = L.MinimalBid, BidCount = L.BidCount, AuctionDate = L.AuctionDate }).ToList(); return(lots); } catch (Exception) { return(new List <LotModel>()); } } }
public void UpdateItems() { HtmlWeb web = new HtmlWeb(); List <string> NewItemList = new List <string>(); List <ItemClass> NewItems = new List <ItemClass>(); string[] a = new[] { "head", "body", "weapon", "hands", "feet", "amulet", "consumable" }; HtmlDocument doc; HtmlEntity util; foreach (var i in a) { doc = web.Load($"https://www.roshpit.ca/items?slot={i}"); HtmlNodeCollection items = doc.DocumentNode.SelectNodes($"//div[@id={Strings.Chr(34)}item-table-container{Strings.Chr(34)}]//a"); foreach (var it in items) { NewItemList.Add(it.GetAttributeValue("href", "none")); } } foreach (var it in NewItemList) { NewItems.Add(LoadItem($"https://www.roshpit.ca/{it}")); System.Threading.Thread.Sleep(500); } using (AuctionContext myx = new AuctionContext()) { myx.Items.AddRange(NewItems); myx.SaveChanges(); } }
public ActionResult Auction(long id) { AuctionContext context = new AuctionContext(); var auction = db.Auctions.Find(id); return(View(auction)); }
public async Task <RaffleEntry> AddRaffleEntry(string raffleId, long amount, string description) { var raffle = GetRaffle(raffleId); if (raffle == null) { return(null); } if (raffle.FinishedAt != -1) { return(null); } var raffleEntry = new RaffleEntry { Amount = amount, Memo = description, Raffle = raffle, RaffleId = raffle.Id, }; raffle.RaffleEntries.Add(raffleEntry); using (var context = new AuctionContext()) { context.Raffles.Update(raffle); raffleEntry = context.RaffleEntries.Add(raffleEntry).Entity; await context.SaveChangesAsync(); } return(raffleEntry); }
public bool SetWinnersForProducts() { var expiredProducts = ProductController.Instance().GetExpiredProductsIds(); using (var db = new AuctionContext()) { var bids = db.Bids .Where(b => expiredProducts.Contains(b.ProductId)) .ToList(); if (bids.Count == 0) { return(false); } foreach (var productId in expiredProducts) { var currentBids = bids .Where(b => b.ProductId == productId) .ToList(); // remove this and include the where in first or default below var lastBidder = currentBids .OrderByDescending(r => r.DateOfCreated) // or coins doesn't matter .Take(1) .FirstOrDefault(); lastBidder.IsWon = true; } db.SaveChanges(); } return(true); }
public async Task <IEnumerable <TraderModel> > GetTradersByNameAndDate(string name, DateTime start, DateTime end) { if (name == null) { throw new ArgumentNullException(nameof(name)); } using (var db = new AuctionContext()) { var traders = db.Traders .Where(t => t.AuctionDate >= start && t.AuctionDate <= end && t.Name == name) .Select(t => new TraderModel { Id = t.Id, Name = t.Name, LegacyForm = t.LegacyForm, IdentityNumber = t.IdentityNumber, ApplicantName = t.ApplicantName, ParticipantName = t.ParticipantName, ParticipantStatus = t.ParticipantStatus, PhoneNumber = t.PhoneNumber, Email = t.Email, BankName = t.BankName, BankAccountNumber = t.BankAccountNumber, Swift = t.Swift, AuctionDate = t.AuctionDate }).ToList(); return(traders); } }
public async Task <TraderModel> EditTrader(TraderModel trader) { if (trader == null) { throw new ArgumentNullException(nameof(trader)); } using (var db = new AuctionContext()) { var traderEntity = db.Traders.FirstOrDefault(t => t.Id == trader.Id); if (traderEntity == null) { return(null); } traderEntity.LegacyForm = trader.LegacyForm; traderEntity.IdentityNumber = trader.IdentityNumber; traderEntity.ApplicantName = trader.ApplicantName; traderEntity.ParticipantName = trader.ParticipantName; traderEntity.ParticipantStatus = trader.ParticipantStatus; traderEntity.PhoneNumber = trader.PhoneNumber; traderEntity.Email = trader.Email; traderEntity.BankName = trader.BankName; traderEntity.BankAccountNumber = trader.BankAccountNumber; traderEntity.Swift = trader.Swift; traderEntity.AuctionDate = trader.AuctionDate; await db.SaveChangesAsync(); return(trader); } }
public List <Bid> GetAllBids(short lotId, string order, string filterPrice, string filterDate, int pageSize = 5, int pageNumber = 1) { // Filtering // Price formating List <int> filterPriceRange = new List <int>(); int minPrice = 0, maxPrice = int.MaxValue; if (string.IsNullOrEmpty(filterPrice)) { filterPrice = ""; } else if (!filterPrice.Contains(",")) { filterPrice = "0," + filterPrice; filterPriceRange = filterPrice.Split(',').Select(item => int.Parse(item)).ToList(); minPrice = filterPriceRange[0]; maxPrice = filterPriceRange[1]; } else { filterPriceRange = filterPrice.Split(',').Select(item => int.Parse(item)).ToList(); minPrice = filterPriceRange[0]; maxPrice = filterPriceRange[1]; } // Date formating List <DateTime> filterDateRange = new List <DateTime>(); DateTime minDate = new DateTime(2000, 1, 1); DateTime maxDate = new DateTime(2100, 1, 1); if (string.IsNullOrEmpty(filterDate)) { filterDate = ""; } else if (!filterDate.Contains(",")) { filterDate = DateTime.MinValue.ToString() + "," + filterDate; filterDateRange = filterDate.Split(',').Select(item => DateTime.Parse(item)).ToList(); minDate = new DateTime(2000, 1, 1); maxDate = filterDateRange[1]; } else { filterDateRange = filterDate.Split(',').Select(item => DateTime.Parse(item)).ToList(); minDate = filterDateRange[0]; maxDate = filterDateRange[1]; } AuctionContext db = new AuctionContext(); List <SqlParameter> parameters = new List <SqlParameter>() { new SqlParameter("@LotId", lotId), new SqlParameter("@PriceMin", minPrice), new SqlParameter("@PriceMax", maxPrice), new SqlParameter("@DateMin", minDate), new SqlParameter("@DateMax", maxDate), new SqlParameter("@StartRowIndex", pageSize * (pageNumber - 1)), new SqlParameter("@PageSize", pageSize) }; var result = db.Database.SqlQuery <Bid>("dbo.GetBids @LotId , @PriceMin , @PriceMax ,@DateMin , @DateMax , @StartRowIndex , @PageSize ", parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6]).ToList(); result = string.IsNullOrEmpty(order) ? result : result.AsQueryable().ApplySort(order).ToList(); return(result); }
public async Task <TraderModel> AddTrader(TraderModel trader) { if (trader == null) { throw new ArgumentNullException(nameof(trader)); } using (var db = new AuctionContext()) { var traderEntity = new Trader() { Name = trader.Name, LegacyForm = trader.LegacyForm, IdentityNumber = trader.IdentityNumber, ApplicantName = trader.ApplicantName, ParticipantName = trader.ParticipantName, ParticipantStatus = trader.ParticipantStatus, PhoneNumber = trader.PhoneNumber, Email = trader.Email, BankName = trader.BankName, BankAccountNumber = trader.BankAccountNumber, Swift = trader.Swift, AuctionDate = trader.AuctionDate }; db.Traders.Add(traderEntity); await db.SaveChangesAsync(); trader.Id = traderEntity.Id; return(trader); } }
public ActionResult Bid(Bid bid) { AuctionContext db = new AuctionContext(); var auction = db.Auctions.Find(bid.AuctionId); if (auction == null) { ModelState.AddModelError("AuctionId", "Auction Not Found"); } else if (auction.CurrentPrice >= bid.Amount) { ModelState.AddModelError("Amount", "Bid Amount Less then the current Amount"); } else { bid.UserName = User.Identity.Name; db.Bids.Add(bid); auction.CurrentPrice = bid.Amount; db.SaveChanges(); } if (!Request.IsAjaxRequest()) { return(RedirectToAction("FindingBy", new { id = bid.AuctionId })); } return(Json(new { CurrentPrice = bid.Amount.ToString("C"), BidCount = auction.Bidcount })); }
public ActionResult Auction([Bind(Exclude = "CurrentPrice")] Auction auction) { //if (string.IsNullOrWhiteSpace(auction.Title)) //{ // ModelState.AddModelError("Title", "Title Must be Required"); //} //else if (auction.Title.Length < 5 || auction.Title.Length > 200) //{ // ModelState.AddModelError("Title", "Your Title Must be Greater Then 5 and Less then 200 char"); //} if (ModelState.IsValid) { AuctionContext db = new AuctionContext(); using (db) { db.Auctions.Add(auction); db.SaveChanges(); } return(RedirectToAction("Index")); } return(View()); }
public ActionResult FindingBy(long id) { AuctionContext db = new AuctionContext(); var auction = db.Auctions.Find(id); return(View(auction)); }
static void Main(string[] args) { AuctionContext context = new AuctionContext(); UnitOfWork uow = new UnitOfWork(context, new ContextRepository <Lot>(context), new ContextRepository <Role>(context), new ContextRepository <User>(context)); uow.Roles.Create(new Role() { Role_name = "Admin" }); uow.Roles.Create(new Role() { Role_name = "Manager" }); uow.Roles.Create(new Role() { Role_name = "User" }); uow.Roles.Create(new Role() { Role_name = "Guest" }); uow.Save(); uow.Users.Create(new User() { Login = "******", Pass = "******", Name = "Admin1", Role_FK = 1 }); uow.Save(); Console.WriteLine("Done"); Console.ReadLine(); }
public Task Handle(ProductSelectionChanged message) { _bidItemsViewModels.Clear(); return(Task.Run(() => { if (message.Product == null) { return; } using (var db = new AuctionContext()) { var bids = db.Bids.Where(bid => bid.ProductId == message.Product.Id).OrderByDescending(bid => bid.BidDate).ToList(); foreach (var bid in bids) { _bidItemsViewModels.Add(new BidItemViewModel { BidAmount = bid.BidAmount, BidDate = bid.BidDate, BidderName = db.Accounts.First(account => account.Id == bid.AccountId).UserName, }); } } })); }
public void SubmitBid(Product product) { var vm = new PlaceBidViewModel { BidAmount = product.LastBidAmount, Title = product.Title }; _windowManager.ShowDialog(vm); if (vm.IsCancelled) { return; } using (var db = new AuctionContext()) { product.LastBidAmount = vm.BidAmount; db.Entry(product).State = EntityState.Modified; db.Bids.Add(new Bid { AccountId = _loginViewModel.Account.Id, BidAmount = vm.BidAmount, ProductId = product.Id }); db.SaveChanges(); } }
public async Task <AuctioneerModel> RegisterAuctioneer(AuctioneerModel auctioneerModel) { if (auctioneerModel == null) { throw new ArgumentNullException(nameof(auctioneerModel)); } using (var db = new AuctionContext()) { var found = db.Auctioneers.Any(a => a.UserName.Equals(auctioneerModel.UserName, StringComparison.CurrentCultureIgnoreCase)); if (found) { return(null); } Auctioneer auctioneer = new Auctioneer { FirstName = auctioneerModel.FirstName, LastName = auctioneerModel.LastName, UserName = auctioneerModel.UserName, Password = auctioneerModel.Password, IsAdmin = auctioneerModel.IsAdmin, }; db.Auctioneers.Add(auctioneer); await db.SaveChangesAsync(); auctioneerModel.Id = auctioneer.Id; return(auctioneerModel); } }
public IList <Bid> GetAllBidsByProductName(string productName) { CoreValidator.ThrowIfNullOrEmpty(productName, nameof(productName)); using (var db = new AuctionContext()) { var isExisting = ProductController.Instance().IsProductExisting(productName); if (!isExisting) { throw new ArgumentException("The product doesn't exist in the system."); } var resultBids = db.Bids .Include("Product") .Include("User") .Where(b => b.Product.Name == productName) .OrderByDescending(b => b.DateOfCreated) .ThenByDescending(b => b.Coins) .ToList(); CoreValidator.ThrowIfNull(resultBids, nameof(resultBids)); return(resultBids); } }
private async void LndService_OnHoldInvoiceActivated(object sender, Invoice invoice, byte[] preImage) { Console.WriteLine("In Hodle Activated {0}", invoice); try { var auctionInvoice = JsonSerializer.Deserialize <AuctionInvoice>(invoice.Memo); using (var context = new AuctionContext()) { var auctionEntry = context.AuctionEntries.FirstOrDefault(e => e.PaymentRequest == invoice.PaymentRequest); var auction = GetAuction(Guid.Parse(auctionInvoice.AuctionId)); if (auction.FinishedAt != 0) { await _lndService.CancelHodlInvoice(invoice.RHash.ToByteArray()); return; } auctionEntry.ActivatedAt = Utility.Utility.DateTimeToUnix(DateTime.UtcNow); auctionEntry.State = AuctionEntryState.ACTIVATED; context.AuctionEntries.Update(auctionEntry); Console.WriteLine("activated auction entry {0}", auctionEntry); await context.SaveChangesAsync(); } }catch (Exception e) { Console.WriteLine("ERROR AT HOLD INVOICE ACTIVATED {0}", invoice); await _lndService.CancelHodlInvoice(invoice.RHash.ToByteArray()); } }
public void LoadGlyphsData(string link, string hero) { HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load(link); HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes($"//div[@class={Strings.Chr(34)}glyph_container{Strings.Chr(34)}]"); List <ItemClass> Itemlist = new List <ItemClass>(); foreach (HtmlNode img in imgs) { Itemlist.Add(new ItemClass() { Name = System.Net.WebUtility.HtmlDecode(img.ChildNodes[1].GetAttributeValue("data-glyph-name", "Unknown")), Rarity = System.Net.WebUtility.HtmlDecode(img.ChildNodes[1].GetAttributeValue("data-rarity-color", "Unknown")), Slot = "Glyph", Image = img.ChildNodes[3].GetAttributeValue("src", "Unknown"), Special_Ability_Description = System.Net.WebUtility.HtmlDecode(img.ChildNodes[1].GetAttributeValue("data-glyph-description", "Unknown").Replace("<font color='#CCFF66'>", "**").Replace("</font>", "**").Replace("'", "'").Replace("<font color="#EF4126">", "**").Replace("<font color="#87D9FF">", "**").Replace("<font color="#C25DFC">", "**").Replace("<font color="#5CCDF9">", "**").Replace("<font color="#69BC71">", "**").Replace("color="#DDDDDD">", "**").Replace("<font color="#B5FFB7">", "**")), AlternativeName = img.ChildNodes[3].GetAttributeValue("src", "Unknown").Replace("https://s3-us-west-2.amazonaws.com/roshpit-assets/glyphs/", "").Replace(".png", ""), Required_level = img.ChildNodes[1].GetAttributeValue("data-required-level", "Unknown"), Special_Ability = hero }); } using (AuctionContext a = new AuctionContext()) { a.Items.AddRange(Itemlist); a.SaveChanges(); } }
public ActionResult SendRegistrationMessage(string a) { if (User.Identity.Name != AppSettings.AdminName) { //Если текущий пользователь не является администратором аукциона, отпрвляем его на главную страницу return(RedirectToAction("Index", "Home")); } else { lock (_padLock) using (AuctionContext db = new AuctionContext()) { //Получаем список пользователей List <User> users = db.Users.ToList(); if (users.Count != 0) { //Если список не пустой, начинаем отправлять сообщения foreach (var user in users) { //Текст сообщения string mailBody = "Для входа на аукцион #PROКАЧКА используйте Вашу учетную запись DeltaCredit."; //Отпрака сообщения SendEmail(user.Email, "Аукцион ДельтаКредит", mailBody); } } //Все письма отправлены ViewBag.SendSuccess = true; return(View()); } } }
public ActionResult Index(string auctionCategory, string searchString) { AuctionContext context = new AuctionContext(); //var auctions = context.Auctions.ToList(); var CategoryLst = new List <string>(); var CategoryQry = from d in db.Auctions select d.Category; CategoryLst.AddRange(CategoryQry.Distinct()); ViewBag.auctionCategory = new SelectList(CategoryLst); var auctions = from m in db.Auctions select m; if (!String.IsNullOrEmpty(searchString)) { auctions = auctions.Where(s => s.Title.Contains(searchString)); } if (!String.IsNullOrEmpty(auctionCategory)) { auctions = auctions.Where(x => x.Category == auctionCategory); } return(View(auctions)); }
//Функция для регистрации пользователей public Task RegisterAll(string Path, string GroupName) { return(Task.Run(() => { //Получем массив пользователей группы с их монетами string[] Group = System.IO.File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory.ToString() + Path); if (Group.Length != 0) { //Если массив не пустой, начинаем регистрировать каждого пользователя foreach (string str in Group) { //Разбиваем строку на логин пользователя и количество монет string[] text = str.Split(':'); //Разбиваем логин пользователя на имя компьютера и имя самого пользователя, чтобы потом сделать из него Email string[] email = text[0].Split('\\'); lock (_padLock) using (AuctionContext db = new AuctionContext()) { //Добавляем нового пользователя в БД db.Users.Add(new User { Login = text[0], Email = email[1] + "@deltacredit.ru", Group = GroupName, Coints = Convert.ToInt32(text[1]) }); //Сохраняем изменения db.SaveChanges(); } } } })); }
public ActionResult Bid(Bid bid) { AuctionContext context = new AuctionContext(); var auction = db.Auctions.Find(bid.AuctionId); if (auction == null) { ModelState.AddModelError("AuctionId", "Auction not found!"); } else if (auction.CurrentPrice >= bid.Amount) { ModelState.AddModelError("Amount", "Bid amount must exceed current bid"); } else { bid.Username = User.Identity.Name; auction.Bids.Add(bid); auction.CurrentPrice = bid.Amount; db.SaveChanges(); } if (!Request.IsAjaxRequest()) { return(RedirectToAction("Auction", new { id = bid.AuctionId })); } return(Json(new { CurrentPrice = bid.Amount.ToString("C"), BidCount = auction.BidCount })); }
public UnitOfWork() { _context = new AuctionContext(); //use this line for debug propose and check in console SQL requests //_context.Database.Log = Console.WriteLine; }
public async Task <LotModel> AddLot(LotModel lot) { if (lot == null) { throw new ArgumentNullException(nameof(lot)); } using (var db = new AuctionContext()) { var lotEntity = new Lot { Id = lot.Id, Name = lot.Name, Description = lot.Description, Quantity = lot.Quantity, Unit = lot.Unit, StartingPrice = lot.StartingPrice, CurrentPrice = lot.CurrentPrice, MinimalBid = lot.MinimalBid, BidCount = lot.BidCount, AuctionDate = lot.AuctionDate }; db.Lots.Add(lotEntity); await db.SaveChangesAsync(); lot.Id = lotEntity.Id; return(lot); } }
public async Task <TradingHistoryModel> EditTradingHistory(TradingHistoryModel history) { if (history == null) { throw new ArgumentNullException(nameof(history)); } using (var db = new AuctionContext()) { var modifiedRecord = db.TradingHistories.FirstOrDefault(h => h.Id == history.Id); if (modifiedRecord == null) { return(null); } var trader = db.Traders.FirstOrDefault(t => t.Id == (history.Trader == null ? 0 : history.Trader.Id)) ?? modifiedRecord.Trader; var lot = db.Lots.FirstOrDefault(L => L.Id == (history.Lot == null ? 0 : history.Lot.Id)) ?? modifiedRecord.Lot; var auctioneer = db.Auctioneers.FirstOrDefault(a => a.Id == (history.Auctioneer == null ? 0 : history.Auctioneer.Id)) ?? modifiedRecord.Auctioneer; modifiedRecord.Lot = lot; modifiedRecord.Trader = trader; modifiedRecord.Auctioneer = auctioneer; modifiedRecord.LotId = lot.Id; modifiedRecord.TraderId = trader.Id; modifiedRecord.AuctioneerId = auctioneer.Id; modifiedRecord.BidTime = history.BidTime; modifiedRecord.BidOrder = history.BidOrder; modifiedRecord.RecordedPrice = history.RecordedPrice; await db.SaveChangesAsync(); return(history); } }
public async Task <LotModel> EditLot(LotModel lot) { if (lot == null) { throw new ArgumentNullException(nameof(lot)); } using (var db = new AuctionContext()) { var lotEntity = db.Lots.FirstOrDefault(L => L.Id == lot.Id); if (lotEntity == null) { return(null); } lotEntity.Name = lot.Name; lotEntity.Description = lot.Description; lotEntity.Quantity = lot.Quantity; lotEntity.Unit = lot.Unit; lotEntity.StartingPrice = lot.StartingPrice; lotEntity.CurrentPrice = lot.CurrentPrice; lotEntity.MinimalBid = lot.MinimalBid; lotEntity.BidCount = lot.BidCount; lotEntity.AuctionDate = lot.AuctionDate; await db.SaveChangesAsync(); return(lot); } }
public bool UpdatePayment(Payment newPayment) { CoreValidator.ThrowIfNull(newPayment, nameof(newPayment)); CoreValidator.ThrowIfNegativeOrZero(newPayment.Id, nameof(newPayment.Id)); CoreValidator.ThrowIfNullOrEmpty(newPayment.PaymentTypeCode, nameof(newPayment.PaymentTypeCode)); CoreValidator.ThrowIfNegativeOrZero(newPayment.UserId, nameof(newPayment.UserId)); using (var db = new AuctionContext()) { var dbPayment = GetPayment(newPayment.Id); CoreValidator.ThrowIfNull(dbPayment, nameof(dbPayment)); db.Payments.Attach(dbPayment); dbPayment.PaymentTypeCode = newPayment.PaymentTypeCode; dbPayment.Type = newPayment.Type; dbPayment.UserId = newPayment.UserId; db.Entry(dbPayment).State = EntityState.Modified; db.SaveChanges(); return(true); } }