Esempio n. 1
0
        public async Task <IActionResult> PostEntry([FromForm] string memory, [FromForm] string userIdentifier)
        {
            var json = JObject.Parse(memory);

            // TODO: Post memory data to Zapier link

            var entry = new RaffleEntry
            {
                MessageSid  = json["twilio"]["sms"]["MessageSid"].ToString(),
                PhoneNumber = userIdentifier
            };

            JsonResult response   = null;
            var        googleData = GetGoogleSheetData(json["twilio"]["collected_data"]["collect_raffle_data"].ToString());

            try
            {
                var sid = await SendRaffleEntryToService(entry);
                await SendRaffleEntryToZapier(googleData.Name, googleData.Major, googleData.Classification, googleData.GradDate);

                response = NotifyRaffleEntrant("You are now entered into the raffle. We'll send you a text to let you know if you've won. Join us tonight and tomorrow for more exciting events by registering at https://twiliohbcu20x20atauc.splashthat.com/. Good luck 😉!");
            }
            catch (Exception)
            {
                // TODO: Log the error if an error occurs
                response = NotifyRaffleEntrant("We ran into a problem adding you to the raffle. Sit tight for a few minutes and try again afterwards.");
                throw;
            }
            finally
            {
                await _connection.StopAsync();
            }

            return(response);
        }
        public async void NoDuplicateSoldProduct()
        {
            Guid        serial  = Guid.NewGuid();
            SoldProduct product = new SoldProduct {
                SerialNumber = serial
            };

            RaffleDbContext context = getDb("NoDupe");

            context.SoldProducts.Add(product);
            await context.SaveChangesAsync();

            RaffleEntry entry = getEntry();

            entry.SoldProduct.SerialNumber = serial;

            RaffleApiController controller = new RaffleApiController(
                context,
                new EntryValidator());

            IStatusCodeActionResult result = await controller.PostRaffleEntry(entry);

            StatusCodeResult statusResult = Assert.IsType <StatusCodeResult>(result);

            Assert.Equal((int)HttpStatusCode.OK, statusResult.StatusCode);

            Assert.Equal(1, await context.SoldProducts.CountAsync());
        }
Esempio n. 3
0
        public void EntryWithTwoPreviousEntries()
        {
            _entries = new List <RaffleEntry>();

            Guid        serial      = Guid.NewGuid();
            SoldProduct soldProduct = new SoldProduct {
                SerialNumber = serial
            };

            _products = new List <SoldProduct> {
                soldProduct
            };

            RaffleEntry entry1 = getEntry();

            entry1.SoldProduct = soldProduct;

            RaffleEntry entry2 = getEntry();

            entry2.SoldProduct = soldProduct;

            _entries.Add(entry1);
            _entries.Add(entry2);

            _entry             = getEntry();
            _entry.SoldProduct = soldProduct;

            bool validEntry = _validator.ValidateEntry(_products.AsQueryable(), _entries.AsQueryable(), _entry);

            Assert.False(validEntry, "Entry got validated with 2 previous entries with the same serial number.");
        }
Esempio n. 4
0
        public void EntryWithOnePreviousEntry()
        {
            _entries = new List <RaffleEntry>();

            Guid        serial      = Guid.NewGuid();
            SoldProduct soldProduct = new SoldProduct {
                SerialNumber = serial
            };

            _products = new List <SoldProduct> {
                soldProduct
            };

            RaffleEntry entry1 = getEntry();

            entry1.SoldProduct = soldProduct;
            _entries.Add(entry1);

            _entry             = getEntry();
            _entry.SoldProduct = soldProduct;

            bool validEntry = _validator.ValidateEntry(_products.AsQueryable(), _entries.AsQueryable(), _entry);

            Assert.True(validEntry, "Entry got rejected even though there has only been 1 previous entry with the same serial number.");
        }
        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);
        }
Esempio n. 6
0
        private async Task <string> NotifyRaffleWinner(RaffleEntry entry)
        {
            var msg = await MessageResource.FetchAsync(
                entry.MessageSid,
                _accountSid);

            var response = await MessageResource.CreateAsync(
                msg.From,
                from : msg.To,
                body : @"You've won the latest raffle. Visit the Twilio booth to pick up your prize. If you can't email [email protected]");

            _notificationSid = response.Sid;

            using (var httpClient = new HttpClient())
            {
                var data = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("winner", msg.From.ToString()),
                    new KeyValuePair <string, string>("raffleSid", LatestRaffle.Sid),
                    new KeyValuePair <string, string>("prize", LatestRaffle.Prize.Name)
                });

                var httpResponse = await httpClient.PostAsync("https://hooks.zapier.com/hooks/catch/3191324/o3o1bt1/", data);

                httpResponse.EnsureSuccessStatusCode();
            }

            return(_notificationSid);
        }
Esempio n. 7
0
        public void EntryGetsNewProductReference()
        {
            _entries = new List <RaffleEntry>();

            Guid        serial        = Guid.NewGuid();
            SoldProduct targetProduct = new SoldProduct {
                SerialNumber = serial, SoldProductId = 2
            };

            _products = new List <SoldProduct>
            {
                new SoldProduct {
                    SerialNumber = Guid.NewGuid(), SoldProductId = 1
                },
                targetProduct,
                new SoldProduct {
                    SerialNumber = Guid.NewGuid(), SoldProductId = 3
                },
            };

            _entry             = new RaffleEntry();
            _entry.SoldProduct = new SoldProduct {
                SerialNumber = serial
            };

            _validator.ValidateEntry(_products.AsQueryable(), _entries.AsQueryable(), _entry);

            Assert.Equal(targetProduct.SoldProductId, _entry.SoldProduct.SoldProductId);
        }
Esempio n. 8
0
        public void CleanupTest()
        {
            _currentRaffleEntry = null;
            _currentRaffle      = null;

            _configMock  = null;
            _updaterMock = null;
        }
Esempio n. 9
0
        public void ValidModel()
        {
            RaffleEntry             entry  = getEntry();
            List <ValidationResult> result = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entry, new ValidationContext(entry), result, true);

            Assert.True(isValid, "Valid model did not pass");
        }
Esempio n. 10
0
        private async Task <string> SendRaffleEntryToService(RaffleEntry entry)
        {
            var startConnectionTask = _connection.StartAsync();
            var sid = await _raffleService.AddRaffleEntry(entry);

            startConnectionTask.Wait();
            await _connection.InvokeAsync("AddRaffleEntry", entry);

            return(sid);
        }
Esempio n. 11
0
        private async Task UpdateEntryList(RaffleEntry entry)
        {
            // TODO: Replace Console.WriteLine with ILogger
            Console.WriteLine($"{DateTime.Now}: Adding {entry.MessageSid} to the entry list");
            await Task.Run(() => EntryList.Add(entry));

            Console.WriteLine($"{DateTime.Now}: Adding {entry.MessageSid} to the entry list");
            ToggleEnabledButtons(false, true, true);
            StateHasChanged();
        }
Esempio n. 12
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();
        }
Esempio n. 13
0
        public void EmailRequired()
        {
            RaffleEntry entry = getEntry();

            entry.Email = "";
            List <ValidationResult> result = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entry, new ValidationContext(entry), result, true);

            Assert.False(isValid, "Email must be required");
        }
Esempio n. 14
0
        public void SoldProductRequired()
        {
            RaffleEntry entry = getEntry();

            entry.SoldProduct = null;
            List <ValidationResult> result = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entry, new ValidationContext(entry), result, true);

            Assert.False(isValid, "SoldProduct must be required");
        }
Esempio n. 15
0
        public void LastNameContainsNoNumber()
        {
            RaffleEntry entry = getEntry();

            entry.FirstName = "3g3sen";
            List <ValidationResult> result = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entry, new ValidationContext(entry), result, true);

            Assert.False(isValid, "LastName must not contain numbers");
        }
Esempio n. 16
0
        public void AgeLessThanMinimum()
        {
            RaffleEntry entry = getEntry();

            entry.Age = 17;
            List <ValidationResult> result = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entry, new ValidationContext(entry), result, true);

            Assert.False(isValid, "Age must be required to be over 18");
        }
Esempio n. 17
0
        public void AgeGreaterThanMinimum()
        {
            RaffleEntry entry = getEntry();

            entry.Age = 60;
            List <ValidationResult> result = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entry, new ValidationContext(entry), result, true);

            Assert.True(isValid, "Age greater than minimum must pass.");
        }
Esempio n. 18
0
        public void AgeExactlyMinimum()
        {
            RaffleEntry entry = getEntry();

            entry.Age = 18;
            List <ValidationResult> result = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entry, new ValidationContext(entry), result, true);

            Assert.True(isValid, "Exact age must pass");
        }
Esempio n. 19
0
        public void InvalidEmail()
        {
            RaffleEntry entry = getEntry();

            entry.Email = "invalid";
            List <ValidationResult> result = new List <ValidationResult>();

            bool isValid = Validator.TryValidateObject(entry, new ValidationContext(entry), result, true);

            Assert.False(isValid, "Invalid email must not be accepted");
        }
Esempio n. 20
0
        /// <summary>
        /// Creates a raffle entry with all properties set except for SoldProduct
        /// </summary>
        /// <returns>RaffleEntry</returns>
        private RaffleEntry getEntry()
        {
            RaffleEntry entry = new RaffleEntry
            {
                FirstName = "Arthur",
                LastName  = "Dent",
                Email     = "*****@*****.**",
                Age       = 30
            };

            return(entry);
        }
        public async void ValidatorIsUsed()
        {
            RaffleApiController controller = new RaffleApiController(
                getDb("ValidatorTest"),
                new EntryValidator());

            RaffleEntry entry = getEntry();

            IStatusCodeActionResult result = await controller.PostRaffleEntry(entry);

            StatusCodeResult statusResult = Assert.IsType <StatusCodeResult>(result);

            Assert.Equal((int)HttpStatusCode.BadRequest, statusResult.StatusCode);
        }
Esempio n. 22
0
        /// <summary>
        /// Creates a valid raffle entry
        /// </summary>
        /// <returns>RaffleEntry</returns>
        private RaffleEntry getEntry()
        {
            RaffleEntry entry = new RaffleEntry
            {
                FirstName   = "Arthur",
                LastName    = "Dent",
                Email       = "*****@*****.**",
                Age         = 30,
                SoldProduct = new SoldProduct
                {
                    SerialNumber = new Guid()
                }
            };

            return(entry);
        }
Esempio n. 23
0
        public async Task <string> AddRaffleEntry(RaffleEntry entry)
        {
            if (LatestRaffle.State == RaffleState.NotRunning)
            {
                _logger.LogError("There is no raffle currently in progress.", LatestRaffle);
                throw new InvalidOperationException("Unable to add a raffle entry to the current raffle. The current raffle is not in progress");
            }

            _logger.LogInformation("Adding the latest raffle entry to the list of entries", entry);
            LatestRaffle.Entries.Add(entry);
            LatestRaffle.UpdatedDate = DateTime.UtcNow;

            await _storageUpdater.UpdateRaffle(LatestRaffle);

            _logger.LogInformation("Added the latest raffle entry to the list of entries", entry);
            return(LatestRaffle.Sid);
        }
Esempio n. 24
0
        public async Task AddRaffleEntry_ToNotRunningRaffle_WithValidEntry_ReturnNull()
        {
            // arrange
            _currentRaffle = new Raffle {
                State = RaffleState.NotRunning
            };
            _currentRaffleEntry = new RaffleEntry();
            var svc = new RaffleService(_updaterMock.Object, _prizeServiceMock.Object, _configMock.Object, _loggerMock.Object)
            {
                LatestRaffle = _currentRaffle
            };

            // act
            var result = await svc.AddRaffleEntry(_currentRaffleEntry);

            // assert
            // TODO: Update ASSERT for Adding a Raffle Entry to a Not Running
            Assert.IsNotNull(result);
        }
Esempio n. 25
0
        public void InvalidSerialNumber()
        {
            _entries = new List <RaffleEntry>();

            _products = new List <SoldProduct> {
                new SoldProduct {
                    SerialNumber = Guid.NewGuid()
                }
            };

            _entry             = getEntry();
            _entry.SoldProduct = new SoldProduct
            {
                SerialNumber = Guid.NewGuid()
            };

            bool validEntry = _validator.ValidateEntry(_products.AsQueryable(), _entries.AsQueryable(), _entry);

            Assert.False(validEntry, "A non valid serial number got accepted");
        }
Esempio n. 26
0
        /*
         * It's suboptimal that this isn't async, however, microsoft states:
         * EF Core doesn't support multiple parallel operations being run on the same context instance.
         * You should always wait for an operation to complete before beginning the next operation.
         * So how to get around this?
         */
        public bool ValidateEntry(IQueryable <SoldProduct> products,
                                  IQueryable <RaffleEntry> entries, RaffleEntry entry)
        {
            // Check if the serial number is valid
            if (products.Any(p => p.SerialNumber == entry.SoldProduct.SerialNumber))
            {
                // Set the instance of SoldProduct in the entry to be the one from the database
                // Otherwise the foreign key wont be resolved properly and the database will create a new product row
                // Maybe move this to a separate function?
                SoldProduct purchasedProduct = products.First(p => p.SerialNumber == entry.SoldProduct.SerialNumber);
                entry.SoldProduct = purchasedProduct;
                // Check that less than 2 entries has been submitted for the serial number
                if (entries.Count(e => e.SoldProduct.SerialNumber == entry.SoldProduct.SerialNumber) < 2)
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 27
0
        public async Task <StatusCodeResult> PostRaffleEntry([Bind("FirstName,LastName,Email,Age,SoldProduct")] RaffleEntry entry)
        {
            if (!ModelState.IsValid)
            {
                return(StatusCode((int)HttpStatusCode.BadRequest));
            }

            bool validEntry = _validator.ValidateEntry(_context.SoldProducts.AsQueryable(),
                                                       _context.Entries.AsQueryable(), entry);

            if (validEntry)
            {
                _context.Entries.Add(entry);
                await _context.SaveChangesAsync();

                return(StatusCode((int)HttpStatusCode.OK));
            }

            return(StatusCode((int)HttpStatusCode.BadRequest));
        }
Esempio n. 28
0
        public void ValidEntry()
        {
            _entries = new List <RaffleEntry>();

            Guid serial = Guid.NewGuid();

            _products = new List <SoldProduct> {
                new SoldProduct {
                    SerialNumber = serial
                }
            };

            _entry             = getEntry();
            _entry.SoldProduct = new SoldProduct
            {
                SerialNumber = serial
            };

            bool validEntry = _validator.ValidateEntry(_products.AsQueryable(), _entries.AsQueryable(), _entry);

            Assert.True(validEntry, "A valid entry was rejected.");
        }
Esempio n. 29
0
        public HouseRaffleManagementGump(HouseRaffleStone stone, SortMethod sort, int page) : base(40, 40)
        {
            m_Stone = stone;
            m_Page  = page;

            m_List = new List <RaffleEntry>(m_Stone.Entries);
            m_Sort = sort;

            switch (m_Sort)
            {
            case SortMethod.Name:
            {
                m_List.Sort(NameComparer.Instance);

                break;
            }

            case SortMethod.Account:
            {
                m_List.Sort(AccountComparer.Instance);

                break;
            }

            case SortMethod.Address:
            {
                m_List.Sort(AddressComparer.Instance);

                break;
            }
            }

            AddPage(0);

            AddBackground(0, 0, 618, 354, 9270);
            AddAlphaRegion(10, 10, 598, 334);

            AddHtml(10, 10, 598, 20, Color(Center("Raffle Management"), LabelColor), false, false);

            AddHtml(45, 35, 100, 20, Color("Location:", LabelColor), false, false);
            AddHtml(145, 35, 250, 20, Color(m_Stone.FormatLocation(), LabelColor), false, false);

            AddHtml(45, 55, 100, 20, Color("Ticket Price:", LabelColor), false, false);
            AddHtml(145, 55, 250, 20, Color(m_Stone.FormatPrice(), LabelColor), false, false);

            AddHtml(45, 75, 100, 20, Color("Total Entries:", LabelColor), false, false);
            AddHtml(145, 75, 250, 20, Color(m_Stone.Entries.Count.ToString(), LabelColor), false, false);

            AddButton(440, 33, 0xFA5, 0xFA7, 3, GumpButtonType.Reply, 0);
            AddHtml(474, 35, 120, 20, Color("Sort by name", LabelColor), false, false);

            AddButton(440, 53, 0xFA5, 0xFA7, 4, GumpButtonType.Reply, 0);
            AddHtml(474, 55, 120, 20, Color("Sort by account", LabelColor), false, false);

            AddButton(440, 73, 0xFA5, 0xFA7, 5, GumpButtonType.Reply, 0);
            AddHtml(474, 75, 120, 20, Color("Sort by address", LabelColor), false, false);

            AddImageTiled(13, 99, 592, 242, 9264);
            AddImageTiled(14, 100, 590, 240, 9274);
            AddAlphaRegion(14, 100, 590, 240);

            AddHtml(14, 100, 590, 20, Color(Center("Entries"), LabelColor), false, false);

            if (page > 0)
            {
                AddButton(567, 104, 0x15E3, 0x15E7, 1, GumpButtonType.Reply, 0);
            }
            else
            {
                AddImage(567, 104, 0x25EA);
            }

            if ((page + 1) * 10 < m_List.Count)
            {
                AddButton(584, 104, 0x15E1, 0x15E5, 2, GumpButtonType.Reply, 0);
            }
            else
            {
                AddImage(584, 104, 0x25E6);
            }

            AddHtml(14, 120, 30, 20, Color(Center("DEL"), LabelColor), false, false);
            AddHtml(47, 120, 250, 20, Color("Name", LabelColor), false, false);
            AddHtml(295, 120, 100, 20, Color(Center("Address"), LabelColor), false, false);
            AddHtml(395, 120, 150, 20, Color(Center("Date"), LabelColor), false, false);
            AddHtml(545, 120, 60, 20, Color(Center("Num"), LabelColor), false, false);

            int    idx    = 0;
            Mobile winner = m_Stone.Winner;

            for (int i = page * 10; i >= 0 && i < m_List.Count && i < (page + 1) * 10; ++i, ++idx)
            {
                RaffleEntry entry = m_List[i];

                if (entry == null)
                {
                    continue;
                }

                AddButton(13, 138 + (idx * 20), 4002, 4004, 6 + i, GumpButtonType.Reply, 0);

                int x     = 45;
                int color = (winner != null && entry.From == winner) ? HighlightColor : LabelColor;

                string name = null;

                if (entry.From != null)
                {
                    Account acc = entry.From.Account as Account;

                    if (acc != null)
                    {
                        name = String.Format("{0} ({1})", entry.From.Name, acc);
                    }
                    else
                    {
                        name = entry.From.Name;
                    }
                }

                if (name != null)
                {
                    AddHtml(x + 2, 140 + (idx * 20), 250, 20, Color(name, color), false, false);
                }

                x += 250;

                if (entry.Address != null)
                {
                    AddHtml(x, 140 + (idx * 20), 100, 20, Color(Center(entry.Address.ToString()), color), false, false);
                }

                x += 100;

                AddHtml(x, 140 + (idx * 20), 150, 20, Color(Center(entry.Date.ToString()), color), false, false);
                x += 150;

                AddHtml(x, 140 + (idx * 20), 60, 20, Color(Center("1"), color), false, false);
                x += 60;
            }
        }
Esempio n. 30
0
 public async Task AddRaffleEntry(RaffleEntry entry)
 {
     await Clients.All.SendAsync("AddRaffleEntry", entry);
 }