//Refresh the live game table
 private void RefreshLiveGameTable(string Player1, string Player2)
 {
     using (var cdb = new minesweeper_RonOzeritskyEntities())
     {
         try
         {
             LiveGame liveGame = new LiveGame
             {
                 Serial      = LiveGamesCounterAdd(),
                 Player1Name = Player1,
                 Player2Name = Player2,
                 GameStarted = GetCurrentDateTime()
             };
             cdb.LiveGames.Add(liveGame);
             cdb.Entry(liveGame).State = System.Data.Entity.EntityState.Added;
             cdb.SaveChanges();
         }
         catch (Exception)
         {
             UserFaultException fault = new UserFaultException()
             {
                 Message = "Server error."
             };
             throw new FaultException <UserFaultException>(fault);
         }
     }
 }
        //Delete client from the DB
        public void DeleteClient(string userName, string password)
        {
            Boolean userPassFlag = false;
            Client  remClient    = new Client
            {
                Name     = userName,
                Password = password
            };

            using (var cdb = new minesweeper_RonOzeritskyEntities())
            {
                try
                {
                    var remFriend = cdb.Clients.Where(o => o.Name == remClient.Name &&
                                                      o.Password == remClient.Password).FirstOrDefault();
                    if (remFriend != null)
                    {
                        userPassFlag = true;
                        cdb.Clients.Remove(remFriend);
                        cdb.SaveChanges();
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Password is incorrect"
                    };
                    throw new FaultException <UserFaultException>(fault);
                }
                try
                {
                    if (userPassFlag)
                    {
                        clients.Remove(remClient.Name);
                        Thread updateThread = new Thread(UpdateClientsLists);
                        updateThread.Start();
                    }
                    else
                    {
                        throw new Exception();  //Unknown error reached.
                    }
                }
                catch (Exception)
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Something went wrong, try again."
                    };
                    throw new FaultException <UserFaultException>(fault);
                }
            }
        }
        // MineService C'tor.
        public MineService()
        {
            liveGames        = new List <GameMatch>();
            clients          = new SortedDictionary <string, IMineServiceCallback>();
            playingClients   = new List <string>();
            liveGamesCounter = 0;
            //set gamesCounter.
            using (var cdb = new minesweeper_RonOzeritskyEntities())
            {
                try
                {
                    var gameCount = (from g in cdb.Games
                                     select g).Count();
                    gamesCounter = gameCount;
                }
                catch
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Some error in DataBase while openning server."
                    };
                    throw new FaultException <UserFaultException>(fault, new FaultReason(fault.Message));
                }
            }

            //Clean LiveGames table.
            using (var cdb = new minesweeper_RonOzeritskyEntities())
            {
                try
                {
                    var liveGame = (from g in cdb.LiveGames
                                    select g);
                    cdb.LiveGames.RemoveRange(liveGame);
                    cdb.SaveChanges();
                }
                catch
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Some error in DataBase while openning server."
                    };
                    throw new FaultException <UserFaultException>(fault);
                }
            }
        }
 // The player has finished playing
 public void PlayerFinishedPlaying(string playerName, string opponent)
 {
     using (var cdb = new minesweeper_RonOzeritskyEntities())
     {
         try
         {
             LiveGame endedGame = (from g in cdb.LiveGames
                                   where g.Player1Name == playerName || g.Player2Name == playerName
                                   select g).SingleOrDefault();
             if (endedGame != null)
             {
                 cdb.LiveGames.Remove(endedGame);
                 cdb.Entry(endedGame).State = System.Data.Entity.EntityState.Deleted;
                 cdb.SaveChanges();
             }
         }
         catch (Exception)
         {
             UserFaultException fault = new UserFaultException()
             {
                 Message = "Server error."
             };
             throw new FaultException <UserFaultException>(fault);
         }
     }
     if (playingClients.Contains(playerName))
     {
         playingClients.Remove(playerName);
         playingClients.Remove(opponent);
         UpdateClientsLists();
         GameMatch match = liveGames.Find(g => g.playerYellow == playerName);
         if (match == null)
         {
             match = liveGames.Find(g => g.playerBlue == playerName);
         }
         LiveGamesCounterReduce();
         if (match != null)
         {
             liveGames.Remove(match);
         }
         Thread gameExit = new Thread(() => clients[opponent].GameExit(playerName));
         gameExit.Start();
     }
 }
        //change the clients password
        public void ChangeClientPassword(string userName, string oldPassword, string newPassword)
        {
            Client passClient = new Client
            {
                Name     = userName,
                Password = oldPassword
            };

            using (var cdb = new minesweeper_RonOzeritskyEntities())
            {
                try
                {
                    if (!IsValidPassword(newPassword))
                    {
                        throw new Exception();
                    }
                    var passChange = (from c in cdb.Clients
                                      where c.Name == passClient.Name && c.Password == passClient.Password
                                      select c).FirstOrDefault();
                    if (passChange == null)
                    {
                        throw new Exception();
                    }
                    else
                    {
                        passChange.Password = newPassword;
                    }
                    cdb.SaveChanges();
                }
                catch (Exception)
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Password change failed"
                    };
                    throw new FaultException <UserFaultException>(fault);
                }
            }
        }
        //Registration

        public void Register(string userName, string password)
        {
            Boolean userExistFlag = true;
            Client  newClient     = new Client
            {
                Name     = userName,
                Password = password
            };

            try
            {
                if (!IsValidName(newClient.Name))
                {
                    throw new Exception();
                }
            }
            catch
            {
                UserFaultException fault = new UserFaultException()
                {
                    Message = "Usernamme should be at least 3 charecters long and contain only numbers and digits"
                };
                throw new FaultException <UserFaultException>(fault, new FaultReason(fault.Message));;
            }
            try
            {
                if (!IsValidPassword(newClient.Password))
                {
                    throw new Exception();
                }
            }
            catch
            {
                UserFaultException fault = new UserFaultException()
                {
                    Message = "Password should be at least 6 charecters long and contain only numbers and digits"
                };
                throw new FaultException <UserFaultException>(fault);
            }
            using (var cdb = new minesweeper_RonOzeritskyEntities())
            {
                try
                {
                    if (cdb.Clients.Any(o => o.Name == newClient.Name))
                    {
                        throw new Exception();
                    }
                    else
                    {
                        userExistFlag = false;
                    }
                }
                catch (Exception)
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Usernamme is taken"
                    };
                    throw new FaultException <UserFaultException>(fault, new FaultReason(fault.Message));
                }
                try
                {
                    if (!userExistFlag)
                    {
                        cdb.Clients.Add(newClient);
                        cdb.SaveChanges();
                    }
                    else
                    {
                        throw new Exception();  //Unknown error reached.
                    }
                }
                catch (Exception)
                {
                    //error adding new user to database.
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Something went wrong, try again."
                    };
                    throw new FaultException <UserFaultException>(fault, new FaultReason(fault.Message));
                }
            }
        }
        //Update the DB after game ends
        private void EndGameDBUpdate(string winner, string loser, bool isTie)
        {
            //Remove game from Livegames table.
            using (var cdb = new minesweeper_RonOzeritskyEntities())
            {
                try
                {
                    LiveGame endedGame = (from g in cdb.LiveGames
                                          where g.Player1Name == winner || g.Player2Name == winner
                                          select g).SingleOrDefault();
                    if (endedGame != null)
                    {
                        cdb.LiveGames.Remove(endedGame);
                        cdb.Entry(endedGame).State = System.Data.Entity.EntityState.Deleted;
                        cdb.SaveChanges();
                    }
                }
                catch (Exception)
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Server error."
                    };
                    throw new FaultException <UserFaultException>(fault);
                }
            }
            //Add game to Games table.
            using (var cdb = new minesweeper_RonOzeritskyEntities())
            {
                try
                {
                    Game game = new Game
                    {
                        Serial    = gamesCounter,
                        Winner    = winner,
                        Loser     = loser,
                        Tie       = isTie,
                        GameEnded = GetCurrentDateTime()
                    };
                    cdb.Games.Add(game);
                    cdb.Entry(game).State = System.Data.Entity.EntityState.Added;
                    cdb.SaveChanges();
                }
                catch (Exception)
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Server error."
                    };
                    throw new FaultException <UserFaultException>(fault);
                }
            }
            //Update Clients table properties.
            using (var cdb = new minesweeper_RonOzeritskyEntities())
            {
                try
                {
                    if (!isTie)
                    {
                        Client Winner = (from w in cdb.Clients
                                         where w.Name == winner
                                         select w).SingleOrDefault();
                        Winner.GamesPlayed++;
                        Winner.Points++;
                        Winner.GamesWon++;

                        Client Loser = (from l in cdb.Clients
                                        where l.Name == loser
                                        select l).SingleOrDefault();
                        Loser.GamesPlayed++;
                        Loser.GamesLost++;



                        cdb.Entry(Winner).State = System.Data.Entity.EntityState.Modified;
                        cdb.Entry(Loser).State  = System.Data.Entity.EntityState.Modified;
                        cdb.SaveChanges();
                    }
                    else //its Tie
                    {
                        Client Winner = (from w in cdb.Clients
                                         where w.Name == winner
                                         select w).SingleOrDefault();
                        Winner.GamesPlayed++;
                        Winner.GamesTie++;

                        Client Loser = (from l in cdb.Clients
                                        where l.Name == loser
                                        select l).SingleOrDefault();
                        Loser.GamesPlayed++;
                        Loser.GamesTie++;

                        cdb.Entry(Winner).State = System.Data.Entity.EntityState.Modified;
                        cdb.Entry(Loser).State  = System.Data.Entity.EntityState.Modified;
                        cdb.SaveChanges();
                    }
                }
                catch (Exception)
                {
                    UserFaultException fault = new UserFaultException()
                    {
                        Message = "Server error."
                    };
                    throw new FaultException <UserFaultException>(fault);
                }
            }
        }