public void RemoveAuction(Auction auction) { if (auction == null) return; if (!auctions.ContainsKey(auction.AuctionId)) return; auctions.Remove(auction.ItemLowId); items.Remove(auction.ItemLowId); AuctionMgr mgr = AuctionMgr.Instance; ItemRecord record = null; if (mgr.AuctionItems.ContainsKey(auction.ItemLowId)) { record = mgr.AuctionItems[auction.ItemLowId]; mgr.AuctionItems.Remove(auction.ItemLowId); } //remove from database RealmServer.IOQueue.AddMessage(() => { if (record != null) { record.IsAuctioned = false; record.Save(); } auction.Delete(); }); }
private PrivateAuctionRound(ImmutableList<Player> players, ImmutableList<PrivateCompany> privates, Auction<PrivateCompany> auction, Player activePlayer, Player lastToAct, int seedMoney) : base(players, activePlayer, lastToAct) { Privates = privates; CurrentAuction = auction; SeedMoney = seedMoney; }
public void Add(Auction auction) { var auctionDTO = new AuctionDTO(); Map(auctionDTO, auction.GetSnapshot()); _auctionExampleContext.Auctions.Add(auctionDTO); }
public void Put(string id, Auction auction) { var currentAuction = _repository.Single<Auction>(id); if (currentAuction != null) { Mapper.DynamicMap(auction, currentAuction); } }
public void Ctor_WhenInvokedWithCorrectValues_PropertiesAreSet() { var auction = new Auction(_dummyItem, _dummyGuid, 1); Assert.AreEqual(_dummyItem, auction.Item); Assert.AreEqual(_dummyGuid, auction.Seller); Assert.AreNotEqual(Guid.Empty, auction.Id); }
public void PlaceBid_WhenInvokedAmountLowerThanMinimum_ArgumentExceptionIsThrown() { var auction = new Auction(_dummyItem, _dummyGuid, 20); var bid = new Bid(Guid.NewGuid(), 10); Assert.Throws<ArgumentException>(() => { auction.PlaceBid(bid); }); }
public RunActionForm(Auction auction) { InitializeComponent(); this._auction = auction; _auctionClient = new AuctionServiceClient(); dataGridView1.DataSource = auction.Lots; _lotCount = 0; NextLot(); }
public void GetCurrentPrice_WhenNoBidsExist_MinimumPriceIsReturned() { uint minimumPrice = 1; var auction = new Auction(_dummyItem, _dummyGuid, minimumPrice); uint currentPrice = auction.GetCurrentPrice(); Assert.AreEqual(minimumPrice, currentPrice); }
public void Add(Auction auction) { var snapshot = auction.GetSnapshot(); var auctionDTO = new AuctionDTO(); Map(auctionDTO, snapshot); _unitOfWork.RegisterNew(auctionDTO, this); }
public void Save(Auction auction) { var snapshot = auction.GetSnapshot(); var auctionDTO = new AuctionDTO(); Map(auctionDTO, snapshot); _unitOfWork.RegisterAmended(auctionDTO, this); }
private void WriteItem(Auction item, Stream stream) { var writer = new StreamWriter(stream); writer.WriteLine("{0},{1},{2}", Encode(item.Title), Encode(item.Description), Encode(item.CurrentPrice)); writer.Flush(); }
public AuctionSniperService(string itemId, Auction auction, ISniperListener listener) { _itemId = itemId; _auction = auction; _listener = listener; _snapshot = SniperSnapshot.Joining(itemId); _listener.AddSniper(_snapshot); }
public void PlaceBid_WhenInvokedAmountLowerThanMinimum_ArgumentExceptionIsThrown() { var auction = new Auction(_dummyItem, _dummyGuid, 20); var expectedTime = DateTime.Now; var userId = Guid.NewGuid(); uint amount = 10; Assert.Throws<ArgumentException>(() => { auction.PlaceBid(userId, amount); }); }
public void AddAuction(Auction newAuction) { if (newAuction == null) return; auctions.Add(newAuction.ItemLowId, newAuction); items.Add(newAuction.ItemLowId); //if this is a new one created by player, it should be save in database if (newAuction.IsNew) { newAuction.Create(); } }
public void FromDomainObject(Auction auction) { AccountID = auction.AccountId; AuctionID = auction.AuctionId; AuctionRef = auction.AuctionRef; DomainName = auction.DomainName; EndDate = auction.EndDate; MinBid = auction.MinBid; MyBid = auction.MyBid; Processed = auction.Processed; BidCount = auction.Bids; }
public void CreateAuction_Is_Idempotent() { // arrange var auction = new Auction("a1", new AuctionState()); // act auction.Create("s1", new Item(), 10, Samples.YesterdayAndTomorrowWindow); auction.Create("s1", new Item(), 10, Samples.YesterdayAndTomorrowWindow); // assert Assert.That(auction.Changes.Count(), Is.EqualTo(1)); Assert.That(auction.Changes.First().Payload, Is.InstanceOf<AuctionCreated>()); }
public ActionResult Create(Auction auction) { if (ModelState.IsValid) { var db = new EbuyDataContext(); db.Auctions.Add(auction); db.SaveChanges(); return RedirectToAction("Details", new { id = auction.Id }); } return View(auction); }
public List<Auction> All() { var auctions = db.Auctions.Where(x => x.IsDeleted == null || x.IsDeleted == false); List<Auction> lstAuctions = new List<Auction>(); foreach (DAL.Auction pt in auctions) { Auction pd = new Auction(); pd.Id = pt.Id; pd.Expired = pt.Expired.HasValue ? pt.Expired.Value : DateTime.Now; pd.Product = new Product(); pd.Product.Id = pt.Id; pd.Product.BuyoutPrice = pt.Product.BuyoutPrice.HasValue ? pt.Product.BuyoutPrice.Value : 0; pd.Product.ProductDesigner = pt.Product.ProductDesigner; pd.Product.Provision = pt.Product.Provision.HasValue ? pt.Product.Provision.Value : 0; pd.Product.StartPrice = pt.Product.StartPrice.HasValue ? pt.Product.StartPrice.Value : 0; pd.Product.SupplierId = pt.Product.SupplierId.HasValue ? pt.Product.SupplierId.Value : 0; pd.Product.Type = UtilityHelper.HelperClass.GetProductType(pt.Product.TypeId.HasValue ? pt.Product.TypeId.Value : 0); if (pt.BidWinnerId.HasValue) { DAL.User user = db.Users.Where(x => x.Id == pt.BidWinnerId).FirstOrDefault(); if (user != null) { pd.BidWinner = new User(); pd.BidWinner.Email = user.Email; pd.BidWinner.Password = user.Password; pd.BidWinner.Address = user.Address; DAL.Bank b = db.Banks.Where(x => x.Id == user.BankDetailId).FirstOrDefault(); if (b != null) { pd.BidWinner.BankDetails = new Bank(); pd.BidWinner.BankDetails.Id = b.Id; pd.BidWinner.BankDetails.AccountNumber = b.AccountNbr; pd.BidWinner.BankDetails.Balance = b.Balance.HasValue ? b.Balance.Value : 0; } } } pd.Start = pt.Start.HasValue ? pt.Start.Value : DateTime.MinValue; lstAuctions.Add(pd); } return lstAuctions; }
public void GetCurrentPrice_WhenTwoBidsExist_HighestAmountIsReturned() { var auction = new Auction(_dummyItem, _dummyGuid, 1); var bid1 = new Bid(Guid.NewGuid(), 2); auction.PlaceBid(bid1); var bid2 = new Bid(Guid.NewGuid(), 3); auction.PlaceBid(bid2); uint currentPrice = auction.GetCurrentPrice(); Assert.AreEqual(bid2.Amount, currentPrice); }
public ActionResult Details(int id = 0) { var auction = new Auction { Id = id, Title = "Brand new Widget 2.0", Description = "This is a brand new version 2.0 Widget!", StartPrice = 1.00m, CurrentPrice = 13.40m, StartTime = DateTime.Parse("6-15-2012 12:34 PM"), EndTime = DateTime.Parse("6-23-2012 12:34 PM"), }; return View(auction); }
public void PlaceBid_WhenInvokedWithCorrectBid_BidIsSaved() { var auction = new Auction(_dummyItem, _dummyGuid, 1); var expectedTime = DateTime.Now; var userId = Guid.NewGuid(); uint amount = 2; auction.PlaceBid(userId, amount); // Assert var storedBid = auction.Bids.First(); Assert.AreEqual(userId, storedBid.UserId); Assert.AreEqual(amount, storedBid.Amount); Assert.IsTrue(storedBid.Time >= expectedTime); }
/// <summary>General factory entrance method which will return an EntityFields object with the format generated by the factory specified</summary> /// <param name="relatedEntityType">The type of entity the fields are for</param> /// <returns>The IEntityFields instance requested</returns> public static IEntityFields CreateEntityFieldsObject(Auction.Entities.EntityType relatedEntityType) { IEntityFields fieldsToReturn=null; IInheritanceInfoProvider inheritanceProvider = InheritanceInfoProviderSingleton.GetInstance(); IFieldInfoProvider fieldProvider = FieldInfoProviderSingleton.GetInstance(); IPersistenceInfoProvider persistenceProvider = PersistenceInfoProviderSingleton.GetInstance(); switch(relatedEntityType) { case Auction.Entities.EntityType.AccountEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "AccountEntity"); break; case Auction.Entities.EntityType.AuctionEventEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "AuctionEventEntity"); break; case Auction.Entities.EntityType.AuctionEventDonorEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "AuctionEventDonorEntity"); break; case Auction.Entities.EntityType.BidderEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "BidderEntity"); break; case Auction.Entities.EntityType.CategoryEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "CategoryEntity"); break; case Auction.Entities.EntityType.DonationEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "DonationEntity"); break; case Auction.Entities.EntityType.DonorEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "DonorEntity"); break; case Auction.Entities.EntityType.ExpenseEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "ExpenseEntity"); break; case Auction.Entities.EntityType.PackageEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "PackageEntity"); break; case Auction.Entities.EntityType.RaffleEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "RaffleEntity"); break; case Auction.Entities.EntityType.RoleEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "RoleEntity"); break; case Auction.Entities.EntityType.UserEntity: fieldsToReturn = fieldProvider.GetEntityFields(inheritanceProvider, persistenceProvider, "UserEntity"); break; } return fieldsToReturn; }
public static Auction CreateTestAuction(decimal? minPrice = null, Window window = null) { var auction = new Auction("test-auction-id", new AuctionState()); var price = minPrice ?? 10; window = window ?? new Window { Start = DateTime.UtcNow.AddDays(-1), End = DateTime.UtcNow.AddDays(1) }; auction.Create( "test-seller-id", new Item { Id = "test-item-id", Name = "item name" }, price, window); // create a new aggregate from the state, to ensure the aggregate doesn't come with changes return AggregateFactory.For<Auction>().CreateFromState(auction.Id, auction.State); }
public Response<Auction> CreateAuction(string auctionName,Product product, DateTime start, DateTime expired) { var response = new Response<Auction>(); if (response.Success) { var auction = new Auction(); auction.Product = product; auction.Start = start; auction.Expired = expired; auction.Name = auctionName; //auction.AskingPrice = askingPrice; _repository.Save(auction); response.Entity = auction; } return response; }
public static List<Auction> Convert(List<Auction> auctionsToConvert) { List<Auction> auctions = new List<Auction>(); foreach (var auc in auctionsToConvert) { var auction = new Auction(); auction.AuctionRef = auc.AuctionRef; auction.MinBid = auc.MinBid; auction.DomainName = auc.DomainName; auction.EndDate = auc.EndDate; auction.EndDate = (DateTime)auc.EndDate; auction.MinBid = auc.MinBid; auction.MyBid = (int)auc.MyBid; auctions.Add(auction); } return auctions; }
public void SaveAuction(Auction auction) { var existingRecord = Context.Auctions.FirstOrDefault(x => x.AuctionRef == auction.AuctionRef); if (existingRecord != null) { existingRecord.EndDate = auction.EndDate; existingRecord.MinBid = auction.MinBid; Context.Auctions.AddOrUpdate(existingRecord); } else { var auc = new Auctions(); auc.FromDomainObject(auction); Context.Auctions.AddOrUpdate(auc); } Context.Save(); }
private void parseAuctionData(Object auctionDataObj) { gBattleAPI.BattleNET.AuctionData auctionData = (gBattleAPI.BattleNET.AuctionData)auctionDataObj; logger.Debug("Parsing auctions for realm '" + auctionData.realm.name + "'"); Stopwatch watch = new Stopwatch(); watch.Start(); foreach (gBattleAPI.BattleNET.AuctionItemInfo _auction in auctionData.alliance.auctions) { Auction auction = new Auction(); auction.id = _auction.auc; auction.bid = _auction.bid; auction.buyout = _auction.buyout; auction.item = ItemManager.INSTANCE.getItem(_auction.item); auction.player = RealmManager.INSTANCE.getPlayerOnRealm(_auction.ownerRealm, _auction.owner, true); auctions.Add(auction); } watch.Stop(); logger.Debug("Parsing for realm '" + auctionData.realm.slug + "' finished in " + watch.ElapsedMilliseconds + "ms"); }
public Response<Auction> UpdateAuctionDetail(int id,string auctionName, Product product, DateTime start, DateTime expired, User winner) { var response = new Response<Auction>(); if (_repository.Get(auctionName) != null) response.Error = ErrorCode.DuplicateEntity; if (response.Success) { var auction = new Auction(); auction.Id = id; auction.Name = auctionName; auction.Product = product; //auction.AskingPrice = askingPrice; auction.Start = start; auction.Expired = expired; auction.BidWinner = winner; _repository.UpdateAuctionDetail(auction); } return response; }
public IActionResult CreateAuction(Auction auctions) { if (ModelState.IsValid) { TempData["Error"] = ""; int?ID = HttpContext.Session.GetInt32("UserId"); auctions.UserId = (int)ID; if (auctions.EndDate < DateTime.Now) { TempData["Error"] = "End Date Must be in the Future"; return(RedirectToAction("Success")); } _context.Add(auctions); _context.SaveChanges(); } else { TempData["Error"] = "All the Fields are Required(Starting Bid Must be >0)"; return(RedirectToAction("Success")); } return(RedirectToAction("Dashboard")); }
private void HandleStartAuction() { Auction currentAuction = auctionCtr.GetCurrentAuction(); if (currentAuction != null && currentAuction.Items.Count > 0) { auctionCtr.MaxIndex = currentAuction.Items.Count - 1; foreach (Item artPiece in currentAuction.Items) { ListViewItem lvItem = new ListViewItem(); lvItem.Text = artPiece.Author + ": " + artPiece.Title; lvItem.Tag = artPiece; listItem.Items.Add(lvItem); } } MarkItem(); ShowItem(GetNextItem()); btnStart.Enabled = true; }
private static Bid SetNewBidForAuction(User user, float amount, Auction auctionDb) { var newBid = new Bid { Bidder = user, Amount = amount }; if (auctionDb.Bids == null) { auctionDb.Bids = new List <Bid> { newBid }; } else { auctionDb.Bids.Add(newBid); } auctionDb.CurrentBid = auctionDb.Bids.OrderByDescending(b => b.Amount).FirstOrDefault(); return(newBid); }
public IActionResult CreateAuction(CreaAuction na) { int?LogId = HttpContext.Session.GetInt32("UserId"); if (LogId == null) { return(Redirect("/")); } ViewBag.LoggedUserId = LogId; if (ModelState.IsValid) { Auction cna = new Auction { SellerId = (int)LogId, StartingBid = na.CreStartingBid, EndDate = na.CreEndDate, Product = na.CreProduct, Description = na.CreDescription }; _context.auctions.Add(cna); _context.SaveChanges(); return(Redirect("/dashboard")); } return(View("NewAuction")); }
public ActionResult Create(AuctionFormViewModel viewModel) { if (!ModelState.IsValid) { return(View("Create", viewModel)); } var auction = new Auction() { UserId = User.Identity.GetUserId(), StartDate = DateTime.Now, StartingPrice = Convert.ToInt32(viewModel.StartingPrice), ItemName = viewModel.ItemName, Details = viewModel.Details, EndTime = DateTime.Now.AddDays(viewModel.Days), Image = ProcessImage(viewModel.Image) }; _context.Auctions.Add(auction); _context.SaveChanges(); return(RedirectToAction("Index", "Home")); }
public IActionResult Bid(int itemID, double amount) { Product currentItem = _context.Products.Where(e => e.ProductID == itemID).SingleOrDefault(); User currentUser = _context.Users.Where(e => e.UserID == (int)HttpContext.Session.GetInt32("CurrentUserID")).SingleOrDefault(); User seller = _context.Users.Where(e => e.UserID == currentItem.SellerID).SingleOrDefault(); Auction auction = _context.Auctions.Where(e => e.ItemID == itemID).SingleOrDefault(); if (auction == null) { Auction newAuction = new Auction { ItemID = itemID, TopbidderID = (int)HttpContext.Session.GetInt32("CurrentUserID") }; currentItem = _context.Products.Where(e => e.ProductID == itemID).SingleOrDefault(); currentItem.StartingBid = amount; _context.Auctions.Add(newAuction); } else if (auction != null) { if (amount > currentItem.StartingBid && currentUser.Wallet > amount) { auction.TopbidderID = (int)HttpContext.Session.GetInt32("CurrentUserID"); currentItem.StartingBid = amount; } else { TempData["error"] = "You need to put higher number than current top bid or You need more money to bid!"; return(RedirectToAction("ShowProduct", new { itemID = itemID })); } } else { ViewBag.Error = "Something Went wrong..."; return(View("Product")); } _context.SaveChanges(); return(RedirectToAction("Dashboard")); }
public bool AuctionIsValid(Auction newAuction) { if (string.IsNullOrEmpty(this.Title)) { return(false); } if (string.IsNullOrEmpty(this.Description)) { return(false); } if (this.StartPrice <= 0) { return(false); } if (this.EndDateTimeUtc < DateTime.Now) { return(false); } return(true); }
private void SendToSeller(Auction auction) { ABUser seller = auction.AllUsers.Where(x => x.Role != null && x.Role.UserRoleName == "SELLER").FirstOrDefault(); if (seller != null) { // Find all buyers that isnt a winner string body = @"<p>The auction you have listed has ended.</p> <p>Please ship the item to the highest bidder to receive the payment</p> <p>Thank you,</p> <p>AnonymousBidder Team</p> <p>AnonymousBidder Pte. Ltd.</p> <p><i>This is a system auto-generated email. Please do not reply to this email. </i></p>"; EmailHelper.SendMail("*****@*****.**", seller.Email, "The auction you have listed has ended", body, "", "smtp_anonymousbidder"); } }
public ActionResult Create(string id) { if (id == null) { return(HttpNotFound()); } var product = _productRepository.Find(id); if (product == null) { return(HttpNotFound()); } ViewBag.ProductName = product.Name; var model = new Auction { Id = id, DateEnd = DateTime.UtcNow.ConvertToSiteZoneFromUtc(), DateStart = DateTime.UtcNow.ConvertToSiteZoneFromUtc() }; return(View(model)); }
public void GetDetailsForAuction_IdNotFound() { // Arrange Mock <IRestClient> restClient = new Mock <IRestClient>(); restClient.Setup(x => x.Execute <Auction>(It.Is <IRestRequest>(r => r.Resource == (APIService.API_URL + "/99")), Method.GET)) .Returns(new RestResponse <Auction> { StatusCode = HttpStatusCode.OK, Data = null, ResponseStatus = ResponseStatus.Completed }); apiService.client = restClient.Object; // Act Auction actualAuction = apiService.GetDetailsForAuction(99); // Assert APIService.API_URL.Should().Be(EXPECTED_API_URL); restClient.Verify(x => x.Execute <Auction>(It.Is <IRestRequest>(r => r.Resource == (EXPECTED_API_URL + "/99")), Method.GET), Times.Once()); actualAuction.Should().BeNull(); }
public Auction GetGoodAuction(BiddingBroker broker) { Product goodProduct = GetGoodProduct(broker); double startValue = 123.3; Currency currency = broker.GetCurrencyByName("ron"); DateTime startDate = DateTime.Now; DateTime endDate = DateTime.Now.AddDays(1); Auction goodAuction = new Auction() { StartDate = startDate, EndDate = endDate, StartValue = startValue }; goodAuction.Product = goodProduct; goodAuction.Currency = currency; return(goodAuction); }
// DELETE api/Auctions/5 public HttpResponseMessage DeleteAuction(long id) { Auction auction = db.Auctions.Find(id); if (auction == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } db.Auctions.Remove(auction); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } return(Request.CreateResponse(HttpStatusCode.OK, auction)); }
public IActionResult Delete(int id) { Auction target = _context.Auctions.SingleOrDefault(a => a.id == id); if (target == null) { return(RedirectToAction("Main")); } if (target.creator_id != HttpContext.Session.GetInt32("id")) { return(RedirectToAction("Main")); } if (target.top_bidder_id != 0) { User topBidder = _context.Users.SingleOrDefault(u => u.id == target.top_bidder_id); topBidder.wallet += target.top_bid; _context.Update(topBidder); } _context.Remove(target); _context.SaveChanges(); return(RedirectToAction("Main")); }
private void LoadDatagrid() { //FormLoading(); try { Auction lObjAuction = mObjAuctionsServicesFactory.GetAuctionService().GetCurrentOrLast(AuctionCategoryEnum.AUCTION); mLstObjBatchExchange = mObjAuctionsServicesFactory.GetBatchService().GetBatchExchangeListToPick(lObjAuction != null ? lObjAuction.Id : 0, mObjBuyerClassification.Id); mLcvListData = new ListCollectionView(mLstObjBatchExchange); this.Dispatcher.Invoke(() => { dgBatch.ItemsSource = null; dgBatch.ItemsSource = mLstObjBatchExchange; SetControlsAuction(lObjAuction); }); } catch (Exception) { throw; } }
// PUT api/Auctions/5 public HttpResponseMessage PutAuction(long id, Auction auction) { if (ModelState.IsValid && id == auction.Id) { db.Entry(auction).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } return(Request.CreateResponse(HttpStatusCode.OK)); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } }
public ActionResult AuctionClose(int idAuction) { Auction a = db.Auctions.Find(idAuction); if (a != null) { DateTime time = ((DateTime)a.OpenedOn).AddSeconds(a.AuctionTime); //ako je sadasnje vreme posle vremena zatvaranje aukcije if (time <= DateTime.UtcNow) { User owner = db.Users.Find(a.FirstUser); owner.TokensNumber += (double?)a.CurrentPrice; a.CompletedOn = DateTime.UtcNow; a.Status = "COMPLETED"; db.Entry(a).State = EntityState.Modified; db.Entry(owner).State = EntityState.Modified; db.SaveChanges(); log.Info("Closed Auction Name : " + a.Name); } } return(RedirectToAction("SearchAuctions", "Auction")); }
public IActionResult CreateAuction(AuctionViewModel model) { int? userId = HttpContext.Session.GetInt32("currentUserId"); if(userId == null) { TempData["LogErrors"] = "You need to log in first"; return RedirectToAction("Index"); } else { User currentUser = _context.Users.SingleOrDefault(u => u.UserId == (int)userId); if(ModelState.IsValid) { if(model.EndDate.Date<DateTime.Today) { TempData["InvalidTime"] = "Your end date has to be after today"; return View(); } else { Auction newAuction = new Auction { ProductName = model.ProductName, CreatedUser = currentUser.FirstName + " " + currentUser.LastName, Description = model.Description, MinimumBid = model.MinimumBid, EndDate = model.EndDate, Created_at = DateTime.Now, Updated_at = DateTime.Now }; _context.Add(newAuction); _context.SaveChanges(); return RedirectToAction("Home"); } } TempData["InvalidTime"] = "Your end date has to be after today"; return View(); } }
public ActionResult Auction(string ID) { using (var ctx = new AuctionModel()) { try { ViewBag.Message = "Auction"; Auction auction = ctx.GetAuction(ID); if (auction == null) { ViewBag.ErrorMsg = "Auction with provided ID doesn't exist."; return(View("Error")); } ViewBag.OwnerID = auction.User.ID; ViewBag.OwnerFirstName = auction.User.FirstName; ViewBag.OwnerLastName = auction.User.LastName; var bids = auction.Bids.OrderByDescending(o => o.CreatedOn).ToList(); ViewBag.Bids = bids; if (bids.Count > 0) { ViewBag.LastBidderID = bids.First().User.ID; ViewBag.LastBidderFirstName = bids.First().User.FirstName; ViewBag.LastBidderLastName = bids.First().User.LastName; } return(View("Auction", auction)); } catch (Exception e) { logger.Error(e.Message); ViewBag.ErrorMsg = "Internal server error."; return(View("Error")); } } }
public void SetUp() { auction = AuctionTestUtils.CreateAuction(); for (int i = 0; i < users.Length; i++) { users[i] = AuctionTestUtils.CreateUser(); } var mockRepo = new Mock <IUserRepository>(); mockRepo.Setup(r => r.FindUser(It.IsAny <UserIdentity>())).Returns <UserIdentity>(identity => { return(auction.Bids.Where(bid => bid.UserIdentity.UserId.Equals(identity.UserId)) .Select(bid => bid.UserIdentity) .Select(userIdentity => users.First(user => user.UserIdentity.UserId.Equals(userIdentity.UserId))) .FirstOrDefault()); }); service = new BuyNowService(mockRepo.Object); }
private Delivery CreateDelivery(Auction currentAuction, string username) { ApplicationUser currentUser = this.db.Users.All().FirstOrDefault(user => user.UserName == username); if (currentUser == null) { throw new ArgumentNullException("User not found."); } Delivery createdDelivery = new Delivery { Id = Guid.NewGuid(), DateShipped = DateTime.Now, Duration = currentAuction.DeliveryDuration, Receiver = currentUser, State = DeliveryState.Shipping }; createdDelivery.Products.Add(currentAuction.Product); return(createdDelivery); }
public void Create(Guid auctionId, Guid productId, DateTime startTime, DateTime endTime) { if (endTime < startTime) { throw new EndTimeBeforeStartTimeException( string.Format("End time {0} cannot be earlier than start time {1}", endTime, startTime)); } if (endTime < DateTime.Now) { throw new EndTimeEarlierThanNowException(string.Format("End time {0} cannot be earlier than now", endTime)); } var product = _productRepository.Get(productId); if (product == null) { throw new ProductNotExistException(string.Format("Product with id {0} does not exist", productId)); } if (product.IsSold) { throw new ProductIsSoldException(product.Name); } if (_auctionRespository.GetAuctions().Any(a => a.IsActive && a.Product.Id == productId)) { throw new ProductHasActiveAuctionException(product.Name); } var auction = new Auction { Id = auctionId, AcceptedPrice = product.GetStartPrice() * (decimal)1.5, Product = product, StartTime = startTime, EndTime = endTime, IsActive = startTime < DateTime.Now }; _auctionRespository.AddAuction(auction); }
public bool UpdateAuctionDetails(AuctionEditRequestModel request, int loggedInUserId) { var strategy = m_context.Database.CreateExecutionStrategy(); strategy.Execute(() => { try { using (var transaction = m_context.Database.BeginTransaction()) { Auction auctionForUpdate = m_context.Auctions.FirstOrDefault(auct => auct.AuctionId == request.AuctionId); if (auctionForUpdate.IsNotSpecified() == false) { auctionForUpdate.Name = request.AuctionName; auctionForUpdate.StartingPrice = request.AuctionStartingPrice; auctionForUpdate.StartDate = request.AuctionStartDate; auctionForUpdate.ApplyTillDate = request.AuctionApplyTillDate; auctionForUpdate.EndDate = request.AuctionEndDate; // todo: kke: add missing status change here! m_context.SaveChanges(); transaction.Commit(); } else { throw new WebApiException(HttpStatusCode.BadRequest, AuctionErrorMessages.CouldNotUpdateAuction); } } } catch (Exception ex) { throw new WebApiException(HttpStatusCode.BadRequest, AuctionErrorMessages.CouldNotUpdateAuction, ex); } }); return(true); }
public ActionResult NewAuction(NewAuctionViewModel model) { if (!ModelState.IsValid) { return(RedirectToAction("NewAuction", "Account")); } byte[] img = new byte[model.Picture.ContentLength]; model.Picture.InputStream.Read(img, 0, img.Length); string userId = User.Identity.GetUserId(); int Id = db.User.Where(u => u.idAspNetUsers == userId).FirstOrDefault().Id; Admin admin = db.Admin.FirstOrDefault(); Auction auction = new Auction(); auction.Id = Guid.NewGuid(); auction.Name = model.ProductName; auction.Picture = img; auction.Duration = model.Duration; auction.StartingPrice = model.StartingPrice; auction.CurrentPrice = model.StartingPrice; auction.DateTimeCreated = DateTime.Now; auction.PriceInTokens = (int)Math.Ceiling(model.StartingPrice / admin.ValueOfToken); auction.TokenValue = admin.ValueOfToken; auction.DateTimeOpened = null; auction.DateTimeClosed = null; auction.Status = "READY"; auction.Currency = admin.Currency; auction.IdOfUser = Id; db.Auction.Add(auction); db.SaveChanges(); return(RedirectToAction("UserIndex", "Auction")); }
public void ModifySavedAuction(Auction anAuction) { string insertString = "UPDATE Auction SET timeLeft=@timeLeft, payment=@payment, result=@result, paymentDate=@paymentDate, " + "productName=@productName, productDescription=@productDescription WHERE id=@id"; using (TransactionScope scope = new TransactionScope()) { using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand CreateCommand = new SqlCommand(insertString, con)) { SqlParameter idParam = new SqlParameter("@id", anAuction.AuctionId); CreateCommand.Parameters.Add(idParam); SqlParameter timeLeftParam = new SqlParameter("@timeLeft", anAuction.TimeLeft); CreateCommand.Parameters.Add(timeLeftParam); SqlParameter paymentParam = new SqlParameter("@payment", anAuction.Payment); CreateCommand.Parameters.Add(paymentParam); SqlParameter resultParam = new SqlParameter("@result", anAuction.Result); CreateCommand.Parameters.Add(resultParam); SqlParameter payDateParam = new SqlParameter("@paymentDate", anAuction.PaymentDate); CreateCommand.Parameters.Add(payDateParam); SqlParameter prodNameParam = new SqlParameter("@productName", anAuction.ProductName); CreateCommand.Parameters.Add(prodNameParam); SqlParameter prodDescriptParam = new SqlParameter("@productDescription", anAuction.ProductDescription); CreateCommand.Parameters.Add(prodDescriptParam); con.Open(); // Execute save /*int rowsAffected = */ int modified = CreateCommand.ExecuteNonQuery(); scope.Complete(); // Evaluate //wasInserted = (rowsAffected == 6); //return wasInserted; } } } }
public ActionResult BatchInformation(Guid id) { List <TransactionVM> SalesWithAgent = new List <TransactionVM>(); IEnumerable <TransactionVM> SalesWithoutAgent = TransactionRepo.GetAll(x => x.BatchId == id && x.TransactionType == TransactionType.Sale).ToList().Select(x => new TransactionVM() { Transaction = x }); IEnumerable <TransactionVM> Auctions = AuctionLogic.FetchCompletedAuctionTransactionsForBatch(id).ToList().Select(x => new TransactionVM() { Transaction = x }); Auction AuctionInformation = Auctionrepo.Get(x => x.BatchId == id); foreach (var item in SalesWithoutAgent) { item.Agent = UserManager.FindById(item.Transaction.AgentId); SalesWithAgent.Add(item); } foreach (var item in Auctions) { item.Auctionee = UserManager.FindById(item.Transaction.AuctioneeId); } BatchInformationVM Records = new BatchInformationVM() { Transactions = SalesWithAgent, AuctionRecords = Auctions, ToBeAuctionedRecord = ToBeAuctionedRepo.Get(x => x.BatchId == id), BatchInfo = ProductInStoreRepo.Get(x => x.Id == id), AuctionDetails = AuctionInformation, }; ViewBag.HA = Records.BatchInfo.DateWhichInventoryWasPurchased; return(View(Records)); }
public IActionResult NewBid(Bid bid) { int?userId = HttpContext.Session.GetInt32("logged_in_id"); if (userId is null) { return(RedirectToAction("LoginReg")); } ViewBag.Name = HttpContext.Session.GetString("logged_in"); User userLoggedIn = dbContext.Users.FirstOrDefault(user => user.UserId == userId); Auction auction = dbContext.Auctions .Include(x => x.Creator) .Include(x => x.Bids) .ThenInclude(x => x.Bidder) .FirstOrDefault(a => a.AuctionId == bid.AuctionId); if (ModelState.IsValid) { if (bid.Amount > userLoggedIn.CurrentWallet) { ModelState.AddModelError("Bid", "You don't have enough money to bid!"); return(View("ViewAuction", auction)); } // if (bid < auction.CurrentHighestBid) // { // ModelState.AddModelError("Bid", "Your bid is too low!"); // return View("ViewAuction", auction); // } dbContext.Bids.Add(bid); dbContext.SaveChanges(); return(RedirectToAction("Auctions")); } // ViewBag.CurrentHighestBidder = dbContext.Users.Where(u => u.UserId == auction.HighestBidderId).FirstOrDefault(); return(View("ViewAuction", auction)); }
public IActionResult NewBid(double newbid, int Id) { if (HttpContext.Session.GetInt32("Id") != null) { User _User = _context.users.SingleOrDefault(u => u.Id == HttpContext.Session.GetInt32("Id")); Auction _Auction = _context.auctions.SingleOrDefault(a => a.Id == Id); var bidcheck = _User.TotalBid; if (newbid <= _User.Wallet && (bidcheck += newbid) <= _User.Wallet && newbid > _Auction.StartingBid) { //create and add user to bid Bid _bid = new Bid(); _bid.bid = newbid; _bid.userid = _User.Id; _bid.auctionid = Id; _context.bids.Add(_bid); //add to user's totalbid pool _User.TotalBid += newbid; //change auction's startingbid to the new bid _Auction.StartingBid = newbid; _context.SaveChanges(); return(RedirectToAction("Auction", new { Id = Id })); } else if (newbid <= _Auction.StartingBid) { TempData["Error"] = "Your bid isn't high enough."; return(RedirectToAction("Auction", new { Id = Id })); } else { TempData["Error"] = "You don't have enough money in your wallet."; return(RedirectToAction("Auction", new { Id = Id })); } } else { return(View("Index")); } }
public IActionResult CreateNewAuction(Auction auction) { if (HttpContext.Session.GetInt32("Id") != null) { if (ModelState.IsValid) { if (auction.EndDate > DateTime.Now) { System.Console.WriteLine(auction); System.Console.WriteLine(auction); Auction NewAuction = new Auction(); NewAuction.userid = (int)HttpContext.Session.GetInt32("Id"); NewAuction.Name = auction.Name; NewAuction.Description = auction.Description; NewAuction.StartingBid = auction.StartingBid; NewAuction.EndDate = auction.EndDate; _context.Add(NewAuction); _context.SaveChanges(); return(RedirectToAction("Dashboard")); } else { ViewBag.Errors = "Your end date must be in the future!"; return(View("NewAuction")); } } else { ViewBag.Errors = "Your end date must be in the future."; return(View("NewAuction")); } } else { return(View("Index")); } }
// GET: Auctions/Details/5 public ActionResult Details(Guid?id) { var userId = Guid.Parse(User.Identity.GetUserId()); if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Auction auction = db.Auctions.Find(id); if (auction == null) { return(HttpNotFound()); } var auctionBids = db.Biddings.Where(x => x.AuctionId == auction.Id).ToList(); var viewModel = new AuctionDetailsViewModel() { Id = auction.Id, Name = auction.Name, Description = auction.Description, EndDate = auction.EndDate, StartingPrice = auction.StartingPrice, ImagePath = auction.ImagePath, StartDate = auction.StartDate, }; if (auctionBids.Any()) { viewModel.NumberOfBidders = auctionBids.GroupBy(x => x.UserId).Count(); viewModel.HighestBid = auctionBids.Max(x => x.BidPrice); viewModel.UserBid = auctionBids.FirstOrDefault(x => x.UserId == userId)?.BidPrice ?? 0; } ViewData["AuctionDetails"] = viewModel; ViewData["UserId"] = userId; return(View(new BidModel())); }
public void TiedAuctionShouldResolveProperly() { var dice = new List <Die> { new Die { Face = 2 }, new Die { Face = 6 }, new Die { Face = 6 }, new Die { Face = 2 }, new Die { Face = 4 }, }; var train = new Train(6); var auction = new Auction(train, new List <int> { 11, 12, 13, 14, 15 }); foreach (var die in dice) { auction.PlaceBid(die); } var expected = CompanyType.SquareRail; var actual = auction.AuctionWinner; Assert.Equal(expected, actual); }
public ActionResult Create(Auction auction) { try { if(String.IsNullOrEmpty(auction.Title)) { ModelState.AddModelError("Title","Title cannot be null."); } if(ModelState.IsValid) { _list.Add(auction); return RedirectToAction("Index"); } } catch { return View(auction); } return View(auction); }
/// <summary>Creates a new, empty Entity object of the type specified</summary> /// <param name="entityTypeToCreate">The entity type to create.</param> /// <returns>A new, empty Entity object.</returns> public static IEntity Create(Auction.Entities.EntityType entityTypeToCreate) { IEntityFactory factoryToUse = null; switch(entityTypeToCreate) { case Auction.Entities.EntityType.AccountEntity: factoryToUse = new AccountEntityFactory(); break; case Auction.Entities.EntityType.AuctionEventEntity: factoryToUse = new AuctionEventEntityFactory(); break; case Auction.Entities.EntityType.AuctionEventDonorEntity: factoryToUse = new AuctionEventDonorEntityFactory(); break; case Auction.Entities.EntityType.BidderEntity: factoryToUse = new BidderEntityFactory(); break; case Auction.Entities.EntityType.CategoryEntity: factoryToUse = new CategoryEntityFactory(); break; case Auction.Entities.EntityType.DonationEntity: factoryToUse = new DonationEntityFactory(); break; case Auction.Entities.EntityType.DonorEntity: factoryToUse = new DonorEntityFactory(); break; case Auction.Entities.EntityType.ExpenseEntity: factoryToUse = new ExpenseEntityFactory(); break; case Auction.Entities.EntityType.PackageEntity: factoryToUse = new PackageEntityFactory(); break; case Auction.Entities.EntityType.RaffleEntity: factoryToUse = new RaffleEntityFactory(); break; case Auction.Entities.EntityType.RoleEntity: factoryToUse = new RoleEntityFactory(); break; case Auction.Entities.EntityType.UserEntity: factoryToUse = new UserEntityFactory(); break; } IEntity toReturn = null; if(factoryToUse != null) { toReturn = factoryToUse.Create(); } return toReturn; }