Exemplo n.º 1
0
        public void AddContestantWithScoreToEvent(int contestantId, int rank, string score, string tiebreak, int eventId)
        {
            var context          = DataEntitiesProvider.Provide();
            var existingEntrants = context.Entrants.Where(e => e.Mind_Sport_ID == contestantId && e.EventId == eventId).ToList();

            if (existingEntrants.Any())
            {
                return;                          // no need
            }
            var evt        = context.Events.First(x => x.EIN == eventId);
            var contestant = context.Contestants.First(x => x.Mind_Sport_ID == contestantId);

            var newEntrant = new Entrant()
            {
                EventId    = eventId,
                OlympiadId = evt.OlympiadId,
                Name       = contestant,
                Absent     = false,
                Rank       = rank,
                Score      = score,
                Tie_break  = tiebreak
            };

            context.Entrants.Add(newEntrant);
            context.SaveChanges();
        }
Exemplo n.º 2
0
        public void AddNewContestantWithScoreToEvent(string firstName, string lastName, string onlineNickname, string country, int rank, string score, int eventId)
        {
            if (string.IsNullOrEmpty(firstName) && string.IsNullOrEmpty(lastName))
            {
                throw new ArgumentException("You must specify at least one of first name and last name");
            }

            var context = DataEntitiesProvider.Provide();

            var contestant = new Contestant()
            {
                Firstname       = firstName ?? "",
                Lastname        = lastName ?? "",
                Nationality     = country ?? "",
                OnlineNicknames = onlineNickname ?? "",
                Male            = true // The default, to exclude unknown people from Women's Pentamind until we have confirmed they are eligible
            };

            context.Contestants.Add(contestant);

            var evt = context.Events.First(x => x.EIN == eventId);

            var newEntrant = new Entrant()
            {
                EventId    = eventId,
                OlympiadId = evt.OlympiadId,
                Name       = contestant,
                Score      = score,
                Rank       = rank,
                Absent     = false
            };

            context.Entrants.Add(newEntrant);
            context.SaveChanges();
        }
Exemplo n.º 3
0
        public static Entrant Create()
        {
            if (_idealEntrantWasCreated == false)
            {
                var entrant = new Entrant
                {
                    Id        = 2, //(связано через claim с аккаунтом идеального пользователя)
                    FirstName = "IDEAL",
                    LastName  = "Ерохин"
                };

                using (var context = new OptimalEducationDbContext())
                {
                    //Добавляем ему результаты по ЕГЭ
                    foreach (
                        var discipline in context.ExamDisciplines.Where(p => p.ExamType == ExamType.UnitedStateExam))
                    {
                        entrant.UnitedStateExams.Add(
                            new UnitedStateExam
                        {
                            Discipline = discipline,
                            Entrant    = entrant,
                            Result     = 100
                        });
                    }
                    //Добавляем ему результаты по школьным предметам
                    foreach (var schoolDisc in context.SchoolDisciplines)
                    {
                        entrant.SchoolMarks.Add(
                            new SchoolMark
                        {
                            SchoolDiscipline = schoolDisc,
                            Entrant          = entrant,
                            Result           = 5
                        });
                    }
                    //Добавляем ему результаты по олимпиадам(по всем???)
                    for (var i = 0; i < 3; i++)
                    {
                        foreach (var olympiad in context.Olympiads)
                        {
                            entrant.ParticipationInOlympiads.Add(
                                new ParticipationInOlympiad
                            {
                                Entrant  = entrant,
                                Result   = OlypmpiadResult.FirstPlace,
                                Olympiad = olympiad
                            });
                        }
                    }

                    context.Entrants.Add(entrant);
                    context.SaveChanges();
                }

                _idealEntrantWasCreated = true;
                return(entrant);
            }
            throw new Exception("Идеальный пользователь уже был создан в Seed методе. Повторный вызов запрещен.");
        }
Exemplo n.º 4
0
        protected void Submit_Click(object sender, EventArgs e)
        {
            //Check the validation controls
            if (IsValid)
            {
                if (AgreeToTerms.Checked && !HasDuplicates())
                {
                    MessageLabel.Text = "Good luck on the contest!";
                    //Taking the data from the controls on the form, and creating objects
                    Entry submission = new Entry(EntryCode.Text, Email.Text);

                    Entrant person = new Entrant(FirstName.Text, LastName.Text, Email.Text, City.Text, Province.SelectedValue /*for a dropdown list*/, PostalCode.Text, int.Parse(Age.Text));

                    MessageLabel.Text = "Good luck on the contest!";


                    Entries.Add(submission);
                    PopulateGridView();
                }
                else
                {
                    if (!AgreeToTerms.Checked)
                    {
                        MessageLabel.Text = "You MUST agree to the terms of the contest!";
                    }
                    else //it's because of a duplicate submission
                    {
                        MessageLabel.Text = "That entry code has already been used";
                    }
                }
            }
        }
Exemplo n.º 5
0
        public void FreezeBackgammon()
        {
            var context                     = DataEntitiesProvider.Provide();
            var currentOlympiad             = context.Olympiad_Infoes.First(x => x.Current);
            var pentamindStandingsGenerator = new PentamindStandingsGenerator();

            // Next a Modern Abstract one
            var modernAbstractStandings = pentamindStandingsGenerator.GetBackgammonStandings(null);
            int rank = 1;

            foreach (var standing in modernAbstractStandings.Standings)
            {
                if (!standing.IsValid)
                {
                    continue;
                }

                var contestant = context.Contestants.FirstOrDefault(x => x.Mind_Sport_ID == standing.ContestantId);
                var evt        = context.Events.FirstOrDefault(x => x.OlympiadId == currentOlympiad.Id && x.Code == "BACC");
                var entry      = context.Entrants.FirstOrDefault(x => x.OlympiadId == currentOlympiad.Id &&
                                                                 x.Game_Code == "BACC" && x.Mind_Sport_ID == standing.ContestantId);
                if (entry == null)
                {
                    entry = Entrant.NewEntrant(evt.EIN, "BACC", currentOlympiad.Id, contestant, 0m);
                    context.Entrants.Add(entry);
                }
                entry.Score = standing.TotalScoreStr;
                entry.Rank  = rank;
                entry.Medal = MedalForRank(rank);
                rank++;
                context.SaveChanges();
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("EntrantId,IdentityDocumentId,CustomInformation,Snils,RegistrationAddressId,FactAddressId,MobilePhone,Email,Uid,CreatedDate,ModifiedDate,InstitutionId,LastName,FirstName,MiddleName,GenderId,PersonId,PersonLinkDate,EntrantGuid")] Entrant entrant)
        {
            if (id != entrant.EntrantId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(entrant);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EntrantExists(entrant.EntrantId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["FactAddressId"]         = new SelectList(_context.Address, "AddressId", "AddressId", entrant.FactAddressId);
            ViewData["GenderId"]              = new SelectList(_context.GenderType, "GenderId", "Name", entrant.GenderId);
            ViewData["IdentityDocumentId"]    = new SelectList(_context.EntrantDocument, "EntrantDocumentId", "DocumentSpecificData", entrant.IdentityDocumentId);
            ViewData["InstitutionId"]         = new SelectList(_context.Institution, "InstitutionId", "Ogrn", entrant.InstitutionId);
            ViewData["PersonId"]              = new SelectList(_context.Rvipersons, "PersonId", "NormSurname", entrant.PersonId);
            ViewData["RegistrationAddressId"] = new SelectList(_context.Address, "AddressId", "AddressId", entrant.RegistrationAddressId);
            return(View(entrant));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Create([Bind("EntrantID,Name,Tag")] Entrant entrant)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                foreach (var Image in files)
                {
                    if (Image != null && Image.Length > 0)
                    {
                        var file    = Image;
                        var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "images/uploads");

                        if (file.Length > 0)
                        {
                            var fileName       = HeaderUtilities.RemoveQuotes(file.FileName).ToString();
                            var fileType       = fileName.Split('.').Last();
                            var uniqueFileName = string.Format(@"{0}." + fileType, DateTime.Now.Ticks);

                            using (var fileStream = new FileStream(Path.Combine(uploads, uniqueFileName), FileMode.Create))
                            {
                                await file.CopyToAsync(fileStream);

                                entrant.Thumbnail = uniqueFileName;
                            }
                        }
                    }
                }

                _context.Add(entrant);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(entrant));
        }
 public void SaveEntrant(Entrant entrant)
 {
     if (entrant.EntrantID == 0)
     {
         context.Entrants.Add(entrant);
     }
     else
     {
         Entrant dbEntry = context.Entrants.Find(entrant.EntrantID);
         if (dbEntry != null)
         {
             dbEntry.FirstName   = entrant.FirstName;
             dbEntry.LastName    = entrant.LastName;
             dbEntry.FatherName  = entrant.FatherName;
             dbEntry.BirthDate   = entrant.BirthDate;
             dbEntry.GPA         = entrant.GPA;
             dbEntry.Town        = entrant.Town;
             dbEntry.Address     = entrant.Address;
             dbEntry.Biography   = entrant.Biography;
             dbEntry.School      = entrant.School;
             dbEntry.PhoneNumber = entrant.PhoneNumber;
         }
     }
     context.SaveChanges();
 }
Exemplo n.º 9
0
        public void SeedDatabase()
        {
            if (this.Database.ProviderName != "Microsoft.EntityFrameworkCore.InMemory")
            {
                this.Database.EnsureCreated();
                if (this.Clubs != null && this.Clubs.SingleOrDefault(a => a.ClubId == 1) == null)
                {
                    var brmc = new Club(1, "BRMC", "*****@*****.**", "https://www.bognor-regis-mc.co.uk");
                    brmc.SetAdminEmails(new[] { new AuthorisationEmail("*****@*****.**") });
                    this.Clubs.Add(brmc);
                }
                if (this.Events != null && this.Events.SingleOrDefault(a => a.EventId == 1) == null)
                {
                    var e = new Event(1, 1, "Kestrel Farm", new DateTime(2000, 1, 1), 10, 2, string.Empty, EventType.AutoTest, string.Empty, TimingSystem.StopWatch);
                    e.SetTests(new[] { new Test(1, "") });
                    this.Events.Add(e);
                }
                if (this.Entrants != null && this.Entrants.SingleOrDefault(a => a.EntrantId == 1) == null)
                {
                    var e = new Entrant(1, 1, "Matt", "McCorry", "*****@*****.**", "A", 1, true, "BRMC", 69, Age.Senior);
                    e.SetVehicle(new Vehicle("Vauxhall", "Corsa", 2005, 1229, Induction.NA, "AA05AAA"));
                    e.SetMsaMembership(new MsaMembership("Clubman", 1234));
                    this.Entrants.Add(e);
                }

                this.SaveChanges();
            }
        }
Exemplo n.º 10
0
 public static void DeleteEntrant(
     this DatabaseContext context
     , Entrant entrant)
 => context
 .Entrants
 .Local
 .Remove(entrant);
Exemplo n.º 11
0
        public ViewResult Edit(int entrantId)
        {
            Entrant entrant = repository.Find(entrantId);

            ViewBag.Title = "Edit";
            return(View(entrant));
        }
Exemplo n.º 12
0
        /// <inheritdoc />
        public async Task <Entrant> MergeWithStore(Entrant entrant)
        {
            Entrants.Update(entrant);
            await SaveChangesAsync().ConfigureAwait(false);

            return(await Entrants.FindAsync(entrant.RowKey).ConfigureAwait(false));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Creates a new entrant in table storage
        /// </summary>
        /// <param name="entrant">The entrant to save. The ID properties must already be populated</param>
        /// <returns>A task that completes when the storage has been updated</returns>
        public async Task Create(Entrant entrant)
        {
            await _entrantTable.CreateIfNotExistsAsync().ConfigureAwait(false);

            var operation = TableOperation.Insert(entrant);
            await _entrantTable.ExecuteAsync(operation).ConfigureAwait(false);
        }
Exemplo n.º 14
0
        public async Task <List <EducationLine> > Calculate(Entrant entrant, IEnumerable <EducationLine> educationLines)
        {
            //Вычисляем характеристики пользователя
            var userCharacterisics = await _entrantCharacterizer.Calculate(entrant);

            //Вычисляем характеристики учебных направлений
            var educationLineRequrements = new List <EducationLineWithCharacterisics>();

            foreach (var item in educationLines.Where(item => item.EducationLinesRequirements.Count > 0))
            {
                var characteristics = await _educationLineCharacterizer.Calculate(item);

                var educationLineWithCharacteristics = new EducationLineWithCharacterisics(item, characteristics);
                educationLineRequrements.Add(educationLineWithCharacteristics);
            }

            //Получаем предпочтения пользователя
            var userPref = _preferenceRelationCalculator.GetPreferenceRelations(userCharacterisics);
            //Пересчитываем кластеры университетов с учетом предпочтений пользователя
            var recalculatedCharacterisics = RecalculateEducationLineCharacterisics(educationLineRequrements, userPref);
            //Строим множество паррето-оптимальных веткоров
            var parretoEducationLineCharacterisics = ParretoSetCreate(recalculatedCharacterisics);

            return(parretoEducationLineCharacterisics.Select(item => item.EducationLine).ToList());
        }
Exemplo n.º 15
0
        public void Create_OnSparseCollection_AddsEntrant()
        {
            var dal = new EntrantDal();

            var controller = new EntrantController(dal);

            var entrant1 = new Entrant {
                FirstName = "First1", LastName = "Last1"
            };
            var action1 = controller.Create(entrant1);

            Assert.That(action1, Is.TypeOf <CreatedAtActionResult>());

            var entrant2 = new Entrant {
                FirstName = "First2", LastName = "Last2"
            };
            var action2 = controller.Create(entrant2);

            Assert.That(action2, Is.TypeOf <CreatedAtActionResult>());

            // create a gap by removing first entrant
            var deleteAction = controller.Delete(1);

            Assert.That(deleteAction, Is.TypeOf <OkResult>());

            var newEntrant = new Entrant {
                FirstName = "First2", LastName = "Last2"
            };
            var action = controller.Create(newEntrant);

            Assert.That(action, Is.TypeOf <CreatedAtActionResult>());
        }
Exemplo n.º 16
0
        /// <summary>
        /// Adds a new  <see cref="Entrant.Models.Entrant"/> object to the store
        /// </summary>
        /// <param name="entrant">A new entrant to store</param>
        /// <returns>returns the new stored entrant object with a unique Id.</returns>
        /// <remarks>The entrants first and last names must be supplied.</remarks>
        public Entrant Create(Entrant entrant)
        {
            if (entrant == null)
            {
                throw new ArgumentNullException(nameof(entrant));
            }

            if (string.IsNullOrWhiteSpace(entrant.FirstName))
            {
                throw new ArgumentException($"{nameof(entrant.FirstName)} can not be blank", nameof(entrant.FirstName));
            }

            if (string.IsNullOrWhiteSpace(entrant.LastName))
            {
                throw new ArgumentException($"{nameof(entrant.LastName)} can not be blank", nameof(entrant.LastName));
            }

            entrant.Id = Interlocked.Increment(ref _lastId);

            bool added = _entrantMap.TryAdd(entrant.Id, entrant);

            if (!added)
            {
                var msg = "Create new Entrant failed";
                Logger.Error(msg);
                throw new Exception(msg);
            }

            Logger.Info($"Created new Entrant id = {entrant.Id}");

            return(entrant);
        }
Exemplo n.º 17
0
        public async Task <IActionResult> Edit(int id, [Bind("EntrantID,Name,Tag,Thumbnail")] Entrant entrant)
        {
            if (id != entrant.EntrantID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(entrant);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!EntrantExists(entrant.EntrantID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index"));
            }
            return(View(entrant));
        }
Exemplo n.º 18
0
 public EntrantTimes(Entrant entrant, int totalTime, IEnumerable <TestTime> times, int position, int classPosition)
 {
     Entrant       = entrant;
     TotalTime     = totalTime;
     Times         = times;
     Position      = position;
     ClassPosition = classPosition;
 }
        public void SaveEntrant(Entrant entrant)
        {
            bool isFree = entrant.EducationFee == "Free";

            entrant.SpecialityId = findSpecialityId(entrant.SpecialityName, isFree);
            _entrantsContext.Entrants.Add(entrant);
            _entrantsContext.SaveChanges();
        }
        public void EditEntrant(Entrant entrant)
        {
            bool isFree = entrant.EducationFee == "Free";

            entrant.SpecialityId = findSpecialityId(entrant.SpecialityName, isFree);
            _entrantsContext.Entry(entrant).State = System.Data.Entity.EntityState.Modified;
            _entrantsContext.SaveChanges();
        }
Exemplo n.º 21
0
        public AHPUser(Entrant entrantGiven, List <EducationLine> educationLinesGiven)
        {
            _entrant        = entrantGiven;
            _educationLines = educationLinesGiven;
            _settings       = new AHPUserSettings();

            CalculateAll();
        }
Exemplo n.º 22
0
 public static void AssignAttributes(this Entrant destination, Entrant source)
 {
     destination.DisplayName = source.DisplayName;
     destination.Time        = source.Time;
     destination.State       = source.State;
     destination.Place       = source.Place;
     destination.Race        = source.Race;
 }
Exemplo n.º 23
0
        public override void AddOrUpdate_Add_Duplicate_Keeps_Collection_Count_Before_Save()
        {
            Entrant entrant = RandomLocalEntrant;
            int     cntRace = entrant.Race.Entrants.Count;

            _context.AddOrUpdate(entrant);

            Assert.AreEqual(cntRace, entrant.Race.Entrants.Count);
        }
Exemplo n.º 24
0
        public override void AddOrUpdate_Add_Increases_Total_Count_Before_Save()
        {
            int     entrantCount = _context.Entrants.Local.Count;
            Entrant entrant      = GenerateEntrant(RandomLocalRace);

            _context.AddOrUpdate(entrant);

            Assert.AreEqual(entrantCount + 1, _context.Entrants.Local.Count);
        }
Exemplo n.º 25
0
        public void AddEntrant(Entrant entrant)
        {
            Entrant line = selectedCollection.Where(e => e.EntrantID == entrant.EntrantID).FirstOrDefault();

            if (line == null)
            {
                selectedCollection.Add(entrant);
            }
        }
Exemplo n.º 26
0
 public AhpUser(int userId)
 {
     _entrant = _context.Entrants.Find(userId);
     foreach (var edLineInDb in _context.EducationLines)
     {
         _educationLines.Add(edLineInDb);
     }
     _settings = new AhpUserSettings();
 }
        protected override IOptimizationRule GetRule()
        {
            var args = Arguments.ToList();

            var entrant1 = new Entrant(args[0], args[1]);
            var entrant2 = new Entrant(args[2], args[3]);

            return(new PriorityUnMatchupRule(entrant1, entrant2));
        }
Exemplo n.º 28
0
        void Add()
        {
            var address = new Address()
            {
                Country = Session.DataModel.Countries.FirstOrDefault()
            };

            var entrant = new Entrant()
            {
                Address = address,
                Gender  = Session.DataModel.Genders.First()
            };

            var ord = new OtherRequiredDocument
            {
                Fluorography       = false,
                Certificate        = false,
                Photos             = false,
                MedicinePermission = false
            };

            var identityDocument = new IdentityDocument();

            var claim = new Claim()
            {
                RegistrationDate  = DateTime.Now,
                IsHostelNeed      = false,
                PersonalReturning = true,
                ClaimStatus       = Session.DataModel.ClaimStatuses.FirstOrDefault()
            };

            claim.Entrants.Add(entrant);
            claim.OtherRequiredDocuments.Add(ord);
            claim.IdentityDocuments.Add(identityDocument);

            Session.DataModel.OtherRequiredDocuments.Add(ord);
            Session.DataModel.Addresses.Add(address);
            Session.DataModel.Entrants.Add(entrant);
            Session.DataModel.IdentityDocuments.Add(identityDocument);
            Session.DataModel.Claims.Add(claim);

            var vm = new ClaimEditorViewModel(claim);

            var validator = new ClaimValidator(claim);

            if (DialogLayer.ShowEditor(EditingContent.ClaimEditor, vm, validator))
            {
                Session.DataModel.SaveChanges();
                RaisePropertyChanged("ClaimList");
            }
            else
            {
                Session.DataModel.Claims.Remove(claim);
                Session.DataModel.SaveChanges();
            }
        }
Exemplo n.º 29
0
        //public static TestRun Map(ulong eventId, int ordinal, ulong testRunId, TestRunSaveModel test)
        //{
        //    var run = new TestRun(testRunId, eventId, ordinal, test.TimeInMS, test.EntrantId, test.Created, 0);
        //    run.SetPenalties(test.Penalties.Select(a => new Penalty(a.PenaltyType, a.InstanceCount)).ToArray());
        //    return run;
        //}

        public static Entrant Map(ulong entrantId, ulong eventId, EntrantSaveModel entrant, string email)
        {
            var e = new Entrant(entrantId, entrant.DriverNumber, entrant.GivenName, entrant.FamilyName, email, entrant.Class, eventId,
                                entrant.IsPaid, entrant.Club, entrant.ClubNumber, entrant.Age);

            e.SetVehicle(Map(entrant.Vehicle));
            e.SetEmergencyContact(Map(entrant.EmergencyContact));
            e.SetMsaMembership(Map(entrant.MsaMembership));
            return(e);
        }
        public void RemoveEntrant(Entrant entrant)
        {
            var removingEntrant = _entrantsContext.Entrants.FirstOrDefault(x => x.EntrantId == entrant.EntrantId);

            if (removingEntrant != null)
            {
                _entrantsContext.Entrants.Remove(removingEntrant);
                _entrantsContext.SaveChanges();
            }
        }