Example #1
0
        /// <summary>
        /// This method allows a user's account to be pulled and updated.
        /// Note: passwords are not included in the information that is pulled
        /// </summary>
        /// <param name="userID">This is the ID of the user in ClueLess whose account if being pulled</param>
        /// <returns>This return the user's account information</returns>
        public static Account GetAccount(int userID)
        {
            Account userAccount = new Account();

            try
            {
                //Step 1. Connect to the database
                ClueLessContext db = new ClueLessContext();
                //Step 2. Pull the user by the ID
                User user = db.Users.Where(x => x.ID == userID).FirstOrDefault();
                //Step 3. "Map" the user information to the account information\
                userAccount = new Account
                {
                    FirstName       = user.FirstName,
                    LastName        = user.LastName,
                    Email           = user.EmailAddress,
                    Avatar          = user.Avatar,
                    UserName        = user.Username,
                    IsAdministrator = user.IsAdminsitrator,
                    Password        = user.Password
                };

                //Step 4. Return the account
                return(userAccount);
            }catch (Exception e)
            {
                Console.WriteLine(e.Message + "/n" + e.StackTrace);
                return(userAccount);
            }
        }
Example #2
0
 public static List <Actions> GetMoveOptions()
 {
     using (ClueLessContext db = new ClueLessContext())
     {
         return(db.Actions.ToList());
     }
 }
Example #3
0
        public void Save()
        {
            using (ClueLessContext db = new ClueLessContext())
            {
                Database.DataModels.Suggestion suggestion = new Database.DataModels.Suggestion
                {
                    LocationID            = LocationID,
                    PlayerID              = playerID,
                    ConfiguredCharacterID = characterID,
                    ConfiguredWeaponID    = weaponID,
                    IsAccusation          = IsAccusastion
                };
                db.Suggestions.Add(suggestion);

                db.SaveChanges();

                //set the player to be the current responding player
                Database.DataModels.Player author = db.Players.Where(x => x.ID == suggestion.PlayerID).FirstOrDefault();
                author.IsCurrentRespondingPlayer = true;
                db.SaveChanges();

                int firstResponderID = FindNextResponder(suggestion.ID);
                Database.DataModels.Player firstResponder = db.Players.Where(x => x.ID == firstResponderID).FirstOrDefault();
                firstResponder.IsCurrentRespondingPlayer = true;
                author.IsCurrentRespondingPlayer         = false;
                db.SaveChanges();
            }
        }
Example #4
0
 public static void ChangeGameStatus(int gameID, Database.DataModels.Status status)
 {
     using (ClueLessContext db = new ClueLessContext())
     {
         Database.DataModels.Game game = db.Games.Where(x => x.ID == gameID).FirstOrDefault();
         game.Status = status;
         db.SaveChanges();
     }
 }
Example #5
0
 public static void MoveCharacter(int playerID, int locationID)
 {
     using (ClueLessContext db = new ClueLessContext())
     {
         Database.DataModels.Player playerToBeMoved = db.Players.Where(x => x.ID == playerID).FirstOrDefault();
         playerToBeMoved.PositionID = locationID;
         db.SaveChanges();
     }
 }
Example #6
0
        public Game()
        {
            Random rnd = new Random();

            ID   = rnd.Next(1, 100000);
            Name = "Game: " + ID.ToString();
            using (ClueLessContext db = new ClueLessContext())
            {
            }
        }
Example #7
0
        public List <Database.DataModels.Game> PullGameList()
        {
            List <Database.DataModels.Game> gameList = new List <Database.DataModels.Game>();

            using (ClueLessContext db = new ClueLessContext())
            {
                gameList = db.Games.ToList();
            }
            return(gameList);
        }
Example #8
0
        /// <summary>
        /// This method changes the user's password to thier new specified password, and
        /// sends them an email notification that thier password was changed.
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="newPassword"></param>
        public static void ResetPassword(int userID, string newPassword)
        {
            ClueLessContext db   = new ClueLessContext();
            User            user = db.Users.Where(x => x.ID == userID).FirstOrDefault();

            user.Password = newPassword;
            db.SaveChanges();

            Notification.SendEmail(NotificationType.PasswordReset, user.EmailAddress);
        }
Example #9
0
        public static List <LocationOption> GetLocationOptions(int gameID)
        {
            ClueLessContext db = new ClueLessContext();
            //get the game's configuration ID
            int configurationID             = db.Games.Where(x => x.ID == gameID).Select(x => x.ConfigurationID).FirstOrDefault();
            List <LocationOption> locations = new List <LocationOption>();
            List <LocationOption> position  = db.Positions.Where(x => x.ConfigurationID == configurationID).Select(x => new LocationOption {
                ID = x.ID, Location = x.Location.LocationName
            }).ToList();

            return(position);
        }
Example #10
0
        public bool ValidateAccusation()
        {
            bool isValid = false;

            try
            {
                using (ClueLessContext db = new ClueLessContext())
                {
                    //Get the datbase suggestion object
                    Database.DataModels.Suggestion suggestion = db.Suggestions.Where(x => x.ID == ID).FirstOrDefault();

                    //Get the gameID
                    int gameID = db.Players.Where(x => x.ID == suggestion.PlayerID).Select(x => x.GameID).FirstOrDefault();

                    //Pull the game's solution
                    Database.DataModels.GameSolution solution = db.GameSolutions.Where(x => x.GameID == gameID).FirstOrDefault();

                    if (solution.ConfiguredCharacterID == suggestion.ConfiguredCharacterID &&
                        solution.ConfiguredWeaponID == suggestion.ConfiguredWeaponID &&
                        solution.PositionID == suggestion.LocationID)
                    {
                        isValid = true;
                        //End the Game
                        solution.SolvedByPlayerID = suggestion.PlayerID;
                        db.SaveChanges();

                        Game.ChangeGameStatus(gameID, Database.DataModels.Status.Completed_Solved);
                    }
                    else
                    {
                        //determine the number of active players
                        int activePlayers = db.Players.Where(x => x.GameID == gameID && x.IsActive).Count();
                        if (activePlayers > 2)
                        {
                            //deactivate the player
                            Database.DataModels.Player player = db.Players.Where(x => x.ID == playerID).FirstOrDefault();
                            player.IsActive = false;
                            db.SaveChanges();
                        }
                        else
                        {
                            //end the game
                            Game.ChangeGameStatus(gameID, Database.DataModels.Status.Completed_Unsolved);
                        }
                    }
                }
            }catch (Exception e)
            {
                Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
            }
            return(isValid);
        }
Example #11
0
        public JsonResult CreateGame()
        {
            List <Database.DataModels.Game> gameList = new List <Database.DataModels.Game>();

            using (ClueLessContext db = new ClueLessContext())
            {
                var      g    = Models.Game.GetGameboard(8);
                string[] keys = Request.Form.AllKeys;

                gameList = db.Games.ToList();
                return(Json(new { success = g.Name }, JsonRequestBehavior.AllowGet));
            }
        }
Example #12
0
 public Game(int userID, int configurationID, string name)
 {
     using (ClueLessContext db = new ClueLessContext())
     {
         db.Games.Add(new Database.DataModels.Game
         {
             UserID          = userID,
             ConfigurationID = configurationID,
             Name            = name
         });
         db.SaveChanges();
     }
 }
Example #13
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion <ClueLessContext, MigrationConfiguration>());


            ClueLessContext db        = new ClueLessContext();
            var             gamecount = db.Games.Count();
        }
Example #14
0
        public static void SignalEndofTurn(int playerID)
        {
            using (ClueLessContext db = new ClueLessContext())
            {
                Database.DataModels.Player currentPlayer = db.Players.Where(x => x.ID == playerID).FirstOrDefault();
                int NextPlayerID = FindNextPlayer(currentPlayer.GameID);
                Database.DataModels.Player nextPlayer = db.Players.Where(x => x.ID == NextPlayerID).FirstOrDefault();

                currentPlayer.IsCurrentPlayer = false;
                nextPlayer.IsCurrentPlayer    = true;

                db.SaveChanges();
            }
        }
Example #15
0
        public bool DetermineAvailability(int locationID, int gameID)
        {
            bool isAvailable = true;

            using (ClueLessContext db = new ClueLessContext())
            {
                Position position     = db.Positions.Where(x => x.ID == locationID).FirstOrDefault();
                int      numOccupants = db.Players.Where(x => x.PositionID == locationID && x.GameID == gameID).Count();
                if (position.Location.LocationType == Database.DataModels.LocationType.Hallway && numOccupants > 0)
                {
                    isAvailable = false;
                }
            }

            return(isAvailable);
        }
Example #16
0
        public static int ValidateUser(string username, string password)
        {
            int userID = -1;

            using (ClueLessContext db = new ClueLessContext())
            {
                User user = db.Users.Where(x => x.Username.Equals(username) && x.Password.Equals(password)).FirstOrDefault();
                userID = user == null ? -1 : user.ID;
            }

            //if (userID > 0)
            //{
            //    HttpContext.Current.Session["userID"] = userID;
            //}
            return(userID);
        }
Example #17
0
        public void CreateAccount()
        {
            //Connect to the database
            AppDomain current    = AppDomain.CurrentDomain;
            var       appDataDir = Path.GetFullPath("../../../AppData");
            var       test       = current.GetData("DataDirectory");

            current.SetData("DataDirectory", appDataDir);

            Account testAccount = new Account
            {
                UserID          = 0,
                FirstName       = "Test",
                LastName        = "User",
                Email           = "*****@*****.**",
                UserName        = "******",
                Avatar          = "",
                IsAdministrator = false
            };

            Account.SetAccount(testAccount);
            ClueLessContext db       = new ClueLessContext();
            Account         TestSave = Account.GetAccount(db.Users.Max(x => x.ID));


            Assert.IsNotNull(TestSave, "Account was successfully saved");

            //Update the created accunt
            string oldAvatar = testAccount.Avatar;

            testAccount.Avatar = "IAmAwesome";

            Account.SetAccount(testAccount);

            //Get the updated account
            Account testAccountUpdate = Account.GetAccount(testAccount.UserID);

            Assert.AreNotEqual(oldAvatar, testAccount.Avatar);

            //Remove the account upon completion

            User testUser = db.Users.Where(x => x.ID == testAccount.UserID).FirstOrDefault();

            db.Users.Remove(testUser);
            db.SaveChanges();
        }
Example #18
0
        public static Clue RespondToSuggestion(int playerId, int suggestionID, int clueID = -1, string ClueType = "")
        {
            Clue responseClue = new Clue();
            SuggestionResponse response;
            ClueLessContext    db = new ClueLessContext();

            if (clueID > 0)
            {
                responseClue = RevealClue(playerId, clueID, ClueType, suggestionID);
                response     = new SuggestionResponse
                {
                    SuggestionID      = suggestionID,
                    Response          = "Revealed Clue",
                    RevealedClueID    = clueID,
                    RevealedClueTable = ClueType
                };
                db.SaveChanges();
            }
            else
            {
                response = new SuggestionResponse
                {
                    SuggestionID = suggestionID,
                    Response     = "Pass"
                };
                db.SaveChanges();

                Database.DataModels.Suggestion suggestion = db.Suggestions.Where(x => x.ID == suggestionID).FirstOrDefault();
                int nextPlayerID = FindNextResponder(suggestionID);
                Database.DataModels.Player currentResponder = db.Players.Where(x => x.ID == suggestion.PlayerID).FirstOrDefault();
                currentResponder.IsCurrentRespondingPlayer = false;
                db.SaveChanges();
                if (nextPlayerID != suggestion.PlayerID)
                {
                    Database.DataModels.Player nextResponder = db.Players.Where(x => x.ID == nextPlayerID).FirstOrDefault();
                    nextResponder.IsCurrentRespondingPlayer = true;
                    db.SaveChanges();
                }
            }

            return(responseClue);
        }
Example #19
0
        private static int FindNextPlayer(int gameID)
        {
            ClueLessContext db = new ClueLessContext();
            int             nextPlayerID;
            //Pull the list of all the players
            List <Database.DataModels.Player> players = db.Players.Where(x => x.GameID == gameID && x.IsActive == true).OrderBy(x => x.ID).ToList();

            //Get the index of the current player
            int currentIndex = players.IndexOf(players.Where(x => x.IsCurrentPlayer).FirstOrDefault());

            if (currentIndex == players.Count - 1)
            {
                nextPlayerID = players.ElementAt(0).ID;
            }
            else
            {
                nextPlayerID = players.ElementAt(currentIndex + 1).ID;
            }

            return(nextPlayerID);
        }
Example #20
0
        /// <summary>
        /// This methods allow for the creation and updating of the user's account
        /// on ClueLess with the exception of setting the password for the user
        /// </summary>
        /// <param name="updatedAccount">The account information for a user's account</param>
        public static void SetAccount(Account updatedAccount)
        {
            try
            {
                User useraccount = new User();
                //Step 1. Connect to the database
                ClueLessContext db = new ClueLessContext();
                //Step 2. Pull the user from the database based on the user's ID
                if (updatedAccount != null && updatedAccount.UserID > 0)
                {
                    useraccount = db.Users.Where(user => user.ID == updatedAccount.UserID).FirstOrDefault();
                }

                else //Step 3. If the user is null, create a new user
                {
                    useraccount = new User
                    {
                        FirstName       = updatedAccount.FirstName,
                        LastName        = updatedAccount.LastName,
                        EmailAddress    = updatedAccount.Email,
                        Username        = updatedAccount.UserName,
                        Avatar          = updatedAccount.Avatar == ""?updatedAccount.UserName:updatedAccount.Avatar,
                        IsAdminsitrator = updatedAccount.IsAdministrator,
                        Password        = "******"
                    };
                }

                //Step 4. Update the database user object from the UserObject
                db.Users.Add(useraccount);
                //Step 5. Save changes
                db.SaveChanges();
            }catch (Exception e)
            {
                Console.WriteLine(e.Message + "./n" + e.StackTrace);
            }
        }
Example #21
0
        private static int FindNextResponder(int suggestionID)
        {
            ClueLessContext db = new ClueLessContext();

            Database.DataModels.Suggestion suggestion = db.Suggestions.Where(x => x.ID == suggestionID).FirstOrDefault();
            Database.DataModels.Player     author     = db.Players.Where(x => x.ID == suggestion.PlayerID).FirstOrDefault();
            int nextPlayerID;
            //Pull the list of all the players
            List <Database.DataModels.Player> players = db.Players.Where(x => x.GameID == author.GameID).OrderBy(x => x.ID).ToList();

            //Get the index of the current player
            int currentIndex = players.IndexOf(players.Where(x => x.IsCurrentRespondingPlayer).FirstOrDefault());

            if (currentIndex == players.Count - 1)
            {
                nextPlayerID = players.ElementAt(0).ID;
            }
            else
            {
                nextPlayerID = players.ElementAt(currentIndex + 1).ID;
            }

            return(nextPlayerID);
        }
Example #22
0
        public static void CreateConfiguration()
        {
            //Connect to the database
            ClueLessContext db = new ClueLessContext();

            //Get the ID of the Default configurations
            Database.DataModels.Configuration config = db.Configurations.Where(x => x.Name == "Default").FirstOrDefault();


            string ConfigurationDownload = "Attachment; filename=ConfigurationTemplate.txt";

            ////Clear everything from the response object
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ClearContent();

            ////Populate the reponse object
            HttpContext.Current.Response.AddHeader("content-disposition", ConfigurationDownload);
            HttpContext.Current.Response.ContentType = "text/csv";
            HttpContext.Current.Response.AddHeader("Pragma", "public");

            var fileWriter = new StringBuilder();

            //Write out the Name and Share row indicators
            fileWriter.Append("Name:" + config.Name + Environment.NewLine);
            fileWriter.Append("Share with Public:" + (config.isShared == true?"Yes":"No") + Environment.NewLine);
            fileWriter.AppendLine();
            //Write out the "Headers for the locations:
            fileWriter.AppendLine("Location, Row, Column, Secret Door Connection");
            //Pull the information for the locations
            List <Position> locations = db.Positions.Where(x => x.ConfigurationID == config.ID && x.Location.LocationType == LocationType.Room).ToList();

            foreach (Position p in locations)
            {
                SecretPassages connectingPassage = db.SecretPassages.Where(x => x.PositionID_1 == p.ID || x.PositionID_2 == p.ID).FirstOrDefault();
                string         connectingRoom    = "";
                if (connectingPassage != null)
                {
                    if (connectingPassage.PositionID_1 == p.ID)
                    {
                        Position connectedPosition = db.Positions.Where(x => x.ID == connectingPassage.PositionID_2).FirstOrDefault();
                        connectingRoom = connectedPosition.Location.LocationName;
                    }
                    else
                    {
                        Position connectedPosition = db.Positions.Where(x => x.ID == connectingPassage.PositionID_1).FirstOrDefault();
                        connectingRoom = connectedPosition.Location.LocationName;
                    }
                }
                // connectingRoom = connectingPassage.PositionID_1 == p.ID ? connectingPassage.Room2.Location.LocationName : connectingPassage.Room1.Location.LocationName;

                fileWriter.AppendLine(p.Location.LocationName + "," + p.RowPosition + "," + p.ColumnPosition + "," + connectingRoom);
            }

            //Write out an empty line
            fileWriter.AppendLine();

            //Write out the "Headers" for the Characters
            fileWriter.AppendLine("Characters, Starting Position, Color(R:G:B)");
            //Pull the information for the characters
            List <Database.DataModels.CharacterConfiguration> characters = db.CharacterConfigurations.Where(x => x.ConfigurationID == config.ID).ToList();

            foreach (Database.DataModels.CharacterConfiguration c in characters)
            {
                Color characterColor = (Color)ColorTranslator.FromHtml("#" + c.Color);//Color.FromName(c.Color);
                fileWriter.AppendLine(c.Character.Name + "," + c.StartingPosition.Location.LocationName + "," + characterColor.R + ":" + characterColor.G + ":" + characterColor.B);
            }

            //Pull the information for the Weapons
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\wrigh\OneDrive\Documents\GraduateSchool\FoundationOfSoftwareEngineering\ConfigurationTest2.txt");
            file.WriteLine(fileWriter.ToString());

            file.Flush();
            file.Dispose();
            string text = fileWriter.ToString();

            HttpContext.Current.Response.BinaryWrite(Encoding.ASCII.GetBytes(fileWriter.ToString()));
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
Example #23
0
        public static bool SaveConfiguration(HttpPostedFile newConfiguration, int userID)
        {
            Database.DataModels.Configuration configuration = new Database.DataModels.Configuration();
            configuration.UserID = userID;

            Dictionary <String, String>         SecretRoomConnections = new Dictionary <string, string>();
            List <Database.DataModels.Location> locations             = new List <Database.DataModels.Location>();
            Dictionary <string, string>         positions             = new Dictionary <string, string>();
            List <PositionHelper> positionsList             = new List <PositionHelper>();
            List <Database.DataModels.Character> characters = new List <Database.DataModels.Character>();
            Dictionary <string, string>          characterConfigurationInfo = new Dictionary <string, string>();
            List <CharacterConfiguration>        characterConfiguration     = new List <CharacterConfiguration>();
            List <Database.DataModels.Weapon>    weapons = new List <Database.DataModels.Weapon>();


            //Check the extension
            string fileExtension = Path.GetExtension(newConfiguration.FileName);

            if (!fileExtension.Equals(".txt"))
            {
                return(false);
            }
            //Save the file to a temporary file
            String tempFolder = Path.GetTempPath();
            String filePath   = Path.Combine(tempFolder, newConfiguration.FileName);

            newConfiguration.SaveAs(filePath);
            StreamReader streamReader = new StreamReader(filePath);

            while (!streamReader.EndOfStream)
            {
                //Read a Line
                string line = streamReader.ReadLine();

                //Split the line
                string[] lineSplit = line.Split(',');

                if (lineSplit[0].Contains("Name:"))
                {
                    configuration.Name = lineSplit[0].Substring(lineSplit[0].IndexOf(":") + 1);
                }
                if (lineSplit[0].Contains("Share with Public:"))
                {
                    string answer = lineSplit[0].Substring(lineSplit[0].IndexOf(':') + 1);
                    configuration.isShared = answer.Trim().ToLower().Equals("yes")?true:false;
                }

                if (lineSplit[0].ToLower().Trim() == "location")
                {
                    for (int i = 0; i < 9; i++)
                    {
                        //Read the next line
                        line = streamReader.ReadLine();
                        if (line == "")
                        {
                            return(false);
                        }
                        lineSplit = line.Split(',');

                        //Create the location
                        Database.DataModels.Location newLocation = new Database.DataModels.Location();
                        newLocation.LocationName = lineSplit[0];
                        newLocation.LocationType = Database.DataModels.LocationType.Room;

                        locations.Add(newLocation);

                        //Create the Position
                        positions.Add(lineSplit[0], lineSplit[1] + "," + lineSplit[2]);
                        positionsList.Add(new PositionHelper {
                            Name = lineSplit[0], Row = Convert.ToInt32(lineSplit[1]), Column = Convert.ToInt32(lineSplit[2])
                        });

                        if (lineSplit[3] != "")
                        {
                            SecretRoomConnections.Add(newLocation.LocationName, lineSplit[3]);
                        }
                    }

                    //Create and save the location positions
                    PositionHelper pos1;
                    PositionHelper pos2;
                    string         locationName = "";
                    for (int i = 0; i <= 4; i++)
                    {
                        for (int j = 0; j <= 4; j += 2)
                        {
                            if (i % 2 == 0 && j < 4)
                            {
                                pos1         = positionsList.Where(x => x.Row == i && x.Column == j).FirstOrDefault();
                                pos2         = positionsList.Where(x => x.Row == i && x.Column == j + 2).FirstOrDefault();
                                locationName = pos1.Name + " to " + pos2.Name;
                                locations.Add(new Database.DataModels.Location
                                {
                                    LocationName = locationName,
                                    LocationType = LocationType.Hallway
                                });

                                PositionHelper hall = new PositionHelper
                                {
                                    Name   = locationName,
                                    Row    = i,
                                    Column = j
                                };

                                positionsList.Add(hall);
                            }
                            else if (i % 2 != 0)
                            {
                                pos1         = positionsList.Where(x => x.Row == i - 1 && x.Column == j).FirstOrDefault();
                                pos2         = positionsList.Where(x => x.Row == i + 1 && x.Column == j).FirstOrDefault();
                                locationName = pos1.Name + " to " + pos2.Name;
                                locations.Add(new Database.DataModels.Location
                                {
                                    LocationName = locationName,
                                    LocationType = LocationType.Hallway
                                });
                                PositionHelper hall = new PositionHelper
                                {
                                    Name   = locationName,
                                    Row    = i,
                                    Column = j
                                };
                                positionsList.Add(hall);
                            }
                        }
                    }

                    //Ensure that the number of secret room configurations is not more than 2
                    if (SecretRoomConnections.Count > 4)
                    {
                        return(false);
                    }
                }

                if (lineSplit[0].ToLower().Trim() == "characters")
                {
                    for (int i = 0; i < 6; i++)
                    {
                        //Read the next line
                        line = streamReader.ReadLine();
                        if (line == "")
                        {
                            return(false);
                        }
                        lineSplit = line.Split(',');

                        characters.Add(new Database.DataModels.Character {
                            Name = lineSplit[0]
                        });
                        characterConfigurationInfo.Add(lineSplit[0], lineSplit[1] + "," + lineSplit[2]);
                    }
                }

                if (lineSplit[0].Trim().ToLower() == "weapons")
                {
                    for (int i = 0; i < 6; i++)
                    {
                        //Read the next line
                        line = streamReader.ReadLine();
                        if (line == "")
                        {
                            return(false);
                        }
                        lineSplit = line.Split(',');

                        weapons.Add(new Database.DataModels.Weapon {
                            Name = lineSplit[0]
                        });
                    }

                    if (!streamReader.EndOfStream)
                    {
                        return(false);
                    }
                }
            }

            //At this point the data can be saved
            using (ClueLessContext db = new ClueLessContext())
            {
                //Save the configuration
                db.Configurations.Add(configuration);
                db.SaveChanges();

                //Save the locations
                foreach (Database.DataModels.Location l in locations)
                {
                    //add the location if it does not already exist
                    Database.DataModels.Location checkLocation = db.Locations.Where(x => x.LocationName.Equals(l.LocationName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    if (checkLocation == null)
                    {
                        db.Locations.Add(l);
                        db.SaveChanges();
                    }
                    else
                    {
                        l.ID = checkLocation.ID;
                    }
                }

                //Save the characters
                foreach (Database.DataModels.Character c in characters)
                {
                    //add the character if it does not already exist
                    Database.DataModels.Character checkCharacter = db.Characters.Where(x => x.Name.Equals(c.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    if (checkCharacter == null)
                    {
                        db.Characters.Add(c);
                        db.SaveChanges();
                    }
                    else
                    {
                        c.ID = checkCharacter.ID;
                    }
                }

                //Save the weapons
                foreach (Database.DataModels.Weapon w in weapons)
                {
                    //add the weapon if it does not already exist
                    Database.DataModels.Weapon checkWeapon = db.Weapons.Where(x => x.Name.Equals(w.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    if (checkWeapon == null)
                    {
                        db.Weapons.Add(w);
                        db.SaveChanges();
                    }
                }

                //Save the location permissions
                List <Position> dbPositions = new List <Position>();
                foreach (PositionHelper ph in positionsList)
                {
                    int locationID = locations.Where(x => x.LocationName == ph.Name).Select(x => x.ID).FirstOrDefault();
                    dbPositions.Add(new Position
                    {
                        LocationID      = locationID,
                        RowPosition     = ph.Row,
                        ColumnPosition  = ph.Column,
                        ConfigurationID = configuration.ID
                    });
                }


                db.Positions.AddRange(dbPositions);
                db.SaveChanges();

                //Create and save the character configurations
                foreach (var key in characterConfigurationInfo.Keys)
                {
                    int      characterID        = characters.Where(x => x.Name == key).Select(x => x.ID).FirstOrDefault();
                    string[] characterInfo      = characterConfigurationInfo[key].Split(',');
                    string[] characterColor     = characterInfo[1].Split(':');
                    string   name               = characterInfo[0];
                    int      startingPositionID = db.Positions.Where(x => x.Location.LocationName == name).Select(x => x.ID).FirstOrDefault();

                    Color color = Color.FromArgb(Convert.ToInt32(characterColor[0]), Convert.ToInt32(characterColor[1]), Convert.ToInt32(characterColor[2]));
                    characterConfiguration.Add(new CharacterConfiguration
                    {
                        CharacterID        = characterID,
                        ConfigurationID    = configuration.ID,
                        StartingPositionID = startingPositionID,
                        Color = color.Name
                    });
                }

                db.CharacterConfigurations.AddRange(characterConfiguration);
                db.SaveChanges();

                return(true);
            }
        }
Example #24
0
        public Clue RevealClue(int locationID, int gameID, int playerID)
        {
            Clue revealedClue = new Clue();

            using (ClueLessContext db = new ClueLessContext())
            {
                //Get the ClueLocation Object
                PositionToClue clue = db.PositionsToClues.Where(x => x.PositionID == locationID && x.GameID == gameID).FirstOrDefault();
                //Based on the clue type added the clue in the room to the player's  tracking table if it does not already exist
                int clueID = -1;
                switch (clue.ClueType)
                {
                case "Character":
                    //Look for the clue in the player's tracked character clues
                    clueID = db.PlayersToCharcters.Where(x => x.CharacterConfigurationID == clue.ClueID && x.PlayerID == playerID).Select(x => x.ID).FirstOrDefault();
                    //if it doesn't exist, add it to the player's tracker character clues
                    if (clueID <= 0)
                    {
                        db.PlayersToCharcters.Add(new PlayerToCharacter
                        {
                            PlayerID = playerID,
                            CharacterConfigurationID = clue.ClueID,
                        });
                        db.SaveChanges();
                    }
                    //Pull the information for the clue to be returned
                    CharacterConfiguration characterConfiguration = db.CharacterConfigurations.Where(x => x.ID == clue.ClueID).FirstOrDefault();
                    revealedClue = new Clue
                    {
                        ID   = characterConfiguration.ID,
                        Name = characterConfiguration.Character.Name,
                    };

                    break;

                case "Weapon":
                    //Look for the clue in the player's tracked weapon clues
                    clueID = db.PlayersToWeapons.Where(x => x.WeaponConfigurationID == clue.ClueID && x.PlayerID == playerID).Select(x => x.ID).FirstOrDefault();
                    //if it doesn't exist, add it to the player's tracked weapon clues
                    if (clueID <= 0)
                    {
                        db.PlayersToWeapons.Add(new PlayerToWeapon
                        {
                            PlayerID = playerID,
                            WeaponConfigurationID = clue.ClueID
                        });
                        db.SaveChanges();
                    }

                    //Pull the informaton for the clue to be returned
                    WeaponConfiguration weaponConfiguration = db.WeaponConfigurations.Where(x => x.ID == clue.ClueID).FirstOrDefault();
                    revealedClue = new Clue {
                        ID = weaponConfiguration.ID, Name = weaponConfiguration.Weapon.Name
                    };

                    break;

                case "Room":
                    clueID = db.PlayersToLocations.Where(x => x.PositionID == clue.ClueID && x.PlayerID == playerID).Select(x => x.ID).FirstOrDefault();
                    if (clueID > 0)
                    {
                        db.PlayersToLocations.Add(new PlayerToLocation
                        {
                            PlayerID   = playerID,
                            PositionID = clue.ClueID
                        });
                        db.SaveChanges();
                    }

                    //Pull the information for the clue to be returned
                    Position position = db.Positions.Where(x => x.ID == clue.ClueID).FirstOrDefault();
                    revealedClue = new Clue {
                        ID = position.ID, Name = position.Location.LocationName
                    };
                    break;

                default:
                    throw new ArgumentException();
                }

                // return the clue object
                return(revealedClue);
            }
        }
Example #25
0
        private static string GetEmailBody(NotificationType notification, int userID = -1, int suggestionID = -1, int gameID = -1)
        {
            string message           = "";
            string opening           = "Dear User,";
            string closingStatetment = "This is an automated email, responses sent to this address will not be recieved.\n\n" +
                                       "Sincerely,\nIconic Alliance";
            string playerName = "";
            string murderer   = "";
            string location   = "";
            string weapon     = "";

            try
            {
                if (suggestionID > 0)
                {
                    using (ClueLessContext db = new ClueLessContext())
                    {
                        playerName = db.Users.Where(x => x.ID == userID).Select(x => x.FirstName + " " + x.LastName).FirstOrDefault();
                        //Get the suggestion
                        Database.DataModels.Suggestion suggestion = db.Suggestions.Where(x => x.ID == suggestionID).FirstOrDefault();

                        murderer = suggestion.Character.Character.Name;
                        location = suggestion.Location.Location.LocationName;
                        weapon   = suggestion.Weapon.Weapon.Name;
                    }
                }
                if (userID > 0)
                {
                    using (ClueLessContext db = new ClueLessContext())
                    {
                        playerName = db.Users.Where(x => x.ID == userID).Select(x => x.FirstName + " " + x.LastName).FirstOrDefault();
                    }
                }
                switch (notification)
                {
                case NotificationType.UserNameReminder:
                    string Username = "";
                    using (ClueLessContext db = new ClueLessContext())
                    {
                        Username = db.Users.Where(x => x.ID == userID).Select(x => x.Username).FirstOrDefault();
                    }
                    message = "Your username for ClueLess is: " + Username + ". If you did not request this information, please check your account.";
                    break;

                case NotificationType.PasswordReset:
                    message = "Your password has been successfully reset. If you did not request a password reset, please check your account.";
                    break;

                case NotificationType.GameInvite:
                    message = "You have been invited by " + playerName + " to join them in a game of ClueLess. To accept the invitation, sign in to your ClueLess account. If you do not have an account and wish to join the game, create an account and search for the game to join.";
                    break;

                case NotificationType.NewSuggestion:
                    message = String.Format("A new suggestion has been made by: {0}. {0} suggested that is was {1} in the {2} with the {3}.", playerName, murderer, location, weapon);
                    break;

                case NotificationType.SuggestionResponse:
                    message = String.Format("{0} has responded to the suggestion: {1} in the {2} with the {3}. To see thier response, sign in to your ClueLess account and re-join your game.", playerName, murderer, location, weapon);
                    break;

                case NotificationType.AccusationMade:
                    message = String.Format("{0} has accused {1} of killing Mr.Boddy in the {2} with the {3}.", playerName, murderer, location, weapon);
                    break;

                case NotificationType.GameOver:

                    using (ClueLessContext db = new ClueLessContext())
                    {
                        Database.DataModels.Game game = db.Games.Where(x => x.ID == gameID).FirstOrDefault();
                        if (game != null)
                        {
                            if (game.Status == Database.DataModels.Status.Completed_Solved)
                            {
                                message = String.Format(" Your ClueLess Game {0} has completed. The murderer was commited by {1} in the {2} with the {3}.", game.Name, murderer, location, weapon);
                            }

                            if (game.Status == Database.DataModels.Status.Completed_Unsolved)
                            {
                                message = String.Format(" Your ClueLess Game {0} has completed. The murder was unsolved.", game.Name);
                            }
                        }
                    }

                    break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error creating email message");
            }


            string body = opening + Environment.NewLine + message + Environment.NewLine + Environment.NewLine + closingStatetment;

            return(body);
        }
Example #26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="playerID">the ID of the player revealing the clue</param>
        /// <param name="clueID">The ID of the clue being revealed</param>
        /// <param name="ClueType">The Type of clue being revealed: Character, Weapon, Room</param>
        public static Clue RevealClue(int playerID, int clueID, string ClueType, int suggestionID)
        {
            Clue revealedClue = new Clue();

            try
            {
                using (ClueLessContext db = new ClueLessContext())
                {
                    //Get the database suggestion object
                    Database.DataModels.Suggestion suggestion = db.Suggestions.Where(x => x.ID == suggestionID).FirstOrDefault();

                    //Update the suggestion's author's clue tracker based on the clue type
                    switch (ClueType)
                    {
                    case "Character":
                        db.PlayersToCharcters.Add(new Database.DataModels.PlayerToCharacter
                        {
                            PlayerID = suggestion.PlayerID,
                            CharacterConfigurationID = clueID,
                        });
                        db.SaveChanges();

                        //Pull the information for the clue to be returned
                        CharacterConfiguration characterConfiguration = db.CharacterConfigurations.Where(x => x.ID == clueID).FirstOrDefault();
                        revealedClue = new Clue
                        {
                            ID   = characterConfiguration.ID,
                            Name = characterConfiguration.Character.Name,
                        };

                        break;

                    case "Weapon":
                        db.PlayersToWeapons.Add(new Database.DataModels.PlayerToWeapon
                        {
                            PlayerID = suggestion.PlayerID,
                            WeaponConfigurationID = clueID
                        });
                        db.SaveChanges();

                        WeaponConfiguration weaponConfiguration = db.WeaponConfigurations.Where(x => x.ID == clueID).FirstOrDefault();
                        revealedClue = new Clue {
                            ID = weaponConfiguration.ID, Name = weaponConfiguration.Weapon.Name
                        };

                        break;

                    case "Room":
                        db.PlayersToLocations.Add(new Database.DataModels.PlayerToLocation
                        {
                            PlayerID   = suggestion.PlayerID,
                            PositionID = clueID
                        });
                        db.SaveChanges();

                        //Pull the information for the clue to be returned
                        Position position = db.Positions.Where(x => x.ID == clueID).FirstOrDefault();
                        revealedClue = new Clue {
                            ID = position.ID, Name = position.Location.LocationName
                        };

                        break;

                    default:
                        throw new ArgumentException();
                    }
                }
            }catch (Exception e)
            {
                Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
            }

            return(revealedClue);
        }