internal bool IsValid() { var fieldsAreSpecified = this.GameId != Guid.Empty && !string.IsNullOrEmpty(this.Platform) && this.PlayerId != Guid.Empty && this.StartTimeUtc > DateTime.MinValue; var doesGameExist = DatabaseMediator.ExecuteScalar <int>("SELECT COUNT(*) FROM Game WHERE Id = @id", this.GameId) == 1; return(fieldsAreSpecified && doesGameExist); }
internal bool IsValid() { var fieldsAreSpecified = !string.IsNullOrEmpty(this.Name) && this.Name.Length >= 6 && this.OwnerId > 0; var doesOwnerExist = DatabaseMediator.ExecuteScalar <int>("SELECT COUNT(*) FROM UserProfile WHERE UserId = @id", new { id = this.OwnerId }) == 1; return(fieldsAreSpecified && doesOwnerExist); }
// POST api/games public JsonApiObject <Game> Post([FromBody] string json) { NullCheck(json); var game = JsonConvert.DeserializeObject <Game>(json); var toReturn = new JsonApiObject <Game>(); if (game.IsValid()) { if (game.Id == Guid.Empty) { game.Id = Guid.NewGuid(); } toReturn.Data = new List <Game> { game }; DatabaseMediator.ExecuteQuery("INSERT INTO Game (Id, Name, OwnerId) VALUES (@Id, @Name, @OwnerId)", game); } else { toReturn.Errors = new string[] { "Validation failed." }; } return(toReturn); }
public ActionResult Create(RegMe regMe) { try { List <string> logins = new List <string>(); System.IO.StreamReader file = new System.IO.StreamReader(new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Users.txt"), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)); if (regMe.password != regMe.password1) { ModelState.AddModelError("", "Пароли не совпадают!"); } List <KeyValuePair <string, string> > logs = new List <KeyValuePair <string, string> >(); if (!string.IsNullOrWhiteSpace(regMe.login)) { string line; while ((line = file.ReadLine()) != null) { if (line != "") { string[] str = line.Split(' '); logs.Add(new KeyValuePair <string, string>(str[0], str[1])); logins.Add(str[0]); } } file.Close(); if (logins.Count() > 0 && logins.Contains(regMe.login)) { ModelState.AddModelError("", "Такой пользователь уже существует"); } } if (ModelState.IsValid) { SHA256Managed hash = new SHA256Managed(); byte[] hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(regMe.login + regMe.password)); string hashStr = BitConverter.ToString(hashBytes).Replace("-", ""); logs.Add(new KeyValuePair <string, string>(regMe.login, hashStr)); System.IO.StreamWriter file1 = new System.IO.StreamWriter(new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Users.txt"), FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite)); string resStr = ""; foreach (var tmp in logs) { resStr += tmp.Key + " " + tmp.Value + "\n"; } file1.Write(resStr); file1.Close(); DatabaseMediator db = new DatabaseMediator(System.Web.HttpContext.Current.Server.MapPath("~")); db.createUser(regMe.login); return(View("Index")); } return(View("Register")); } catch (Exception e) { System.IO.File.AppendAllText(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/log.txt"), e.Message); ViewBag.MessagerFromControl = "Произошла ошибка, зайдите позже."; return(View("Index")); } }
public static int GetCurrentUserId(this ApiController c) { var userName = c.User.Identity.Name; if (!userNameToId.ContainsKey(userName)) { var userId = DatabaseMediator.ExecuteScalar <int>("SELECT UserId FROM UserProfile WHERE UserName = @name", new { name = userName }); userNameToId[userName] = userId; } return(userNameToId[userName]); }
// POST api/<controller> public JsonApiObject <GameSession> Post([FromBody] string json) { var session = JsonConvert.DeserializeObject <GameSession>(json); var toReturn = new JsonApiObject <GameSession>(); if (session.IsValid()) { toReturn.Data = new List <GameSession> { session }; DatabaseMediator.ExecuteQuery("INSERT INTO Game (Id, GameId, Platform, PlayerId, StartTimeUtc) VALUES (@Id, @GameId, @Platform, @PlayerId, @StartTimeUtc)", session); } else { toReturn.Errors = new string[] { "Validation failed." }; } return(toReturn); }
/* * Метод для выхода из приложения. * Входные параметры: * 1. Строка логин - строка или null, если в куках ничего нет * Выходные параметры: * ActionResult с помощью которого пользователь перенаправляется на страницу Index. * Куки, содержащие информацию о пользователе очищаются. * Если в ходе работы произошли ошибки, выводится сообщение об этом. * Побочные эффекты: * 1. Модифицируется файл /App_Data/UserData.txt * 2. Модифицируется файл /App_Data/OnlineUsers.txt * 3. Модифицируется файл /App_Data/log.txt */ public ActionResult Logout(string loginUser) { try { FormsAuthentication.SignOut(); System.IO.StreamReader file = new System.IO.StreamReader(new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/OnlineUsers.txt"), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)); List <KeyValuePair <string, string> > users = new List <KeyValuePair <string, string> >(); string line; while ((line = file.ReadLine()) != null) { if (line != "") { string[] logins = line.Split(' '); users.Add(new KeyValuePair <string, string>(logins[0], logins[1])); } } file.Close(); System.IO.StreamWriter file1 = new System.IO.StreamWriter(new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/OnlineUsers.txt"), FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite)); users = users.Where(c => c.Key != loginUser).ToList(); string result = ""; foreach (var str in users) { result += str.Key + " " + str.Value + "\n"; } file1.Write(result); file1.Close(); DatabaseMediator db = new DatabaseMediator(System.Web.HttpContext.Current.Server.MapPath("~")); db.setUserLastActivity(loginUser, DateTime.UtcNow); return(View("Index")); } catch (Exception e) { System.IO.File.AppendAllText(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/log.txt"), e.Message); ViewBag.MessagerFromControl = "Произошла ошибка, зайдите позже."; return(View("Index")); } }
// GET api/games public JsonApiObject <Game> Get() { var all = DatabaseMediator.GetAll <Game>("SELECT * FROM Game WHERE OwnerId = @me", new { me = this.GetCurrentUserId() }); return(new JsonApiObject <Game>(all)); }