Ejemplo n.º 1
0
 public ActionResult Index()
 {
     using (TournamentContext db = new TournamentContext())
     {
         return(View(db.TournamentModels.ToList()));
     }
 }
Ejemplo n.º 2
0
        private static void SeedData(TournamentContext context)
        {
            var t1 = new Tournament()
            {
                Id        = Guid.NewGuid(),
                Name      = "Test-Tournament",
                StartDate = DateTime.Now.Date,
                EndDate   = DateTime.Now.Date.AddDays(3),
            };

            var p1 = new Player()
            {
                Id           = Guid.NewGuid(),
                Name         = "Player 1",
                Firstname    = "Player",
                Lastname     = "One",
                TournamentId = t1.Id
            };

            var p2 = new Player()
            {
                Id           = Guid.NewGuid(),
                Name         = "Player 2",
                Firstname    = "Player",
                Lastname     = "Two",
                TournamentId = t1.Id
            };

            context.Tournaments.Add(t1);
            context.SaveChanges();

            context.Players.AddRange(p1, p2);
            context.SaveChanges();
        }
        protected RepositoryTestBase()
        {
            var options = new DbContextOptionsBuilder <TournamentContext>()
                          .UseInMemoryDatabase(databaseName: "TournamentRepositoryTest")
                          .Options;

            Context = new TournamentContext(options);
            Context.EnsureSeed();
        }
Ejemplo n.º 4
0
        // DELETE: api/Tournament/5
        public void Delete(int id)
        {
            using (var context = new TournamentContext())
            {
                var tournament = context.Tournaments.FirstOrDefault(t => t.ID == id);

                context.Tournaments.Remove(tournament);
                context.SaveChanges();
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Get Active Tournaments
 /// </summary>
 /// <returns></returns>
 public IEnumerable <TournamentResponse> Get()
 {
     using (var context = new TournamentContext())
     {
         return(context.Tournaments.Where(t => t.Active).Select(t => new TournamentResponse()
         {
             Active = t.Active, ID = t.ID, Title = t.Title
         }).ToList());
     }
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Get Tournament By ID
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public TournamentResponse Get(int id)
 {
     using (var context = new TournamentContext())
     {
         return(context.Tournaments.Where(t => t.ID == id).Select(t => new TournamentResponse()
         {
             Active = t.Active, ID = t.ID, Title = t.Title, Matches = t.Matches.ToList()
         }).FirstOrDefault());
     }
 }
Ejemplo n.º 7
0
 public static void EnsureDataSeeding(TournamentContext context)
 {
     if (context.Tournaments.Any())
     {
         Console.WriteLine("Already found tournaments in the database");
     }
     else
     {
         SeedData(context);
     }
 }
Ejemplo n.º 8
0
        public static List <Knight> SelectAllKnights()
        {
            List <Knight>     knights = new List <Knight>();
            TournamentContext context = new TournamentContext();

            foreach (Knight tournament in context.Knight)
            {
                knights.Add(tournament);
            }

            return(knights);
        }
Ejemplo n.º 9
0
        public static List <Tournament> SelectAllTournaments()
        {
            List <Tournament> tournaments = new List <Tournament>();
            TournamentContext context     = new TournamentContext();

            foreach (Tournament tournament in context.Tournament)
            {
                tournaments.Add(tournament);
            }

            return(tournaments);
        }
Ejemplo n.º 10
0
        internal static List <Knight> SelectKnightsHaveAMount()
        {
            List <Knight>     knights = new List <Knight>();
            TournamentContext context = new TournamentContext();

            //  var CougarsAnimalsCount = context.Animals.Where((a) => a.Specie.SpecieName == "Cougars blancs")
            foreach (Knight tournament in context.Knight.Where((knight) => knight.Mount == true))
            {
                knights.Add(tournament);
            }

            return(knights);
        }
Ejemplo n.º 11
0
 public ActionResult LoggedIn()
 {
     using (TournamentContext db = new TournamentContext())
     {
         if (Session["PersonId"] != null)
         {
             return(View(db.Tournamets.ToList()));
         }
         else
         {
             return(RedirectToAction("Login"));
         }
     }
 }
Ejemplo n.º 12
0
 public ActionResult Register(PersonModel Account)
 {
     if (ModelState.IsValid)
     {
         using (TournamentContext db = new TournamentContext())
         {
             db.TournamentModels.Add(Account);
             db.SaveChanges();
         }
         ModelState.Clear();
         ViewBag.Message = Account.FirstName + " " + Account.LastName + " succesful register.";
     }
     return(View());
 }
        public Output Process(IMessage input, IMessageContext model)
        {
            var cmd       = input as DeleteTournamentCommand;
            var ctx_model = model as DeleteTournamentCommandContextModel;

            if (ctx_model.Tournament_existing)
            {
                var tournament_context = new TournamentContext(cmd.Id, nameof(TournamentContext));
                var ev = new TournamentDeleted(nameof(TournamentDeleted), tournament_context, new TournamentDeleteData()
                {
                    Id = cmd.Id
                });
                return(new CommandOutput(new Success(), new Event[] { ev }));
            }

            return(new CommandOutput(new Failure("Turnier existiert nicht")));
        }
Ejemplo n.º 14
0
 public ActionResult Login(PersonModel user)
 {
     using (TournamentContext db = new TournamentContext())
     {
         var usr = db.TournamentModels.Where(u => u.NickName == user.NickName && u.Password == user.Password).FirstOrDefault();
         if (usr != null)
         {
             Session["PersonId"] = usr.PersonId.ToString();
             Session["NickName"] = usr.NickName.ToString();
             return(RedirectToAction("LoggedIn"));
         }
         else
         {
             ModelState.AddModelError("", "Username or Password is not correct");
         }
     }
     return(View());
 }
Ejemplo n.º 15
0
        // POST: api/Tournament
        public void Post(TournamentRequest request)
        {
            var tournament = new Tournament();

            tournament.Active  = true;
            tournament.Title   = request.Title;
            tournament.Matches = new List <Match>();

            if (request.Competitors == 2)
            {
                CreateBrackets(1, tournament.Matches);
            }
            else if (request.Competitors <= 4)
            {
                CreateBrackets(2, tournament.Matches);
            }
            else if (request.Competitors <= 8)
            {
                CreateBrackets(3, tournament.Matches);
            }
            else if (request.Competitors <= 16)
            {
                CreateBrackets(4, tournament.Matches);
            }
            else if (request.Competitors <= 32)
            {
                CreateBrackets(5, tournament.Matches);
            }
            else if (request.Competitors <= 64)
            {
                CreateBrackets(6, tournament.Matches);
            }
            else
            {
                throw new Exception("Too many competitors");
            }

            using (var context = new TournamentContext())
            {
                context.Tournaments.Add(tournament);
                context.SaveChanges();
            }
        }
Ejemplo n.º 16
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new TournamentContext(
                       serviceProvider.GetRequiredService <DbContextOptions <TournamentContext> >()))
            {
                // Look for any tournaments
                if (context.Tournaments.Any())
                {
                    return;// Data was already seeded
                }

                context.Tournaments.AddRange(
                    new Tournament
                {
                    Id           = 1,
                    Name         = "Squash Grand Prix 1",
                    CreationDate = DateTime.Now,
                    StartDate    = DateTime.Today,
                    Draws        = new List <Draw>(),
                    Players      = new List <Player>()
                    {
                        new ()
                        {
                            Id   = 15,
                            Name = "Peter Revsbech",
                        }
                        ,
                        new ()
                        {
                            Id   = 16,
                            Name = "Simon Steenholdt",
                        }
                        ,
                        new ()
                        {
                            Id   = 17,
                            Name = "Sebastian Brinker",
                        }
                    }
                }
Ejemplo n.º 17
0
        public MainWindow()
        {
            InitializeComponent();

            TournamentContext db      = new TournamentContext();
            ICategoryManager  manager = new CategoryManager(db);
            var list = manager.GetCategories();
            int a    = 10;


            /* IPageManager pageManager = new PageManager();
             * OpenFileDialog openFileDialog = new OpenFileDialog();
             * openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
             *
             * if (openFileDialog.ShowDialog() == true)
             * {
             *   var res =  pageManager.ImportFromExcel(openFileDialog.FileName);
             *
             *
             * }
             */
        }
Ejemplo n.º 18
0
 public TournamentsUsersRepository(TournamentContext context) : base(context)
 {
 }
Ejemplo n.º 19
0
 /// <summary>
 /// create manager fow work with category
 /// </summary>
 /// <param name="dataBase">Database context</param>
 public CategoryManager(TournamentContext dataBase)
 {
     db           = dataBase;
     categoryRepo = new  EFGenericRepository <DAL.Entities.Category>(db);;
 }
Ejemplo n.º 20
0
 public EFGenericRepository(TournamentContext context)
 {
     _context = context;
     _dbSet   = context.Set <TEntity>();
 }
Ejemplo n.º 21
0
 public PlayerRepository(TournamentContext context)
 {
     _tournamentContext = context;
     _dbSet             = _tournamentContext.Set <Player>();
 }
Ejemplo n.º 22
0
 public PlayerRepository(TournamentContext context)
 {
     tournamentContext = context;
     table             = context.Set <Player>();
 }
Ejemplo n.º 23
0
 public PlayerController(TournamentContext context)
 {
     _context = context;
 }
Ejemplo n.º 24
0
        public static void EnsureSeed(this TournamentContext dataContext)
        {
            dataContext.Database.EnsureCreated();
            //using (var transaction = dataContext.Database.BeginTransaction())
            //{

            var tournament = new TournamentDto()
            {
                Id             = 1,
                Caption        = "New Tournament",
                Description    = "First added tournament",
                StartDate      = DateTime.Now,
                EndDate        = DateTime.Now.AddDays(3),
                TournamentTime = 20
            };
            var tournament2 = new TournamentDto()
            {
                Id             = 2,
                Caption        = "Old Tournament",
                Description    = "First added tournament",
                StartDate      = DateTime.Now,
                EndDate        = DateTime.Now.AddDays(3),
                TournamentTime = 20
            };

            if (!dataContext.Tournaments.Any())
            {
                dataContext.Tournaments.Add(tournament);
                dataContext.Tournaments.Add(tournament2);
                //dataContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Tournaments ON");
                dataContext.SaveChanges();
                //dataContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Tournaments OFF");
            }

            if (!dataContext.TournamentsUsers.Any())
            {
                dataContext.TournamentsUsers.Add(new TournamentsUsers()
                {
                    Tournament = tournament,
                    UserId     = "5e7398bde6ab1940182c5cfd"
                });
                dataContext.SaveChanges();
            }

            if (!dataContext.Exercises.Any())
            {
                dataContext.Exercises.AddRange(
                    new ExerciseDto()
                {
                    Id          = 1,
                    Text        = "1+1",
                    Answer      = "2",
                    OrderNumber = 1,
                    Tournament  = tournament
                }, new ExerciseDto()
                {
                    Id          = 2,
                    Text        = "3+5",
                    Answer      = "8",
                    OrderNumber = 2,
                    Tournament  = tournament
                }, new ExerciseDto()
                {
                    Id          = 3,
                    Text        = "First three letters of alphabet",
                    Answer      = "a,b,c",
                    OrderNumber = 3,
                    Tournament  = tournament
                }, new ExerciseDto()
                {
                    Id          = 4,
                    Text        = "First three letters of alphabet",
                    Answer      = "a,b,c",
                    OrderNumber = 3,
                    Tournament  = tournament2
                });
                //dataContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Exercises ON");
                dataContext.SaveChanges();
                //dataContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Exercises OFF");
            }

            if (!dataContext.ExercisesUsers.Any())
            {
                dataContext.ExercisesUsers.AddRange(
                    new ExercisesUsers()
                {
                    ExerciseId = 1,
                    UserId     = "5e7398bde6ab1940182c5cfd",
                    UserAnswer = "2",
                    IsCorrect  = true
                });
                dataContext.SaveChanges();
            }
            dataContext.SaveChanges();
            //    transaction.Commit();
            //}
        }
Ejemplo n.º 25
0
        public static void SeedData(this TournamentContext dataContext)
        {
            dataContext.Database.EnsureCreated();


            var tournament = new TournamentDto()
            {
                Caption        = "New Tournament",
                Description    = "First added tournament",
                StartDate      = DateTime.Now,
                EndDate        = DateTime.Now.AddDays(3),
                TournamentTime = 20
            };
            var tournament2 = new TournamentDto()
            {
                Caption        = "Old Tournament",
                Description    = "First added tournament",
                StartDate      = DateTime.Now,
                EndDate        = DateTime.Now.AddDays(3),
                TournamentTime = 20
            };

            if (!dataContext.Tournaments.Any())
            {
                dataContext.Tournaments.Add(tournament);
                dataContext.Tournaments.Add(tournament2);
                dataContext.SaveChanges();
            }

            if (!dataContext.TournamentsUsers.Any())
            {
                dataContext.TournamentsUsers.Add(new TournamentsUsers()
                {
                    Tournament = tournament,
                    UserId     = "5e7398bde6ab1940182c5cfd"
                });
                dataContext.SaveChanges();
            }

            if (!dataContext.Exercises.Any())
            {
                dataContext.Exercises.AddRange(
                    new ExerciseDto()
                {
                    Text        = "1+1",
                    Answer      = "2",
                    OrderNumber = 1,
                    Tournament  = tournament
                }, new ExerciseDto()
                {
                    Text        = "3+5",
                    Answer      = "8",
                    OrderNumber = 2,
                    Tournament  = tournament
                }, new ExerciseDto()
                {
                    Text        = "First three letters of alphabet",
                    Answer      = "a,b,c",
                    OrderNumber = 3,
                    Tournament  = tournament
                }, new ExerciseDto()
                {
                    Text        = "First three letters of alphabet",
                    Answer      = "a,b,c",
                    OrderNumber = 3,
                    Tournament  = tournament2
                });
                dataContext.SaveChanges();
            }

            if (!dataContext.ExercisesUsers.Any())
            {
                dataContext.ExercisesUsers.AddRange(
                    new ExercisesUsers()
                {
                    ExerciseId = 1,
                    UserId     = "5e7398bde6ab1940182c5cfd",
                    UserAnswer = "2",
                    IsCorrect  = true
                });
                dataContext.SaveChanges();
            }
            dataContext.SaveChanges();
        }
Ejemplo n.º 26
0
 public ScoresController(TournamentContext context)
 {
     _context = context;
 }
Ejemplo n.º 27
0
 public static void EnsureDatabaseMigration(TournamentContext context)
 {
     context.Database.Migrate();
 }
Ejemplo n.º 28
0
 public MatchesController(TournamentContext context)
 {
     _context = context;
 }
Ejemplo n.º 29
0
 public Repository(TournamentContext context)
 {
     TContext = context;
     table    = context.Set <T>();
 }
Ejemplo n.º 30
0
        public MainViewModel()
        {
            CurrentScreen = ScreenType.ApiKey;

            //Observable.Start(() =>
            //{
            //    try
            //    {
            //        //I'm considering doing an http request to smashboards to find if a new version is released. I think smashboard's anti-DDOS protection is preventing it from working
            //        WebRequest request = WebRequest.Create(ThreadUrl);
            //        request.Credentials = CredentialCache.DefaultCredentials;

            //        WebResponse response = request.GetResponse();
            //        if (((HttpWebResponse)response).StatusDescription == "OK")
            //        {
            //            Stream dataStream = response.GetResponseStream();
            //            StreamReader reader = new StreamReader(dataStream);
            //            string responseFromServer = reader.ReadToEnd();
            //            reader.Close();
            //        }
            //        response.Close();
            //    }
            //    catch { /* ignore */ }
            //});

            //Modify ViewModel state when an action is initiated
            Action startAction = () =>
            {
                ErrorMessage = null;
                IsBusy       = true;
            };

            //Modify ViewModel state when an action is completed
            Action endAction = () =>
            {
                IsBusy = false;
            };

            //Modify ViewModel state when an action comes back with an exception
            Action <Exception> errorHandler = ex =>
            {
                if (ex.InnerException is ChallongeApiException)
                {
                    var cApiEx = (ChallongeApiException)ex.InnerException;

                    if (cApiEx.Errors != null)
                    {
                        ErrorMessage = cApiEx.Errors.Aggregate((one, two) => one + "\r\n" + two);
                    }
                    else
                    {
                        ErrorMessage = string.Format("Error with ResponseStatus \"{0}\" and StatusCode \"{1}\". {2}", cApiEx.RestResponse.ResponseStatus,
                                                     cApiEx.RestResponse.StatusCode, cApiEx.RestResponse.ErrorMessage);
                    }
                }
                else
                {
                    ErrorMessage = ex.NewLineDelimitedMessages();
                }

                IsBusy = false;
            };

            var dispatcher = System.Threading.SynchronizationContext.Current;

            //Handle next button press
            NextCommand = Command.CreateAsync(() => true, () =>
            {
                switch (CurrentScreen)
                {
                case ScreenType.ApiKey:
                    var subdomain = string.IsNullOrWhiteSpace(Subdomain) ? null : Subdomain;
                    Portal        = new ChallongePortal(ApiKey, subdomain);

                    //Load list of tournaments that match apikey/subdomain
                    TournamentCollection = Portal.GetTournaments().OrderByDescending(t => t.CreatedAt).ToArray();

                    try
                    {
                        //This is a silly method for checking whether a new application version exists without me having my own website.
                        //I manage the most recent version number in the description of a tournament hosted on challonge. This code fetches that number
                        var versionCheckPortal = new ChallongePortal(ApiKey, "fizzitestorg");
                        MostRecentVersion      = versionCheckPortal.GetTournaments().Where(t => t.Name == "CMDVersionTest").Select(t =>
                        {
                            //Modifying the description seems to put some html formatting into the result. This filters the description for
                            //just the version number by itself
                            var versionResult = string.Concat(t.Description.Where(c => char.IsDigit(c) || c == '.'));
                            return(versionResult);
                        }).First();

                        //Check both version numbers to determine if current version is older than recent version
                        var versionCompareResult = Version.Split('.').Zip(MostRecentVersion.Split('.'), (v, mrv) =>
                        {
                            return(int.Parse(v).CompareTo(int.Parse(mrv)));
                        }).FirstOrDefault(i => i != 0);

                        //If app version is older than most recent version, show message
                        IsVersionOutdatedVisible = versionCompareResult < 0;
                    }
                    catch (Exception)
                    {
                        //If version check fails simply ignore the problem and move on
                        System.Diagnostics.Debug.WriteLine("Version check failed.");
                    }

                    break;

                case ScreenType.TournamentSelection:
                    if (Context != null)
                    {
                        Context.Dispose();
                    }
                    if (matchesChangedHandler != null)
                    {
                        Context.Tournament.PropertyChanged -= matchesChangedHandler;
                    }

                    //Create tournament context from selected tournament
                    Context = new TournamentContext(Portal, SelectedTournament.Id);
                    Context.StartSynchronization(TimeSpan.FromMilliseconds(500), 6);

                    //Create TO View Model
                    OrgViewModel = new OrganizerViewModel(this, dispatcher);

                    //Load up matches into display matches. This is done to allow ordering of assigned matches over unassigned matches without having to refresh the view
                    DisplayMatches = Context.Tournament.Matches.Select(kvp => new DisplayMatch(OrgViewModel, kvp.Value, DisplayMatch.DisplayType.Assigned))
                                     .Concat(Context.Tournament.Matches.Select(kvp => new DisplayMatch(OrgViewModel, kvp.Value, DisplayMatch.DisplayType.Unassigned))).ToList();

                    //This handler is used to keep matches display matches in sync with tournament context matches. If the matches in the context change, re-generate the display matches
                    matchesChangedHandler = new PropertyChangedEventHandler((sender, e) =>
                    {
                        if (e.PropertyName == "Matches")
                        {
                            if (Context.Tournament.Matches == null)
                            {
                                DisplayMatches = null;
                            }
                            else
                            {
                                DisplayMatches = Context.Tournament.Matches.Select(kvp => new DisplayMatch(OrgViewModel, kvp.Value, DisplayMatch.DisplayType.Assigned))
                                                 .Concat(Context.Tournament.Matches.Select(kvp => new DisplayMatch(OrgViewModel, kvp.Value, DisplayMatch.DisplayType.Unassigned))).ToList();
                            }
                        }
                    });
                    Context.Tournament.PropertyChanged += matchesChangedHandler;

                    break;
                }

                CurrentScreen = (ScreenType)((int)CurrentScreen + 1);
            }, startAction, endAction, errorHandler);

            Back = Command.CreateAsync(() => true, () =>
            {
                switch (CurrentScreen)
                {
                case ScreenType.TournamentSelection:
                    ApiKey = null;
                    break;

                case ScreenType.PendingMatchView:
                    if (OrgViewModel != null)
                    {
                        OrgViewModel.Dispose();
                        OrgViewModel = null;
                    }
                    break;
                }
                CurrentScreen = (ScreenType)((int)CurrentScreen - 1);
            }, startAction, endAction, errorHandler);

            IgnoreVersionNotification = Command.Create(() => true, () => IsVersionOutdatedVisible = false);
        }