public string Add(User entity) { try { var newEntity = new User() { Name = entity.Name, Email = entity.Email, Phone = entity.Phone, Address = entity.Address, Password = CustomCrypto.Hash(DefaultValue.UserPassword), IsEmailVerified = true, ActivationCode = Guid.NewGuid(), UserRole = Role.Company }; _companyUnitOfWork.ComapanyRepository.Add(newEntity); _companyUnitOfWork.Save(); return(newEntity.Id); } catch (Exception ex) { Console.WriteLine(ex); return(string.Empty); } }
public string NewGame(string hashedPlayerId) { try { CustomCrypto hashing = new CustomCrypto(); int playerId = Convert.ToInt32(hashing.Decrypt(hashedPlayerId)); GameDAL gdal = new GameDAL(); int gameId = gdal.AddGame(playerId); var hashed_gameId = hashing.Encrypt(gameId.ToString()); // Wait for other players to join WaitForPlayers(30, gameId); var game = gdal.GetGame(gameId); // check if game room is full if (game.Player1 != null && game.Player2 != null && game.Player3 != null && game.Player4 != null) { return(hashed_gameId.ToString()); } AbortGame(hashed_gameId); throw new CustomException("Timeout. Players insufficient."); } catch (CustomException e) { throw new CustomException(e.Message); } catch (Exception e) { logger.Error(e); throw new Exception("Oops! Some error occured."); } }
public List <UserModel> GetAllUsers() { try { CustomCrypto hashing = new CustomCrypto(); UserDAL u_dal = new UserDAL(); var users = u_dal.GetAllUsers(); List <UserModel> userModel = new List <UserModel>(); foreach (var u in users) { userModel.Add(new UserModel { UserName = u.Username, EmailId = u.EmailId, Wins = u.Wins, Draws = u.Draws, Losses = u.Losses, Points = u.Points }); } return(userModel); } catch (CustomException e) { throw new CustomException(e.Message); } catch (Exception e) { logger.Error(e); throw new Exception("Oops! Some error occured."); } }
public bool ResetUserPassword(User user) { try { var existUser = _userUnitOfWork.UserRepository.Get(x => x.ResetPasswordCode == user.ResetPasswordCode).FirstOrDefault(); if (existUser != null) { existUser.Password = CustomCrypto.Hash(user.Password); existUser.ResetPasswordCode = ""; _userUnitOfWork.UserRepository.Update(existUser); return(_userUnitOfWork.Save()); } else { return(false); } } catch (Exception ex) { Console.WriteLine(ex); return(false); } return(true); }
public async Task <JsonResult> RegisterUser(ReqRegisterUser request) { var findExistingEmail = await _userRepository.GetUser(request.Email); if (findExistingEmail == null) { var user = new User { Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, VerificationCode = ObjectId.GenerateNewId().ToString(), IsOnline = true, Password = CustomCrypto.HashSha256(request.Password) }; await _userRepository.CreateSync(user); return(Json(new JsonGenericResult { IsSuccess = true, Message = user.Id.ToString() })); } return(Json(new JsonGenericResult { IsSuccess = false, Message = "Email with the same user already exists." })); }
public bool Registration(User user) { try { var newUser = new User() { Name = user.Name, Email = user.Email, Phone = user.Phone, Password = CustomCrypto.Hash(user.Password), IsEmailVerified = true, ActivationCode = Guid.NewGuid(), UserRole = Role.NormalUser }; _userUnitOfWork.UserRepository.Add(newUser); //Send Email to User //CustomEmail.SendVerificationLinkEmail(newUser.Email, newUser.ActivationCode.ToString(), DefaultValue.EmailTypes.VerifyAccount); var isSaved = _userUnitOfWork.Save(); return(isSaved); } catch (Exception ex) { Console.WriteLine(ex); return(false); } }
public void Add(IDataBaseVariables variable) { //TODO CustomCrypto crypto = new CustomCrypto(); variable.ConnectionString = crypto.Encrypt(variable.ConnectionString); _dbContext.VariableCollection.InsertOne(variable); }
public UserController(UserRepository userRepository, SettingsRepository settingsRepository, ILogger <UserController> logger, CustomCrypto crypto) { UserRepository = userRepository; SettingsRepository = settingsRepository; _logger = logger; _crypto = crypto; }
public Player(int userId, string username) { Stash = new List <Card>(); PassOrSelect = true; Hand = new List <Card>(); CardsToPass = new List <Card>(); UserId = new CustomCrypto().Encrypt(Convert.ToString(userId)); UserName = username; }
public List <GameModel> GetAllWaitingGames() { try { GameDAL gdal = new GameDAL(); UserDAL udal = new UserDAL(); CustomCrypto hashing = new CustomCrypto(); var games = gdal.GetAllWaitingGames(); List <GameModel> waiting_game = new List <GameModel>(); foreach (var game in games) { var new_game = new GameModel { //GameId = game.GameId, GameURL = hashing.Encrypt(game.GameId.ToString()), Status = game.Status, EndTime = game.EndTime, StartTime = game.StartTime }; User player; if (game.Player1 != null) { player = udal.GetUserById(game.Player1.Value); new_game.Player1 = new Player(player.UserId, player.Username); } if (game.Player2 != null) { player = udal.GetUserById(game.Player2.Value); new_game.Player2 = new Player(player.UserId, player.Username); } if (game.Player3 != null) { player = udal.GetUserById(game.Player3.Value); new_game.Player3 = new Player(player.UserId, player.Username); } if (game.Player4 != null) { player = udal.GetUserById(game.Player4.Value); new_game.Player4 = new Player(player.UserId, player.Username); } waiting_game.Add(new_game); } return(waiting_game); } catch (CustomException e) { throw new CustomException(e.Message); } catch (Exception e) { logger.Error(e); throw new Exception("Oops! Some error occured."); } }
public BasicAuthenticationMiddleware( RequestDelegate next, IOptions <BasicAuthenticationOptions> options, ILoggerFactory loggerFactory, UrlEncoder encoder, UserRepository userRepository, CustomCrypto crypto) : base(next, options, loggerFactory, encoder) { _userRepository = userRepository; _crypto = crypto; }
public override bool ValidateUser(string username, string password) { var container = new Container(); container.Options.DefaultScopedLifestyle = new WebRequestLifestyle(); container.Verify(); var userRepository = container.GetInstance <UserRepository>(); var user = Task.Run(() => userRepository.GetUser(username)).Result; if (user != null) { return(user.Password == CustomCrypto.HashSha256(password)); } return(false); }
public bool AbortGame(string hashedgameId) { try { GameDAL gdal = new GameDAL(); CustomCrypto unhash = new CustomCrypto(); int gameId = Convert.ToInt32(unhash.Decrypt(hashedgameId)); return(gdal.AbortGame(gameId)); } catch (CustomException e) { throw new CustomException(e.Message); } catch (Exception e) { logger.Error(e); throw new Exception("Oops! Some error occured."); } }
public User IsAuthenticatedUser(LoginUserModel model) { try { var user = _userService.GetByEmail(model.Email); if (user != null) { if (!user.IsEmailVerified) { executeMessage = "Please verify your email first"; return(null); } if (String.Compare(CustomCrypto.Hash(model.Password), user.Password) == 0) { CustomFormsAuthentication.Login(user, model.RememberMe); executeMessage = ""; return(user); } else { executeMessage = "Invalid user email or password"; return(null); } } else { executeMessage = "Invalid user email or password"; return(null); } } catch (Exception ex) { Console.WriteLine(ex); executeMessage = ex.Message; return(null); } }
public UserModel GetUserById(string hashedUserId) { try { CustomCrypto hashing = new CustomCrypto(); UserDAL udal = new UserDAL(); var userId = Convert.ToInt32(hashing.Decrypt(hashedUserId)); var user = udal.GetUserById(userId); string activeGameId = ""; if (user.ActiveGameId != null) { activeGameId = hashing.Encrypt(user.ActiveGameId.ToString()); } return(new UserModel { UserId = hashing.Encrypt(user.UserId.ToString()), UserName = user.Username, EmailId = user.EmailId, Wins = user.Wins, Draws = user.Draws, Losses = user.Losses, ActiveGameId = activeGameId, LastModifiedTime = user.LastModifiedTime, Points = user.Points }); } catch (CustomException e) { throw new CustomException(e.Message); } catch (Exception e) { logger.Error(e); throw new Exception("Oops! Some error occured."); } }
public async Task <JsonResult> LoginRegister(ReqRegisterUser request) { User user; user = await _userRepository.GetUser(request.Email); if (user == null) { user = new User { Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, VerificationCode = ObjectId.GenerateNewId().ToString(), IsOnline = true, Password = CustomCrypto.HashSha256("MyPassword1239!3") }; await _userRepository.CreateSync(user); } var isUserValid = Membership.ValidateUser(user.Email, "MyPassword1239!3"); if (isUserValid) { FormsAuthentication.SetAuthCookie(user.Email, true); return(Json(new JsonGenericResult { IsSuccess = true }, JsonRequestBehavior.AllowGet)); } return(Json(new JsonGenericResult { IsSuccess = true, Message = user.Id.ToString() })); }
public bool Add(User user) { try { var newUser = new User() { Name = user.Name, Email = user.Email, Password = CustomCrypto.Hash(user.Password), IsEmailVerified = true, // Should be false ActivationCode = Guid.NewGuid(), UserRoleId = user.UserRoleId }; _userUnitOfWork.UserRepository.Add(newUser); //Send Email to User //CustomEmail.SendVerificationLinkEmail(newUser.Email, newUser.ActivationCode.ToString()); var isSaved = _userUnitOfWork.Save(); //--------Save with Patient--------- if (newUser.UserRoleId == (int)CustomEnum.UserType.Patient) { var newPatient = new Patient() { UserId = newUser.Id }; _patientService.Add(newPatient); } return(isSaved); } catch (Exception ex) { Console.WriteLine(ex); return(false); } }
// Display the properties of the specified CustomCrypto object to the // console. public static void DisplayProperties(CustomCrypto customCrypto) { try { // Retrieve the class description for the customCrypto object. string classDescription = customCrypto.ToString(); Console.WriteLine(classDescription); Console.Write("KeyExchangeAlgorithm: "); Console.WriteLine(customCrypto.KeyExchangeAlgorithm); Console.Write("SignatureAlgorithm: "); Console.WriteLine(customCrypto.SignatureAlgorithm); Console.WriteLine("KeySize: " + customCrypto.KeySize); Console.WriteLine("Parameters described in Xml format:"); Console.WriteLine(customCrypto.ToXmlString(true)); // Display the MinSize, MaxSize, and SkipSize properties of // each KeySize item in the local keySizes member variable. KeySizes[] legalKeySizes = customCrypto.LegalKeySizes; if (legalKeySizes.Length > 0) { for (int i=0; i < legalKeySizes.Length; i++) { Console.Write("Keysize" + i + " min, max, step: "); Console.Write(legalKeySizes[i].MinSize + ", "); Console.Write(legalKeySizes[i].MaxSize + ", "); Console.WriteLine(legalKeySizes[i].SkipSize + ", "); } } } catch (Exception ex) { Console.WriteLine("Caught unexpected exception: " + ex.ToString()); } }
static void Main(string[] args) { // Construct a CustomCrypto object and initialize its // CspParameters. CustomCrypto customCrypto = new CustomCrypto(); customCrypto.InitializeParameters(); // Display properties of the current customCrypto object. Console.WriteLine("*** CustomCrypto created with default " + "parameters:"); DisplayProperties(customCrypto); // Release all the resources used by this instance of // CustomCrytpo. customCrypto.Clear(); customCrypto = new CustomCrypto(64); // Create new parameters and set them by using the FromXmlString // method. string parameterXml = "<CustomCryptoKeyValue>"; parameterXml += "<ProviderName>Contoso</ProviderName>"; parameterXml += "<KeyContainerName>SecurityBin2"; parameterXml += "</KeyContainerName>"; parameterXml += "<KeyNumber>1</KeyNumber>"; parameterXml += "<ProviderType>2</ProviderType>"; parameterXml += "</CustomCryptoKeyValue>"; customCrypto.FromXmlString(parameterXml); // Display the properties of a customCrypto object created with // custom parameters. Console.WriteLine("\n*** " + "CustomCrypto created with custom parameters:"); DisplayProperties(customCrypto); // Create an object by using the assembly name. try { CustomCrypto myCryptoA = CustomCrypto.Create("CustomCrypto"); if (myCryptoA != null) { Console.Write("\n*** " + "Successfully created CustomCrytpo from"); Console.WriteLine(" the Create method."); DisplayProperties(myCryptoA); } else { Console.Write("Unable to create CustomCrytpo from "); Console.WriteLine(" the Create method."); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine("This sample completed successfully; " + "press Enter to exit."); Console.ReadLine(); }
public GameModel MakeMove(GameModel gameModel, string hashedUserId) { try { GameDAL gdal = new GameDAL(); UserDAL udal = new UserDAL(); CustomCrypto unhash = new CustomCrypto(); var g = unhash.Decrypt(gameModel.GameURL); int gameId = Convert.ToInt32(g); int userId = Convert.ToInt32(unhash.Decrypt(hashedUserId)); var game = gdal.GetGame(gameId); var user = udal.GetUserById(userId); if (user.ActiveGameId != game.GameId) { throw new CustomException("You are not a part of this game."); } //set cards in hand List <Card> cardsInHand = null; if (game.Player1.Value == userId) { cardsInHand = ConvertStringtoListCard(game.Player1Hand, game.Player1.Value); } else if (game.Player2.Value == userId) { cardsInHand = ConvertStringtoListCard(game.Player2Hand, game.Player2.Value); } else if (game.Player3.Value == userId) { cardsInHand = ConvertStringtoListCard(game.Player3Hand, game.Player3.Value); } else if (game.Player4.Value == userId) { cardsInHand = ConvertStringtoListCard(game.Player4Hand, game.Player4.Value); } string stash = ""; // check pass the trash if (game.PassOrPlay == 1) { if ((game.Player1 == userId && game.Player1Trash != null && game.Player1Trash.Length > 1) || (game.Player2 == userId && game.Player2Trash != null && game.Player2Trash.Length > 1) || (game.Player3 == userId && game.Player3Trash != null && game.Player3Trash.Length > 1) || (game.Player4 == userId && game.Player4Trash != null && game.Player4Trash.Length > 1)) { throw new CustomException("You have already passed the trash. Wait for the game to begin."); } if (gameModel.CardsToPass.FindAll(x => x.IsSlected).Count != 3) { throw new CustomException("Select only THREE cards to pass."); } if (gameModel.CardsToPass.FirstOrDefault(x => x.IsSlected && x.Suit == Suit.Clubs && x.Value == Value.Two) != null) { throw new CustomException("You can not pass Two of Clubs."); } //check valid card foreach (var item in gameModel.CardsToPass) { if (item.IsSlected) { if (item.Suit == Suit.Clubs && item.Value == Value.Two) { throw new CustomException(String.Format("{0} You cannot pass this : ", item.Name)); } if (cardsInHand.Find(x => x.Suit == item.Suit && x.Value == item.Value) == null) { throw new CustomException(String.Format("{0} Invalid card. You do not hve this card in your hand", item.Name)); } else { cardsInHand.RemoveAll(x => x.Suit == item.Suit && x.Value == item.Value); } } } } //check card to play else if (game.PassOrPlay == 2) { if (game.Turn != userId) { throw new CustomException("It it not your turn."); } if (gameModel.CardSelectedString == null || gameModel.CardSelectedString.Length < 3) { throw new CustomException("You did not select a card to play."); } gameModel.CardSelected = new Card(); gameModel.CardSelected.ConvertStringToCard(gameModel.CardSelectedString); if (cardsInHand.Find(x => x.Suit == gameModel.CardSelected.Suit && x.Value == gameModel.CardSelected.Value) == null) { throw new CustomException(String.Format("{0} Invalid card. You do not hve this card in your hand", gameModel.CardSelected.Name)); } //check if card is a valid move if (game.LeadingSuit != null) { //if player doesnt play leading suit if ((int)gameModel.CardSelected.Suit != game.LeadingSuit.Value) { //check if cardsinHand have leading suit if (cardsInHand.FirstOrDefault(x => x.Suit == (Suit)game.LeadingSuit) != null) { throw new CustomException("Play the leading suit."); } } // else play any suit, card is accepted if (gameModel.CardSelected.Suit == Suit.Hearts) { game.HeartsPlayed = true; } if (gameModel.CardSelected.Suit == Suit.Spades) { game.SpadesPlayed = true; } } else { if (cardsInHand.Count == 13) { if (!(gameModel.CardSelected.Suit == Suit.Clubs && gameModel.CardSelected.Value == Value.Two)) { throw new CustomException("First Card to the first trick is Two of Clubs"); } } if (game.HeartsPlayed == false && gameModel.CardSelected.Suit == Suit.Hearts) { throw new CustomException("You cannot play Hearts as a leading suit, untill Hearts are broken."); } if (game.SpadesPlayed == false && gameModel.CardSelected.Suit == Suit.Spades) { throw new CustomException("You cannot play Spades as a leading suit, untill Spades are broken."); } //update leading suit game.LeadingSuit = (int)gameModel.CardSelected.Suit; } //remove selected card from hand cardsInHand.RemoveAll(x => x.Suit == gameModel.CardSelected.Suit && x.Value == gameModel.CardSelected.Value); //save selected card & update the turn & update stash if (game.Player1 == userId) { game.Player1Card = gameModel.CardSelected.Value + "-" + gameModel.CardSelected.Suit; game.Turn = game.Player2; } else if (game.Player2 == userId) { game.Player2Card = gameModel.CardSelected.Value + "-" + gameModel.CardSelected.Suit; game.Turn = game.Player3; } else if (game.Player3 == userId) { game.Player3Card = gameModel.CardSelected.Value + "-" + gameModel.CardSelected.Suit; game.Turn = game.Player4; } else if (game.Player4 == userId) { game.Player4Card = gameModel.CardSelected.Value + "-" + gameModel.CardSelected.Suit; game.Turn = game.Player1; } //if all players played, update scores if (game.Player1Card != null && game.Player2Card != null && game.Player3Card != null && game.Player4Card != null) { if (game.Player1Card.Length > 0 && game.Player2Card.Length > 0 && game.Player3Card.Length > 0 && game.Player4Card.Length > 0) { //get all cards playeds Card player1Card = new Card(); player1Card.ConvertStringToCard(game.Player1Card); Card player2Card = new Card(); player2Card.ConvertStringToCard(game.Player2Card); Card player3Card = new Card(); player3Card.ConvertStringToCard(game.Player3Card); Card player4Card = new Card(); player4Card.ConvertStringToCard(game.Player4Card); //calculate points int totalPoints = player1Card.Points + player2Card.Points + player3Card.Points + player4Card.Points; //calculate the stash stash = "," + game.Player1Card + "," + game.Player2Card + "," + game.Player3Card + "," + game.Player4Card; //find winner, set next turn and update points Value maxValue = Value.Two; if (player1Card.Suit == (Suit)game.LeadingSuit && player1Card.Value >= maxValue) { maxValue = player1Card.Value; game.Turn = game.Player1.Value; } if (player2Card.Suit == (Suit)game.LeadingSuit && player2Card.Value >= maxValue) { maxValue = player2Card.Value; game.Turn = game.Player2.Value; } if (player3Card.Suit == (Suit)game.LeadingSuit && player3Card.Value >= maxValue) { maxValue = player3Card.Value; game.Turn = game.Player3.Value; } if (player4Card.Suit == (Suit)game.LeadingSuit && player4Card.Value >= maxValue) { maxValue = player4Card.Value; game.Turn = game.Player4.Value; } if (game.Turn == game.Player1) { game.Player1Score += totalPoints; game.Player1Stash += stash; } else if (game.Turn == game.Player2) { game.Player2Score += totalPoints; game.Player2Stash += stash; } else if (game.Turn == game.Player3) { game.Player3Score += totalPoints; game.Player3Stash += stash; } else if (game.Turn == game.Player4) { game.Player4Score += totalPoints; game.Player4Stash += stash; } //clear leading suit and PlayerCards game.LeadingSuit = null; game.Player1Card = null; game.Player2Card = null; game.Player3Card = null; game.Player4Card = null; } } } //update cards in hand if (game.PassOrPlay == 1 || game.PassOrPlay == 2) { string newHand = ""; foreach (var card in cardsInHand) { newHand = newHand + "," + card.Value + "-" + card.Suit; } if (game.Player1.Value == userId) { game.Player1Hand = newHand; } else if (game.Player2.Value == userId) { game.Player2Hand = newHand; } else if (game.Player3.Value == userId) { game.Player3Hand = newHand; } else if (game.Player4.Value == userId) { game.Player4Hand = newHand; } if (game.PassOrPlay == 1) // pass the trass { foreach (var card in gameModel.CardsToPass) { if (card.IsSlected) { if (game.Player1.Value == userId) { game.Player1Trash = game.Player1Trash + "," + card.Value + "-" + card.Suit; } else if (game.Player2.Value == userId) { game.Player2Trash = game.Player2Trash + "," + card.Value + "-" + card.Suit; } else if (game.Player3.Value == userId) { game.Player3Trash = game.Player3Trash + "," + card.Value + "-" + card.Suit; } else if (game.Player4.Value == userId) { game.Player4Trash = game.Player4Trash + "," + card.Value + "-" + card.Suit; } } } } gdal.UpdateGameAfterMove(game, userId); string winner = null; // if PassOrPlay == 2 && all cards of all the players are over // call Inititalize round function if (game.PassOrPlay == 2) // play { if (game.Player1Hand.Length == 0 && game.Player2Hand.Length == 0 && game.Player1Hand.Length == 0 && game.Player1Hand.Length == 0) { if (game.GameRound == 4) { winner = UpdateScores(gameModel); } InitializeRound(game.GameId); } } var returnModel = GetGame(gameModel.GameURL, hashedUserId); returnModel.Winner = winner; return(returnModel); } return(null); } catch (CustomException e) { throw new CustomException(e.Message); } catch (Exception e) { logger.Error(e); throw new Exception("Oops! Some error occured."); } }
protected override void Seed(Medicine.Repository.Context.MedicineDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. // user context.Users.AddOrUpdate(x => x.Email, new User() { Name = "Admin", Email = "*****@*****.**", Password = CustomCrypto.Hash(DefaultValue.UserPassword), IsEmailVerified = true, UserRole = Role.Admin } ); // comapny context.Users.AddOrUpdate(x => x.Email, new User() { Name = "Square Limited", Email = "*****@*****.**", Address = "Dhaka", Password = CustomCrypto.Hash(DefaultValue.UserPassword), IsEmailVerified = true, UserRole = Role.Company }, new User() { Name = "Beximco Limited", Email = "*****@*****.**", Address = "Dhaka", Password = CustomCrypto.Hash(DefaultValue.UserPassword), IsEmailVerified = true, UserRole = Role.Company }, new User() { Name = "Pharmaceutical Limited", Email = "*****@*****.**", Address = "Dhaka", Password = CustomCrypto.Hash(DefaultValue.UserPassword), IsEmailVerified = true, UserRole = Role.Company } ); // pharmacy context.Users.AddOrUpdate(x => x.Email, new User() { Name = "Ronoda Pharmacy", Email = "*****@*****.**", Address = "Dhaka", Password = CustomCrypto.Hash(DefaultValue.UserPassword), IsEmailVerified = true, UserRole = Role.Pharmacy } ); }
public BasicAuthenticationHandler(UserRepository userRepository, CustomCrypto crypto) { _userRepository = userRepository; _crypto = crypto; }
public GameModel GetGame(string hashedGameId, string hashedUserId) { try { GameDAL gdal = new GameDAL(); UserDAL udal = new UserDAL(); CustomCrypto unhash = new CustomCrypto(); var g = unhash.Decrypt(hashedGameId); int gameId = Convert.ToInt32(g); int userId = Convert.ToInt32(unhash.Decrypt(hashedUserId)); var game = gdal.GetGame(gameId); var user = udal.GetUserById(userId); if (game.Player1.Value != user.UserId && game.Player2.Value != user.UserId && game.Player3.Value != user.UserId && game.Player4.Value != user.UserId) { throw new CustomException("You cannot access this game currently. Join or create another game."); } if (game.Status == (int)GameStatus.Aborted || game.Status == (int)GameStatus.Ended) { throw new CustomException("Game has either aborted or ended."); } //resume a started or waiting game GameModel gameModel = new GameModel { GameURL = unhash.Encrypt(game.GameId.ToString()), Status = game.Status, EndTime = game.EndTime, StartTime = game.StartTime }; User player; if (game.Player1 != null) { player = udal.GetUserById(game.Player1.Value); gameModel.Player1 = new Player(player.UserId, player.Username); } if (game.Player2 != null) { player = udal.GetUserById(game.Player2.Value); gameModel.Player2 = new Player(player.UserId, player.Username); } if (game.Player3 != null) { player = udal.GetUserById(game.Player3.Value); gameModel.Player3 = new Player(player.UserId, player.Username); } if (game.Player4 != null) { player = udal.GetUserById(game.Player4.Value); gameModel.Player4 = new Player(player.UserId, player.Username); } //return game status to player resuming the game if (game.Status == (int)GameStatus.Started) { if (game.GameRound != null) { gameModel.GameRound = game.GameRound.Value; } if (game.PassOrPlay != null) { gameModel.PassOrPlay = game.PassOrPlay.Value; } if (game.Turn != null) { gameModel.PlayerTurn = game.Turn.Value; } gameModel.CurrentTurn = udal.GetUserById(gameModel.PlayerTurn).Username; gameModel.HeartsPlayed = game.HeartsPlayed; gameModel.SpadesPlayed = game.SpadesPlayed; if (game.LeadingSuit != null) { gameModel.Trick = new MoveModel(); gameModel.Trick.LeadingSuit = (Suit)(game.LeadingSuit.Value); if (game.Player1Card != null) { gameModel.Trick.Card1 = new Card(); gameModel.Trick.Card1.ConvertStringToCard(game.Player1Card); } if (game.Player2Card != null) { gameModel.Trick.Card2 = new Card(); gameModel.Trick.Card2.ConvertStringToCard(game.Player2Card); } if (game.Player3Card != null) { gameModel.Trick.Card3 = new Card(); gameModel.Trick.Card3.ConvertStringToCard(game.Player3Card); } if (game.Player4Card != null) { gameModel.Trick.Card4 = new Card(); gameModel.Trick.Card4.ConvertStringToCard(game.Player4Card); } } gameModel.SpadesPlayed = game.SpadesPlayed; gameModel.HeartsPlayed = game.HeartsPlayed; if (game.Player1 == userId) { gameModel.Player1.Hand = ConvertStringtoListCard(game.Player1Hand, game.Player1.Value); } else if (game.Player2 == userId) { gameModel.Player2.Hand = ConvertStringtoListCard(game.Player2Hand, game.Player2.Value); } else if (game.Player3 == userId) { gameModel.Player3.Hand = ConvertStringtoListCard(game.Player3Hand, game.Player3.Value); } else if (game.Player4 == userId) { gameModel.Player4.Hand = ConvertStringtoListCard(game.Player4Hand, game.Player4.Value); } gameModel.Player1.Stash = ConvertStringtoListCard(game.Player1Stash, game.Player1.Value); gameModel.Player2.Stash = ConvertStringtoListCard(game.Player2Stash, game.Player2.Value); gameModel.Player3.Stash = ConvertStringtoListCard(game.Player3Stash, game.Player3.Value); gameModel.Player4.Stash = ConvertStringtoListCard(game.Player4Stash, game.Player4.Value); gameModel.Player1.PreviousRoundPoint = game.Player1Score; gameModel.Player2.PreviousRoundPoint = game.Player2Score; gameModel.Player3.PreviousRoundPoint = game.Player3Score; gameModel.Player4.PreviousRoundPoint = game.Player4Score; } return(gameModel); } catch (CustomException e) { throw new CustomException(e.Message); } catch (Exception e) { logger.Error(e); throw new Exception("Oops! Some error occured."); } }
public string JoinGame(string hashedGameId, string hashedPlayerid) { try { GameDAL gdal = new GameDAL(); UserDAL udal = new UserDAL(); CustomCrypto hashing = new CustomCrypto(); int gameId = Convert.ToInt32(hashing.Decrypt(hashedGameId)); int playerid = Convert.ToInt32(hashing.Decrypt(hashedPlayerid)); Game game = gdal.GetGame(gameId); User user = udal.GetUserById(playerid); if (playerid == game.Player1 || playerid == game.Player2 || playerid == game.Player3 || playerid == game.Player4) { //user is already part of the game return(hashing.Encrypt(game.GameId.ToString())); } //user is already part of ANOTHER the game if (user.ActiveGameId != null) { throw new CustomException("You are already a part of another game."); } if (game.Player1 != null && game.Player2 != null && game.Player3 != null && game.Player4 != null) { throw new CustomException("Game room is full."); } int time = 0; if (game.Player1 == null) { game.Player1 = playerid; var secondsElapsed = (DateTime.Now).Subtract(game.StartTime).Seconds; time = 30 - secondsElapsed; } else if (game.Player2 == null) { game.Player2 = playerid; var secondsElapsed = (DateTime.Now).Subtract(game.StartTime).Seconds; time = 30 - secondsElapsed; } else if (game.Player3 == null) { game.Player3 = playerid; var secondsElapsed = (DateTime.Now).Subtract(game.StartTime).Seconds; time = 30 - secondsElapsed; } else if (game.Player4 == null) { game.Player4 = playerid; var secondsElapsed = (DateTime.Now).Subtract(game.StartTime).Seconds; time = 30 - secondsElapsed; } var new_game = gdal.AddPlayer(playerid, game.GameId); udal.UpdateActiveGame(playerid, new_game.GameId); // check if game room is full if (game.Player1 != null && game.Player2 != null && game.Player3 != null && game.Player4 != null) { InitializeGame(game.GameId); WaitForPlayers(time, new_game.GameId); return(hashing.Encrypt(new_game.GameId.ToString())); } WaitForPlayers(time, new_game.GameId); game = gdal.GetGame(game.GameId); if (game.Status != (int)GameStatus.Started) { AbortGame(hashedGameId); throw new CustomException("Timeout. Players insufficient."); } else { return(hashing.Encrypt(new_game.GameId.ToString())); } } catch (CustomException e) { throw new CustomException(e.Message); } catch (Exception e) { logger.Error(e); throw new Exception("Oops! Some error occured."); } }