コード例 #1
0
        public void RaffleHasFiveTickets()
        {
            var    builder      = new TicketsBuilder().StartingAt(1).EndingWith(5);
            Raffle testedRaffle = new Raffle(builder);

            Assert.AreEqual(5, testedRaffle.TicketCount);
        }
コード例 #2
0
        public async void TestInvalidSerial()
        {
            options = new DbContextOptionsBuilder <RaffleDbContext>()
                      .UseInMemoryDatabase(databaseName: "TestInvalidEntryDatabase").Options;
            RaffleDbContext  context    = new RaffleDbContext(options);
            RaffleController controller = new RaffleController(context);

            context.Serialnumbers.Add(new Serialnumber {
                Number = 1754
            });

            Raffle rafValid = new Raffle
            {
                Firstname = "Jane",
                Lastname  = "Doe",
                Age       = 20,
                Number    = 6821,
                Email     = "*****@*****.**"
            };

            context.SaveChanges();
            var result = await controller.Create(rafValid);

            Assert.False(context.Raffle.Any(), "Entry was added, with invalid Serial");
        }
コード例 #3
0
        public async Task <IActionResult> Edit(int id, [Bind("ID,Firstname,Lastname,Email,Number")] Raffle raffle)
        {
            if (id != raffle.ID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(raffle);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RaffleExists(raffle.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(raffle));
        }
コード例 #4
0
        public void TryObtainingTheNumberOfTicketsInTheRaffle()
        {
            var testedRaffle = new Raffle();

            // Fail :(
            Assert.AreEqual(3, testedRaffle.TicketCount);
        }
コード例 #5
0
        public async void TestValidAge()
        {
            options = new DbContextOptionsBuilder <RaffleDbContext>()
                      .UseInMemoryDatabase(databaseName: "TestCreateValidEntryDatabase").Options;
            RaffleDbContext  context    = new RaffleDbContext(options);
            RaffleController controller = new RaffleController(context);

            context.Serialnumbers.Add(new Serialnumber {
                Number = 6821
            });

            Raffle rafValid = new Raffle
            {
                Firstname = "Jane",
                Lastname  = "Doe",
                Age       = 20,
                Number    = 6821,
                Email     = "*****@*****.**"
            };

            context.SaveChanges();
            var result = await controller.Create(rafValid);

            ViewResult viewResult = Assert.IsType <ViewResult>(result);

            Assert.True(context.Raffle.Any(), "Entry wasn't added, with valid age and serial");
        }
コード例 #6
0
        public async Task StartRaffle(bool reuseEntrants = false)
        {
            // Determine if Raffle is in progress
            // If so throw an exception so the raffle is ended
            _logger.LogInformation("Starting a new raffle");
            if (LatestRaffle != null && LatestRaffle.State == RaffleState.Running)
            {
                _logger.LogWarning("There is a Raffle in progress. Stop that raffle first");
                await Task.CompletedTask;
            }
            else
            {
                // Select re-entrants to the new raffle
                var prize = await SelectRafflePrize();

                LatestRaffle = new Raffle
                {
                    Name    = $"Raffle-{DateTime.UtcNow}",
                    State   = RaffleState.Running,
                    Entries = LatestRaffle?.Entries?.Where(x => !x.IsWinner).ToList() ?? new List <RaffleEntry>(),
                    Prize   = prize
                };
                var doc = (await _storageUpdater.CreateRaffle(LatestRaffle.Name,
                                                              LatestRaffle)) as DocumentResource;

                LatestRaffle.Sid = doc?.Sid;
                if (reuseEntrants)
                {
                    await NotifyRaffleReEntrants();
                }

                _notificationSid = string.Empty;
            }
            _logger.LogInformation("Started a new raffle");
        }
コード例 #7
0
        public void TryObtainingTheNumberOfTicketsInTheRaffle()
        {
            var testedRaffle = new Raffle();

            // Use magic knowledge
            Assert.AreEqual(3, testedRaffle.TicketCount);
        }
コード例 #8
0
        public async Task <Raffle> AddOrUpdateAsync(Raffle raffle)
        {
            InsertOrUpdate(raffle);
            await SaveAsync();

            return(raffle);
        }
コード例 #9
0
        public void CleanupTest()
        {
            _currentRaffleEntry = null;
            _currentRaffle      = null;

            _configMock  = null;
            _updaterMock = null;
        }
        public void RaffleHasFiveTickets()
        {
            var testedRaffle = new Raffle(new HashSet <int> {
                1, 2, 3, 4, 5
            });

            Assert.AreEqual(5, testedRaffle.TicketCount);
        }
コード例 #11
0
 private void CalculateWinners(Raffle raffle)
 {
     foreach (var item in raffle.RaffleItems)
     {
         HeapInsertRollsFor(raffle.RaffleParticipants);
         GetWinnersFor(item);
     }
 }
コード例 #12
0
        public async Task <Raffle> GetRandom(int PrizeId)
        {
            var prizeDetail = Context.Prizes.FirstOrDefault(p => p.Id == PrizeId);

            var raffleCounter = Context.RaffleCounter.FirstOrDefault(c => c.Id == RaffleCounterId);

            var partMin = Context.Users.Min(u => u.First);

            var partMax = Context.Users.Max(u => u.Last);

            var participantRanges = Context.Users.OrderBy(u => u.First).ToList();

            var excludeList = Context.Excludes.Select(e => e.Number).ToHashSet();

            //Add winners to exclude list
            excludeList = excludeList.Union(
                Context.Raffles.Where(r => (r.RaffleCounter == raffleCounter.Counter && r.Status == RaffleStatus.NonWinner) ||
                                      (r.RaffleCounter != raffleCounter.Counter && r.Status == RaffleStatus.Winner)).
                Select(rp => rp.UserId).ToHashSet()
                ).ToHashSet();

            for (int i = 0; i < participantRanges.Count; i++)
            {
                if ((i + 1) < participantRanges.Count)
                {
                    var rangeLast = participantRanges[i + 1].First - participantRanges[i].Last;
                    if (rangeLast > 0)
                    {
                        var rangeExclude = Enumerable.Range(participantRanges[i].Last + 1, rangeLast - 1).ToHashSet();
                        excludeList = excludeList.Union(rangeExclude).ToHashSet();
                    }
                }
            }

            var rangeRandom = Enumerable.Range(partMin, partMax).Where(i => !excludeList.Contains(i));

            var rand  = new System.Random();
            int index = rand.Next(0, partMax - excludeList.Count);

            var raffle = new Raffle
            {
                Prize         = prizeDetail,
                Cicle         = raffleCounter.Cicle,
                UserId        = rangeRandom.ElementAt(index),
                RaffleCounter = raffleCounter.Counter,
                Status        = RaffleStatus.NonWinner
            };

            InsertOrUpdate(raffle);

            raffleCounter.Cicle = raffleCounter.Cicle + 1;
            UpdateCounter(raffleCounter);

            await SaveAsync();


            return(raffle);
        }
コード例 #13
0
        public RaffleWinners(Raffle raffle)
        {
            Raffle  = raffle;
            heap    = new PriorityQueue <RaffleParticipant, int>(new ExtractMax());
            random  = new RNGCryptoServiceProvider();
            Winners = new ObservableCollection <Winner>();

            CalculateWinners(Raffle);
        }
コード例 #14
0
 private void startRaffleButton_Click(object sender, EventArgs e)
 {
     raffle = new Raffle();
     raffle.StartRaffle(int.TryParse(entryfeeBox.Text, out var entryfee) ? entryfee : 0,
                        TextBoxHandler.CheckForInput(keywordBox, out string keyword) ? (keywordCaseSensitive.Checked ? keyword : keyword.ToLower()) : "",
                        TextBoxHandler.CheckForInput(timerBox, out string timerText) ? int.Parse(timerText) : 1,
                        followerBar.Value,
                        subscriberBar.Value);
 }
コード例 #15
0
        public void InitializeTest()
        {
            _configMock       = new Mock <IConfiguration>();
            _updaterMock      = new Mock <IRaffleStorageService>();
            _prizeServiceMock = new Mock <IPrizeService>();
            _loggerMock       = new Mock <ILogger <RaffleService> >();

            _currentRaffleEntry = new  RaffleEntry();
            _currentRaffle      = new Raffle();
        }
コード例 #16
0
 public ActionResult Create(Raffle raffle)
 {
     if (ModelState.IsValid) {
         _raffleRepository.InsertOrUpdate(raffle);
         _raffleRepository.Save();
         return RedirectToAction("Index");
     }
     ViewBag.PossibleNumbers = _lotteryNumberRepository.SoldAndPaidWithoutRafflePrize;
     ViewBag.PossiblePrizes = _prizeRepository.ToRaffle;
     return View();
 }
コード例 #17
0
 private void InsertOrUpdate(Raffle raffle)
 {
     if (raffle.Id != 0)
     {
         Context.Entry(raffle).State = EntityState.Modified;
     }
     else
     {
         Context.Set <Raffle>().Add(raffle);
     }
 }
コード例 #18
0
        public Data AddDataPoint(Raffle raffle)
        {
            Data data = new Data();

            data.Time     = DateTime.Now.Ticks;
            data.Money    = raffle.TotalRaised;
            data.RaffleId = raffle.RaffleId;
            context.Data.Add(data);
            context.SaveChanges();
            return(data);
        }
コード例 #19
0
        public static RaffleModel CastToRaffle(this Raffle raffle)
        {
            var model = new RaffleModel
            {
                id         = raffle.Id,
                eventDate  = raffle.EventDate,
                isComplete = raffle.IsComplete,
                title      = raffle.Title
            };

            return(model);
        }
コード例 #20
0
        public ParticipantAction AddAction(Raffle raffle, int tickets)
        {
            ParticipantAction action = new ParticipantAction();
            var         currentUser  = User.Identity.GetUserId();
            Participant participant  = context.Participants.FirstOrDefault(p => p.ApplicationUserId == currentUser);

            action.Action        = "Acquired " + tickets + " for " + raffle.Name + ", please pay for your tickets in the transactions tab.";
            action.Time          = DateTime.Now;
            action.ParticipantId = participant.ParticipantId;
            context.ParticipantActions.Add(action);
            context.SaveChanges();
            return(action);
        }
コード例 #21
0
ファイル: Data.cs プロジェクト: ahidson1/KhaosBot
        public static async Task <int> AddRaffle(string Name, DateTime End, int Prize)
        {
            Raffle raffle = new Raffle {
                CreateDate = DateTime.Now, DoneDate = End, RaffleName = Name, TokenPrize = Prize
            };

            using (var DbContext = new SQLiteDbContext())
            {
                DbContext.Raffles.Add(raffle);
                await DbContext.SaveChangesAsync();

                return(raffle.Id);
            }
        }
コード例 #22
0
        public Task StartRaffle(int numTickets, ulong channelId)
        {
            if (_raffleState.ContainsKey(channelId))
            {
                throw new RaffleException("Cannot start a raffle when one is already in progress!");
            }
            var raffle = new Raffle
            {
                MaxTickets = numTickets
            };

            _raffleState.Add(channelId, raffle);
            return(Task.CompletedTask);
        }
コード例 #23
0
        public async Task InitializeService()
        {
            _logger.LogInformation("Initializing the Raffle Service");
            if (LatestRaffle == null)
            {
                LatestRaffle = await _storageUpdater.GetLatestRaffle();
            }

            if (!_prizeService.IsInitialized)
            {
                await _prizeService.InitializeService();
            }
            _logger.LogInformation("Initialized the Raffle Service");
        }
コード例 #24
0
        public Transaction AddTransaction(Raffle raffle, double amount, int tickets)
        {
            var         currentUserId = User.Identity.GetUserId();
            Participant participant   = context.Participants.FirstOrDefault(p => p.ApplicationUserId == currentUserId);
            Transaction transaction   = new Transaction();

            transaction.Money         = amount;
            transaction.ManagerId     = raffle.ManagerId;
            transaction.ParticipantId = participant.ParticipantId;
            transaction.Paid          = false;
            transaction.Description   = "Purchasing " + tickets + " tickets from " + raffle.Name + ".";
            context.Transactions.Add(transaction);
            context.SaveChanges();
            return(transaction);
        }
コード例 #25
0
        public ActionResult AddItem([Bind(Include = "RafflePrizeId,Description,Value,RaffleId,Category,CurrentTickets,WinnerId,Name")] RafflePrize rafflePrize, int id)
        {
            Raffle raffle = context.Raffles.FirstOrDefault(a => a.RaffleId == id);

            rafflePrize.RaffleId       = raffle.RaffleId;
            rafflePrize.CurrentTickets = 0;
            rafflePrize.WinnerId       = null;


            context.RafflePrizes.Add(rafflePrize);
            context.SaveChanges();


            return(RedirectToAction("Continue", new { id = rafflePrize.RaffleId }));
        }
コード例 #26
0
        public ActionResult IndexRaffle(int id)
        {
            Raffle           raffle     = context.Raffles.FirstOrDefault(a => a.RaffleId == id);
            var              dataSet    = context.Data.Where(d => d.RaffleId == id);
            List <DataPoint> dataPoints = new List <DataPoint>();

            foreach (Data point in dataSet)
            {
                dataPoints.Add(new DataPoint(point.Time, point.Money));
            }

            ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);

            return(View());
        }
コード例 #27
0
        public ActionResult RaffleNumbers(int lotteryid)
        {
            var prize = _prizeRepository.GetOnePrizeForRaffle(lotteryid);
            var lotteryNumber = _lotteryNumberRepository.GetOneNumberForRaffle(lotteryid);

            int? raffleId = null;
            if (lotteryNumber != null && prize != null)
            {
                var raffle = new Raffle { LotteryNumberId = lotteryNumber.LotteryNumberId, PrizeId = prize.PrizeId };
                _raffleRepository.InsertOrUpdate(raffle);
                _raffleRepository.Save();
                raffleId = raffle.RaffleId;
            }

            return View("Details", raffleId == null ? null : _raffleRepository.Find((int) raffleId));
        }
コード例 #28
0
        public async Task <Raffle> StartRaffle()
        {
            var raffle = new Raffle()
            {
                FinishedAt    = -1,
                StartedAt     = DateTime.UtcNow.ToFileTimeUtc(),
                RaffleEntries = new List <RaffleEntry>()
            };

            using (var context = new AuctionContext())
            {
                raffle = context.Raffles.Add(raffle).Entity;
                await context.SaveChangesAsync();
            }
            return(raffle);
        }
コード例 #29
0
        public ActionResult BuyTickets([Bind(Include = "FirstName,LastName,EmailAddress,ApplicationUserId,RaffleTickets")] Participant participant, int id)
        {
            Raffle raffle            = context.Raffles.FirstOrDefault(r => r.RaffleId == id);
            var    currentUserId     = User.Identity.GetUserId();
            var    buyingParticipant = context.Participants.FirstOrDefault(p => p.ApplicationUserId == currentUserId);
            int    tickets           = (participant.RaffleTickets);
            double amount            = (tickets * raffle.CostPerTicket);

            raffle.TotalRaised += amount;
            buyingParticipant.RaffleTickets += participant.RaffleTickets;
            context.SaveChanges();
            AddDataPoint(raffle);
            var transaction = AddTransaction(raffle, amount, tickets);

            AddAction(raffle, tickets);
            return(RedirectToAction("Pay", "Transaction", new { id = transaction.TransactionId }));
        }
コード例 #30
0
        public async Task <IActionResult> Create([Bind("ID,Firstname,Lastname,Email,Age,Number")] Raffle raffle)
        {
            if (ModelState.IsValid)
            {
                if (_context.Serialnumbers.Any(s => s.Number == raffle.Number))
                {
                    if (_context.Raffle.Where(r => r.Number.Equals(raffle.Number)).Count() < 2)
                    {
                        _context.Add(raffle);
                        await _context.SaveChangesAsync();

                        return(View("Entered"));
                    }
                }
            }
            return(View());
        }
コード例 #31
0
        private void AddRaffle()
        {
            var raffle = new Raffle {
                Name     = "<Enter Name, and Select Items and Participants>",
                Location = new ContactDetails()
                {
                    Address1 = "<Enter Location and Contact Details>"
                },
                RaffleParticipants = new ObservableCollection <RaffleParticipant>(),
                RaffleItems        = new ObservableCollection <RaffleItem>()
            };

            uow.Raffles.Add(raffle);
            SelectedRaffle = new RaffleModel(raffle);
            Raffles.Add(SelectedRaffle);
            ClearSelectedItems();
            ClearSelectedParticipants();
        }
コード例 #32
0
        public RaffleModel(Raffle entity)
        {
            RaffleId = entity.RaffleId;

            Name           = entity.Name;
            Description    = entity.Description;
            Location       = entity.Location;
            ExecutionCount = entity.ExecutionCount;

            RaffleParticipants =
                new ObservableCollection <RaffleParticipant>(
                    entity.RaffleParticipants);
            RaffleItems =
                new ObservableCollection <RaffleItem>(
                    entity.RaffleItems);
            Winners = entity.Winners != null
                ? new ObservableCollection <Winner>(entity.Winners)
                : new ObservableCollection <Winner>();
        }
コード例 #33
0
        protected void populateLabels(Raffle raf)
        {
            //populate the picture
            imageLogo.ImageUrl = record.ImageLink;

            //sets correct website URL
            CharityWebsiteLink.HRef = record.WebsiteURL;
            //sets charity title
            CharityNameLabel.Text = record.Name;
            //sets charity description
            DescriptionLabel.Text = record.Description;
            //sets raffle end time
            DateTime endDate = raf.EndTime.Value;
            raffleEndLabel.Text = DaysTill(endDate);
            //sets raffle title

            //sets raised dollars
            MoneyRaisedLabel.Text = "$" + ((int)(raf.RaisedDollars)).ToString();
            //sets time until end
            //TimeSpan tilEnd = (TimeSpan)(raf.EndTime - DateTime.Now);
            //EndLabel.Text = tilEnd.TotalDays.ToString();
            //sets current prize amount
            PrizeLabel.Text = ((int)(raf.RaisedDollars) / 2).ToString();

            EnteredLabel.Text = (raf.TicketsEntered).ToString();
        }