private void SetWinner() { Raffle.Models.Raffle selectedRaffle = this.item.Raffles.OrderBy(r => Guid.NewGuid()).First(); IEnumerable <Raffle.Models.Raffle> otherRaffles = this.item.Raffles.Where(r => r.RaffleNumber != selectedRaffle.RaffleNumber); selectedRaffle.IsPrized = true; foreach (var raffle in otherRaffles) { raffle.IsPrized = false; } this.item.ClosedAt = DateTime.Now; }
public Raffle.Models.Raffle BuyRaffle(UserProfile buyer) { lock (this.item) { ValidateTransaction(buyer); Raffle.Models.Raffle raffle = ExecuteTransaction(buyer); if (!this.item.CanBuy) { SetWinner(); } return(raffle); } }
public async Task <ActionResult> Purchase(int id) { UserProfile user = Context.UserProfiles.First(u => u.UserName == User.Identity.Name); if (user.UnusedRaffles == 0) { return(RedirectToAction("Index", new { id })); } Item item = await Context.Items.FindAsync(id); lock (item) { int mostRecentRaffleNumber = item.Raffles.OrderByDescending(r => r.RaffleNumber) .Select(r => r.RaffleNumber) .FirstOrDefault(); item.Raffles.Add(new Raffle.Models.Raffle { UserProfileId = user.UserId, PurchasedAt = DateTime.Now, RaffleNumber = mostRecentRaffleNumber + 1 }); user.UnusedRaffles--; Context.SaveChanges(); if (item.Raffles.Count == item.Price + (int)(item.Price * 0.40)) { Raffle.Models.Raffle selectedRaffle = item.Raffles.OrderBy(r => Guid.NewGuid()).First(); IEnumerable <Raffle.Models.Raffle> otherRaffles = item.Raffles.Where(r => r.RaffleNumber != selectedRaffle.RaffleNumber); selectedRaffle.IsPrized = true; foreach (var raffle in otherRaffles) { raffle.IsPrized = false; } item.ClosedAt = DateTime.Now; } } return(RedirectToAction("Index", new { id })); }
private Raffle.Models.Raffle ExecuteTransaction(UserProfile buyer) { int mostRecentRaffleNumber = this.item.Raffles.OrderByDescending(r => r.RaffleNumber) .Select(r => r.RaffleNumber) .FirstOrDefault(); var raffle = new Raffle.Models.Raffle { ItemId = this.item.Id, UserProfileId = buyer.UserId, RaffleNumber = mostRecentRaffleNumber + 1, PurchasedAt = DateTime.Now }; this.item.Raffles.Add(raffle); return raffle; }
private Raffle.Models.Raffle ExecuteTransaction(UserProfile buyer) { int mostRecentRaffleNumber = this.item.Raffles.OrderByDescending(r => r.RaffleNumber) .Select(r => r.RaffleNumber) .FirstOrDefault(); var raffle = new Raffle.Models.Raffle { ItemId = this.item.Id, UserProfileId = buyer.UserId, RaffleNumber = mostRecentRaffleNumber + 1, PurchasedAt = DateTime.Now }; this.item.Raffles.Add(raffle); return(raffle); }