public override void HandleRequest(MvcRoute Route) { // Try and Fetch Player ID Int32.TryParse(Route.Action, out Pid); // NOTE: The HttpServer will handle the DbConnectException using (Database = new StatsDatabase()) { // Fetch Player Rows = Database.Query("SELECT * FROM player WHERE id=@P0", Pid); if (Rows.Count == 0) { Client.Response.Redirect("/bf2stats/search"); return; } // Load our page based on the param passed if (Route.Params.Length > 0) { if (Route.Params[0] == "rankings") ShowRankings(); else if (Route.Params[0] == "history") ShowHistory(); else Client.Response.StatusCode = 404; } else { ShowStats(); } } }
private static bool MatchProvider(MvcRoute applyTo, RequestContext requestContext) { var area = AreaHelpers.GetAreaName(requestContext.RouteData); var controller = requestContext.GetRequestValue("controller"); var action = requestContext.GetRequestValue("action"); var matched = applyTo.Area.EqualsOrNullEmpty(area, StringComparison.OrdinalIgnoreCase) && applyTo.Controller.Equals(controller, StringComparison.OrdinalIgnoreCase) && applyTo.Action.EqualsOrNullEmpty(action, StringComparison.OrdinalIgnoreCase); if (matched && applyTo.RouteValues != null) { foreach (var item in applyTo.RouteValues) { if (item.Value == null) { continue; } var routeValue = requestContext.GetRequestValue(item.Key); if (routeValue == null) { matched = false; break; } if (!item.Value.ToString().EqualsOrNullEmpty(routeValue.ToString(), StringComparison.OrdinalIgnoreCase)) { matched = false; break; } } } return(matched); }
private static bool MatchProvider(MvcRoute applyTo, RequestContext requestContext) { var area = AreaHelpers.GetAreaName(requestContext.RouteData); var controller = requestContext.GetRequestValue("controller"); var action = requestContext.GetRequestValue("action"); var matched = applyTo.Area.EqualsOrNullEmpty(area, StringComparison.OrdinalIgnoreCase) && applyTo.Controller.Equals(controller, StringComparison.OrdinalIgnoreCase) && applyTo.Action.EqualsOrNullEmpty(action, StringComparison.OrdinalIgnoreCase); if (matched && applyTo.RouteValues != null) { foreach (var item in applyTo.RouteValues) { if (item.Value == null) { continue; } var routeValue = requestContext.GetRequestValue(item.Key); if (routeValue == null) { matched = false; break; } if (!item.Value.ToString().EqualsOrNullEmpty(routeValue.ToString(), StringComparison.OrdinalIgnoreCase)) { matched = false; break; } } } return matched; }
public override void HandleRequest(MvcRoute Route) { // Get our Action if (Route.Action == "index" || Array.IndexOf(ActionNames, Route.Action) < 0) ShowIndex(); else ShowRankingType(Route); }
protected void SetGridResult(MvcRoute route) { _gridResult.ColumnSettings = Support.GetVendorColumnSettings(); var currentViewModel = GridViewExtension.GetViewModel("VendorGridView"); _gridResult.GridViewModel = (currentViewModel == null) ? Support.CreateGridViewModel(_gridResult.ColumnSettings) : currentViewModel; _gridResult.Records = Support.GetVendors(); }
public void Can_create_mvc_route_with_constraints() { var route = MvcRoute .MapUrl("test/{controller}/{action}") .WithConstraints(new { action = "^[a-Z]+$" }) .ToDefaultAction <MvcRouteController>(x => x.WithTwoArgs("mupp", null)); Assert.AreEqual("^[a-Z]+$", route.Constraints["action"]); }
public void Can_create_mvc_route_to_method_with_actionName() { var route = MvcRoute .MapUrl("test/{controller}/{action}") .ToDefaultAction <MvcRouteController>(x => x.WithActionNameAttribute()); Assert.AreEqual("ChangedName", route.Defaults["action"]); }
public void Can_create_mvc_route_to_method_with_string_defaults() { var route = MvcRoute .MapUrl("test/{controller}/{action}") .WithDefaults(new { controller = "home", action = "index" }); Assert.AreEqual("home", route.Defaults["controller"]); Assert.AreEqual("index", route.Defaults["action"]); }
public void Can_create_mvc_route_with_default_controller_action_and_additional_defaults() { var route = MvcRoute .MapUrl("test/{controller}/{action}/{id}") .ToDefaultAction <MvcRouteController>(x => x.Index(), new { id = "def" }); Assert.AreEqual("MvcRoute", route.Defaults["controller"]); Assert.AreEqual("Index", route.Defaults["action"]); Assert.AreEqual("def", route.Defaults["id"]); }
public void Can_create_mvc_route_with_namespaces() { var namespaces = new[] { "Namespace.One", "Namespace.Two" }; var route = MvcRoute .MapUrl("test/{controller}/{action}") .WithNamespaces(namespaces) .ToDefaultAction <MvcRouteController>(x => x.WithTwoArgs("mupp", null)); Assert.AreEqual(namespaces, route.DataTokens["Namespaces"]); }
public void Can_create_mvc_route_and_add_to_route_collection() { var routes = new RouteCollection(); MvcRoute .MapUrl("test/{controller}/{action}") .ToDefaultAction <MvcRouteController>(x => x.WithTwoArgs("mupp", null)) .AddWithName("TestName", routes); Assert.IsNotNull(routes["TestName"]); }
public void Can_create_mvc_route_with_default_controller_action_and_parameter_defaults() { var route = MvcRoute .MapUrl("test/{controller}/{action}") .ToDefaultAction <MvcRouteController>(x => x.WithTwoArgs("mupp", null)); Assert.AreEqual("MvcRoute", route.Defaults["controller"]); Assert.AreEqual("WithTwoArgs", route.Defaults["action"]); Assert.AreEqual("mupp", route.Defaults["arg1"]); Assert.IsFalse(route.Defaults.ContainsKey("arg2")); }
public override void HandleRequest(MvcRoute Route) { // Get our Action if (Route.Action == "index" || Array.IndexOf(ActionNames, Route.Action) < 0) { ShowIndex(); } else { ShowRankingType(Route); } }
public virtual void RegisterRoutes(Action action) { RouteCollection routes = RouteTable.Routes; routes.Clear(); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{resource}.gif/{*pathInfo}"); routes.IgnoreRoute("{resource}.ico/{*pathInfo}"); action(); MvcRoute.MappUrl("{conferenceKey}/speakers/{speakerKey}") .WithDefaults(new { controller = "Speaker", action = "index" }) .AddWithName("speaker", routes) .RouteHandler = new DomainNameRouteHandler(); MvcRoute.MappUrl("{conferenceKey}/sessions/{sessionKey}") .WithDefaults(new { controller = "Session", action = "index" }) .AddWithName("session", routes) .RouteHandler = new DomainNameRouteHandler(); MvcRoute.MappUrl("{conferenceKey}/proposal/vote/{id}") .WithDefaults(new { controller = "Proposal", action = "vote" }) .AddWithName("ProposalVote", routes) .RouteHandler = new DomainNameRouteHandler(); MvcRoute.MappUrl("{conferenceKey}/{controller}/{action}") .WithDefaults(new { controller = "Conference", action = "index" }) .WithConstraints(new { conferenceKey = new ConferenceKeyCannotBeAControllerNameConstraint(), controller = "schedule|session|timeslot|track|attendee|conference|speaker|admin|proposal|user|sponsor|meeting" }) .AddWithName("conferenceDefault", routes) .RouteHandler = new DomainNameRouteHandler(); MvcRoute.MappUrl("{controller}/{action}") .WithDefaults(new { controller = "home", action = "index" }) .WithConstraints(new { controller = "(admin|login|home|conference|usergroup|user|rss|sponsor|rssfeed|event|meeting|heartbeat)" }) .AddWithName("default", routes) .RouteHandler = new DomainNameRouteHandler(); }
public override void HandleRequest(MvcRoute Route) { // Try and Fetch Player ID Int32.TryParse(Route.Action, out Pid); // NOTE: The HttpServer will handle the DbConnectException using (Database = new StatsDatabase()) { // Fetch Player Rows = Database.Query("SELECT * FROM player WHERE id=@P0", Pid); if (Rows.Count == 0) { Client.Response.Redirect("/bf2stats/search"); return; } // Load our page based on the param passed if (Route.Params.Length > 0) { if (Route.Params[0] == "rankings") { ShowRankings(); } else if (Route.Params[0] == "history") { ShowHistory(); } else { Client.Response.StatusCode = 404; } } else { ShowStats(); } } }
public override void HandleRequest(MvcRoute Route) { // Get our POST variables HttpRequest Request = Client.Request; Dictionary <string, string> postParams = Request.GetFormUrlEncodedPostVars(); int[] pids = new int[0]; // Fetch our cookie, which contains our PiD's Cookie C = Request.Request.Cookies["leaderboard"] ?? new Cookie("leaderboard", ""); // Convert cookie format into a readable one, and make sure we end with a comma! Model.CookieValue = C.Value.Trim().Replace('|', ','); if (!Model.CookieValue.EndsWith(",")) { Model.CookieValue += ","; } // Save Leaderboard if (postParams.ContainsKey("set") && postParams.ContainsKey("leaderboard")) // Save cookie { Model.CookieValue = postParams["leaderboard"]; } else if (Route.Action != "index" && Route.Params.Length != 0) { switch (Route.Action) { case "add": if (Validator.IsValidPID(Route.Params[0])) { Model.CookieValue += $"{Route.Params[0]},"; } break; case "remove": if (Validator.IsValidPID(Route.Params[0])) { Model.CookieValue = Model.CookieValue.Replace($"{Route.Params[0]},", ""); } break; case "list": Model.CookieValue = Route.Params[0]; break; } } // Read pids from the cookie try { // Pids are stored as xxxx,yyyyy,zzzz in the cookie if (Model.CookieValue.Length > 0) { string[] players = Model.CookieValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (players.Length > 0) { pids = Array.ConvertAll(players, Int32.Parse).Distinct().ToArray(); } } } catch { // Bad Cookie value, so flush it! Model.CookieValue = ""; C.Value = String.Empty; Client.Response.SetCookie(C); } // if "get" is POSTED, that means we are generated a URL instead of a cookie if (postParams.ContainsKey("get")) { Client.Response.Redirect(Model.Root + "/myleaderboard/list/" + String.Join(",", pids)); return; } // If we have some player ID's, then the leaderboard is not empty if (pids.Length > 0) { // NOTE: The HttpServer will handle the DbConnectException using (StatsDatabase Database = new StatsDatabase()) { var Rows = Database.Query( String.Format("SELECT id, name, score, time, country, rank, lastonline, kills, deaths FROM player WHERE id IN ({0})", String.Join(",", pids) )); // Loop through each result, and process foreach (Dictionary <string, object> Row in Rows) { // DO Kill Death Ratio double Kills = Int32.Parse(Row["kills"].ToString()); double Deaths = Int32.Parse(Row["deaths"].ToString()); double Kdr = (Deaths > 0) ? Math.Round(Kills / Deaths, 3) : Kills; // Get Score Per Min double Score = Int32.Parse(Row["score"].ToString()); double Mins = Int32.Parse(Row["time"].ToString()) / 60; double SPM = (Mins > 0) ? Math.Round(Score / Mins, 4) : Score; int Pid = Int32.Parse(Row["id"].ToString()); // Add Result Model.Players.Add(new PlayerResult { Pid = Pid, Name = Row["name"].ToString(), Score = (int)Score, Rank = Int32.Parse(Row["rank"].ToString()), TimePlayed = FormatTime(Int32.Parse(Row["time"].ToString())), LastOnline = FormatDate(Int32.Parse(Row["lastonline"].ToString())), Country = Row["country"].ToString().ToUpperInvariant(), Kdr = Kdr, Spm = SPM, Status = GetOnlineStatus(Pid) }); } } } // Finally, set the cookie if we arent viewing from a List if (Route.Action != "list") { Model.CookieValue = String.Join(",", pids); C.Value = String.Join("|", pids); C.Expires = DateTime.Now.AddYears(1); C.Path = "/"; Client.Response.SetCookie(C); } // TO prevent null expception in the template if (Model.CookieValue == null) { Model.CookieValue = String.Empty; } // Set content type base.SendTemplateResponse("myleaderboard", typeof(LeaderboardModel), Model); }
/// <summary> /// Processes the request, and sends a resonse back to the client /// </summary> public abstract void HandleRequest(MvcRoute Route);
public override void HandleRequest(MvcRoute Route) { // Get our POST variables HttpRequest Request = Client.Request; Dictionary<string, string> postParams = Request.GetFormUrlEncodedPostVars(); int[] pids = new int[0]; // Fetch our cookie, which contains our PiD's Cookie C = Request.Request.Cookies["leaderboard"] ?? new Cookie("leaderboard", ""); // Convert cookie format into a readable one, and make sure we end with a comma! Model.CookieValue = C.Value.Trim().Replace('|', ','); if (!Model.CookieValue.EndsWith(",")) Model.CookieValue += ","; // Save Leaderboard if (postParams.ContainsKey("set") && postParams.ContainsKey("leaderboard")) // Save cookie { Model.CookieValue = postParams["leaderboard"]; } else if (Route.Action != "index" && Route.Params.Length != 0) { switch (Route.Action) { case "add": if (Validator.IsValidPID(Route.Params[0])) Model.CookieValue += $"{Route.Params[0]},"; break; case "remove": if (Validator.IsValidPID(Route.Params[0])) Model.CookieValue = Model.CookieValue.Replace($"{Route.Params[0]},", ""); break; case "list": Model.CookieValue = Route.Params[0]; break; } } // Read pids from the cookie try { // Pids are stored as xxxx,yyyyy,zzzz in the cookie if (Model.CookieValue.Length > 0) { string[] players = Model.CookieValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (players.Length > 0) { pids = Array.ConvertAll(players, Int32.Parse).Distinct().ToArray(); } } } catch { // Bad Cookie value, so flush it! Model.CookieValue = ""; C.Value = String.Empty; Client.Response.SetCookie(C); } // if "get" is POSTED, that means we are generated a URL instead of a cookie if (postParams.ContainsKey("get")) { Client.Response.Redirect(Model.Root + "/myleaderboard/list/" + String.Join(",", pids)); return; } // If we have some player ID's, then the leaderboard is not empty if (pids.Length > 0) { // NOTE: The HttpServer will handle the DbConnectException using (StatsDatabase Database = new StatsDatabase()) { var Rows = Database.Query( String.Format("SELECT id, name, score, time, country, rank, lastonline, kills, deaths FROM player WHERE id IN ({0})", String.Join(",", pids) )); // Loop through each result, and process foreach (Dictionary<string, object> Row in Rows) { // DO Kill Death Ratio double Kills = Int32.Parse(Row["kills"].ToString()); double Deaths = Int32.Parse(Row["deaths"].ToString()); double Kdr = (Deaths > 0) ? Math.Round(Kills / Deaths, 3) : Kills; // Get Score Per Min double Score = Int32.Parse(Row["score"].ToString()); double Mins = Int32.Parse(Row["time"].ToString()) / 60; double SPM = (Mins > 0) ? Math.Round(Score / Mins, 4) : Score; int Pid = Int32.Parse(Row["id"].ToString()); // Add Result Model.Players.Add(new PlayerResult { Pid = Pid, Name = Row["name"].ToString(), Score = (int)Score, Rank = Int32.Parse(Row["rank"].ToString()), TimePlayed = FormatTime(Int32.Parse(Row["time"].ToString())), LastOnline = FormatDate(Int32.Parse(Row["lastonline"].ToString())), Country = Row["country"].ToString().ToUpperInvariant(), Kdr = Kdr, Spm = SPM, Status = GetOnlineStatus(Pid) }); } } } // Finally, set the cookie if we arent viewing from a List if (Route.Action != "list") { Model.CookieValue = String.Join(",", pids); C.Value = String.Join("|", pids); C.Expires = DateTime.Now.AddYears(1); C.Path = "/"; Client.Response.SetCookie(C); } // TO prevent null expception in the template if (Model.CookieValue == null) Model.CookieValue = String.Empty; // Set content type base.SendTemplateResponse("myleaderboard", typeof(LeaderboardModel), Model); }
public override void HandleRequest(MvcRoute Route) { // Get our POST'ed parameters Dictionary <string, string> postParams = Client.Request.GetFormUrlEncodedPostVars(); // If we have a search value, run it if (postParams.ContainsKey("searchvalue")) { // NOTE: The HttpServer will handle the DbConnectException using (StatsDatabase Database = new StatsDatabase()) { Model.SearchValue = postParams["searchvalue"].Replace("+", " "); List <Dictionary <string, object> > Rows; // Do processing if (Validator.IsNumeric(Model.SearchValue)) { if (Validator.IsValidPID(Model.SearchValue)) { // If player PID exists, redirect there bool exists = Database.ExecuteScalar <bool>("SELECT COUNT(id) FROM player WHERE id=@P0", Model.SearchValue); if (exists) { Client.Response.Redirect("/bf2stats/player/" + Model.SearchValue); return; } } Rows = Database.Query( "SELECT id, name, score, time, country, rank, lastonline, kills, deaths FROM player WHERE id LIKE @P0 LIMIT 50", "%" + Model.SearchValue + "%" ); } else { // Check to see if player with this name exists Rows = Database.Query("SELECT id FROM player WHERE name=@P0 LIMIT 1", Model.SearchValue); if (Rows.Count > 0) { Client.Response.Redirect("/bf2stats/player/" + Rows[0]["id"]); return; } Rows = Database.Query( "SELECT id, name, score, time, country, rank, lastonline, kills, deaths FROM player WHERE name LIKE @P0 LIMIT 50", Model.SearchValue ); } // Loop through each result, and process foreach (Dictionary <string, object> Row in Rows) { // DO Kill Death Ratio double Kills = Int32.Parse(Row["kills"].ToString()); double Deaths = Int32.Parse(Row["deaths"].ToString()); double Kdr = (Deaths > 0) ? Math.Round(Kills / Deaths, 3) : Kills; // Get Score Per Min double Score = Int32.Parse(Row["score"].ToString()); double Mins = Int32.Parse(Row["time"].ToString()) / 60; double SPM = (Mins > 0) ? Math.Round(Score / Mins, 4) : Score; // Add Result Model.SearchResults.Add(new PlayerResult { Pid = Int32.Parse(Row["id"].ToString()), Name = Row["name"].ToString(), Score = (int)Score, Rank = Int32.Parse(Row["rank"].ToString()), TimePlayed = FormatTime(Int32.Parse(Row["time"].ToString())), LastOnline = FormatDate(Int32.Parse(Row["lastonline"].ToString())), Country = Row["country"].ToString().ToUpperInvariant(), Kdr = Kdr, Spm = SPM }); } } } // Send response base.SendTemplateResponse("search", typeof(SearchModel), Model); }
private void ShowRankingType(MvcRoute Route) { // Create our model RankingsTypeModel Model = new RankingsTypeModel(Client); Model.UrlName = Route.Action; string CacheName = $"rankings_{Route.Action}_1"; // Parse our country and page filters based on URL // Url formats: // - scoreType/country/pageNumber // - scoreType/pageNumber if (Route.Params.Length == 1) { if (Int32.TryParse(Route.Params[0], out Model.CurrentPage)) { // Just a page number provided CacheName = $"rankings_{Route.Action}_{Model.CurrentPage}"; } else if (Route.Params[0].Length == 2) { // Just a country code provided, default to page 1 Model.Country = Route.Params[0]; CacheName = $"rankings_{Route.Action}_{Model.Country}_1"; } } else if (Route.Params.Length == 2 && Int32.TryParse(Route.Params[1], out Model.CurrentPage)) { if (Route.Params[0].Length == 2) // Check valid country code { Model.Country = Route.Params[0]; CacheName = $"rankings_{Route.Action}_{Model.Country}_{Model.CurrentPage}"; } else { CacheName = $"rankings_{Route.Action}_{Model.CurrentPage}"; } } // Check the cache file if (!base.CacheFileExpired(CacheName, 30)) { base.SendCachedResponse(CacheName); return; } // NOTE: The HttpServer will handle the DbConnectException using (StatsDatabase Database = new StatsDatabase()) { // Get our DISTINCT country list from our player pool SelectQueryBuilder builder = new SelectQueryBuilder(Database); builder.SelectColumn("country"); builder.Distinct = true; builder.SelectFromTable("player"); builder.AddWhere("country", Comparison.NotEqualTo, "xx"); foreach (var Row in builder.ExecuteQuery()) { Model.CountryList.Add(Row["country"].ToString()); } // Start building our player query builder = new SelectQueryBuilder(Database); builder.SelectCount(); builder.SelectFromTable("player"); WhereClause Where = builder.AddWhere("score", Comparison.GreaterOrEquals, 1); // Add country filter if (Model.Country.Length == 2) { Where.AddClause(LogicOperator.And, "country", Comparison.Equals, Model.Country); } // Hpd additional Where if (Route.Action.Equals("hpd", StringComparison.InvariantCultureIgnoreCase)) { Where.AddClause(LogicOperator.And, "time", Comparison.GreaterOrEquals, 3600); } // Get our total records Model.TotalRecords = builder.ExecuteScalar <int>(); Model.TotalPages = 1 + (Model.TotalRecords / PlayersPerPage); Model.ScoreHeader = GetHeaderName(Route.Action); // Now, Build Query that will select the players, not just the count bool isDecimal = false; FinishQuery(Route.Action, builder, out isDecimal); // Get our players, limiting to 50 and starting by page builder.Limit(PlayersPerPage, (Model.CurrentPage * PlayersPerPage) - PlayersPerPage); var Rows = builder.ExecuteQuery(); // Initialize records based on records returned from Database Model.Records = new List <RankingsTypeModel.PlayerRow>(Rows.Count); foreach (Dictionary <string, object> Player in Rows) { Model.Records.Add(new RankingsTypeModel.PlayerRow() { Pid = Int32.Parse(Player["pid"].ToString()), Name = Player["name"].ToString(), Rank = Int32.Parse(Player["rank"].ToString()), Country = Player["country"].ToString(), Time = Int32.Parse(Player["time"].ToString()), ScorePerMin = Double.Parse(Player["spm"].ToString()), KillDeathRatio = Double.Parse(Player["kdr"].ToString()), WinLossRatio = Double.Parse(Player["wlr"].ToString()), ScoreValue = (isDecimal) ? String.Format(CultureInfo.InvariantCulture, "{0:n4}", Player["value"]) : String.Format(CultureInfo.InvariantCulture, "{0:n0}", Player["value"]) }); } } // Send response base.SendTemplateResponse("rankings_type", typeof(RankingsTypeModel), Model, CacheName); }
private void ShowRankingType(MvcRoute Route) { // Create our model RankingsTypeModel Model = new RankingsTypeModel(Client); Model.UrlName = Route.Action; string CacheName = $"rankings_{Route.Action}_1"; // Parse our country and page filters based on URL // Url formats: // - scoreType/country/pageNumber // - scoreType/pageNumber if (Route.Params.Length == 1) { if (Int32.TryParse(Route.Params[0], out Model.CurrentPage)) { // Just a page number provided CacheName = $"rankings_{Route.Action}_{Model.CurrentPage}"; } else if (Route.Params[0].Length == 2) { // Just a country code provided, default to page 1 Model.Country = Route.Params[0]; CacheName = $"rankings_{Route.Action}_{Model.Country}_1"; } } else if (Route.Params.Length == 2 && Int32.TryParse(Route.Params[1], out Model.CurrentPage)) { if (Route.Params[0].Length == 2) // Check valid country code { Model.Country = Route.Params[0]; CacheName = $"rankings_{Route.Action}_{Model.Country}_{Model.CurrentPage}"; } else CacheName = $"rankings_{Route.Action}_{Model.CurrentPage}"; } // Check the cache file if (!base.CacheFileExpired(CacheName, 30)) { base.SendCachedResponse(CacheName); return; } // NOTE: The HttpServer will handle the DbConnectException using (StatsDatabase Database = new StatsDatabase()) { // Get our DISTINCT country list from our player pool SelectQueryBuilder builder = new SelectQueryBuilder(Database); builder.SelectColumn("country"); builder.Distinct = true; builder.SelectFromTable("player"); builder.AddWhere("country", Comparison.NotEqualTo, "xx"); foreach (var Row in builder.ExecuteQuery()) Model.CountryList.Add(Row["country"].ToString()); // Start building our player query builder = new SelectQueryBuilder(Database); builder.SelectCount(); builder.SelectFromTable("player"); WhereClause Where = builder.AddWhere("score", Comparison.GreaterOrEquals, 1); // Add country filter if (Model.Country.Length == 2) Where.AddClause(LogicOperator.And, "country", Comparison.Equals, Model.Country); // Hpd additional Where if (Route.Action.Equals("hpd", StringComparison.InvariantCultureIgnoreCase)) Where.AddClause(LogicOperator.And, "time", Comparison.GreaterOrEquals, 3600); // Get our total records Model.TotalRecords = builder.ExecuteScalar<int>(); Model.TotalPages = 1 + (Model.TotalRecords / PlayersPerPage); Model.ScoreHeader = GetHeaderName(Route.Action); // Now, Build Query that will select the players, not just the count bool isDecimal = false; FinishQuery(Route.Action, builder, out isDecimal); // Get our players, limiting to 50 and starting by page builder.Limit(PlayersPerPage, (Model.CurrentPage * PlayersPerPage) - PlayersPerPage); var Rows = builder.ExecuteQuery(); // Initialize records based on records returned from Database Model.Records = new List<RankingsTypeModel.PlayerRow>(Rows.Count); foreach (Dictionary<string, object> Player in Rows) { Model.Records.Add(new RankingsTypeModel.PlayerRow() { Pid = Int32.Parse(Player["pid"].ToString()), Name = Player["name"].ToString(), Rank = Int32.Parse(Player["rank"].ToString()), Country = Player["country"].ToString(), Time = Int32.Parse(Player["time"].ToString()), ScorePerMin = Double.Parse(Player["spm"].ToString()), KillDeathRatio = Double.Parse(Player["kdr"].ToString()), WinLossRatio = Double.Parse(Player["wlr"].ToString()), ScoreValue = (isDecimal) ? String.Format(CultureInfo.InvariantCulture, "{0:n4}", Player["value"]) : String.Format(CultureInfo.InvariantCulture, "{0:n0}", Player["value"]) }); } } // Send response base.SendTemplateResponse("rankings_type", typeof(RankingsTypeModel), Model, CacheName); }
public override void HandleRequest(MvcRoute Route) { // Get our POST'ed parameters Dictionary<string, string> postParams = Client.Request.GetFormUrlEncodedPostVars(); // If we have a search value, run it if (postParams.ContainsKey("searchvalue")) { // NOTE: The HttpServer will handle the DbConnectException using (StatsDatabase Database = new StatsDatabase()) { Model.SearchValue = postParams["searchvalue"].Replace("+", " "); List<Dictionary<string, object>> Rows; // Do processing if (Validator.IsNumeric(Model.SearchValue)) { if (Validator.IsValidPID(Model.SearchValue)) { // If player PID exists, redirect there bool exists = Database.ExecuteScalar<bool>("SELECT COUNT(id) FROM player WHERE id=@P0", Model.SearchValue); if (exists) { Client.Response.Redirect("/bf2stats/player/" + Model.SearchValue); return; } } Rows = Database.Query( "SELECT id, name, score, time, country, rank, lastonline, kills, deaths FROM player WHERE id LIKE @P0 LIMIT 50", "%" + Model.SearchValue + "%" ); } else { // Check to see if player with this name exists Rows = Database.Query("SELECT id FROM player WHERE name=@P0 LIMIT 1", Model.SearchValue); if (Rows.Count > 0) { Client.Response.Redirect("/bf2stats/player/" + Rows[0]["id"]); return; } Rows = Database.Query( "SELECT id, name, score, time, country, rank, lastonline, kills, deaths FROM player WHERE name LIKE @P0 LIMIT 50", Model.SearchValue ); } // Loop through each result, and process foreach (Dictionary<string, object> Row in Rows) { // DO Kill Death Ratio double Kills = Int32.Parse(Row["kills"].ToString()); double Deaths = Int32.Parse(Row["deaths"].ToString()); double Kdr = (Deaths > 0) ? Math.Round(Kills / Deaths, 3) : Kills; // Get Score Per Min double Score = Int32.Parse(Row["score"].ToString()); double Mins = Int32.Parse(Row["time"].ToString()) / 60; double SPM = (Mins > 0) ? Math.Round(Score / Mins, 4) : Score; // Add Result Model.SearchResults.Add(new PlayerResult { Pid = Int32.Parse(Row["id"].ToString()), Name = Row["name"].ToString(), Score = (int)Score, Rank = Int32.Parse(Row["rank"].ToString()), TimePlayed = FormatTime(Int32.Parse(Row["time"].ToString())), LastOnline = FormatDate(Int32.Parse(Row["lastonline"].ToString())), Country = Row["country"].ToString().ToUpperInvariant(), Kdr = Kdr, Spm = SPM }); } } } // Send response base.SendTemplateResponse("search", typeof(SearchModel), Model); }
public override void HandleRequest(MvcRoute Route) { // NOTE: The HttpServer will handle the DbConnectException using (StatsDatabase Database = new StatsDatabase()) { if (Program.Config.BF2S_HomePageType == HomePageType.Leaderboard) { // Fetch our player list Model.Players = Database.Query( "SELECT id, name, rank, score, kills, country, time FROM player WHERE score > 0 ORDER BY score DESC LIMIT " + Program.Config.BF2S_LeaderCount ); // Send response base.SendTemplateResponse("index_leaderboard", typeof(IndexModel), Model); } else { // Fetch our top 10 player list Model.Players = Database.Query("SELECT id, name, score FROM player WHERE score > 0 ORDER BY score DESC LIMIT 10"); // Fetch our cookie, which contains our personal leaderboard Pid's int[] pids = new int[0]; HttpRequest Request = Client.Request; Cookie C = Request.Request.Cookies["leaderboard"] ?? new Cookie("leaderboard", ""); // Read pids from the cookie try { // Pids are stored as xxxx|yyyyy|zzzz in the cookie if (C.Value.Length > 0) { string[] players = C.Value.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (players.Length > 0) { pids = Array.ConvertAll(players, Int32.Parse).Distinct().ToArray(); } } } catch { // Bad Cookie value, so flush it! C.Value = String.Empty; C.Path = "/"; Client.Response.SetCookie(C); } var Rows = Database.Query( String.Format("SELECT id, name, score, time, country, rank, lastonline, kills, deaths FROM player WHERE id IN ({0})", String.Join(",", pids) )); // Loop through each result, and process foreach (Dictionary<string, object> Row in Rows) { // DO Kill Death Ratio double Kills = Int32.Parse(Row["kills"].ToString()); double Deaths = Int32.Parse(Row["deaths"].ToString()); double Kdr = (Deaths > 0) ? Math.Round(Kills / Deaths, 3) : Kills; // Get Score Per Min double Score = Int32.Parse(Row["score"].ToString()); double Mins = Int32.Parse(Row["time"].ToString()) / 60; double SPM = (Mins > 0) ? Math.Round(Score / Mins, 4) : Score; int Pid = Int32.Parse(Row["id"].ToString()); // Add Result Model.MyLeaderboardPlayers.Add(new PlayerResult { Pid = Pid, Name = Row["name"].ToString(), Score = (int)Score, Rank = Int32.Parse(Row["rank"].ToString()), TimePlayed = FormatTime(Int32.Parse(Row["time"].ToString())), LastOnline = FormatDate(Int32.Parse(Row["lastonline"].ToString())), Country = Row["country"].ToString().ToUpperInvariant(), Kdr = Kdr, Spm = SPM, Status = GetOnlineStatus(Pid) }); } // Get a list of our online servers if (GamespyEmulator.IsRunning) { // Get our servers next foreach (GameServer server in MasterServer.Servers.Values) { // Add info if its online Model.Servers.Add(new Server() { AddressInfo = new IPEndPoint(server.AddressInfo.Address, server.hostport), Name = server.hostname, ImagePath = base.CorrectUrls(server.bf2_communitylogo_url, Model), MapName = server.mapname, MaxPlayers = server.maxplayers, PlayerCount = server.numplayers, MapSize = server.bf2_mapsize, GameType = BF2Server.GetGametypeString(server.gametype) }); } } // Send response base.SendTemplateResponse("index", typeof(IndexModel), Model); } } }
public override void HandleRequest(MvcRoute Route) { // NOTE: The HttpServer will handle the DbConnectException using (StatsDatabase Database = new StatsDatabase()) { if (Program.Config.BF2S_HomePageType == HomePageType.Leaderboard) { // Fetch our player list Model.Players = Database.Query( "SELECT id, name, rank, score, kills, country, time FROM player WHERE score > 0 ORDER BY score DESC LIMIT " + Program.Config.BF2S_LeaderCount ); // Send response base.SendTemplateResponse("index_leaderboard", typeof(IndexModel), Model); } else { // Fetch our top 10 player list Model.Players = Database.Query("SELECT id, name, score FROM player WHERE score > 0 ORDER BY score DESC LIMIT 10"); // Fetch our cookie, which contains our personal leaderboard Pid's int[] pids = new int[0]; HttpRequest Request = Client.Request; Cookie C = Request.Request.Cookies["leaderboard"] ?? new Cookie("leaderboard", ""); // Read pids from the cookie try { // Pids are stored as xxxx|yyyyy|zzzz in the cookie if (C.Value.Length > 0) { string[] players = C.Value.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (players.Length > 0) { pids = Array.ConvertAll(players, Int32.Parse).Distinct().ToArray(); } } } catch { // Bad Cookie value, so flush it! C.Value = String.Empty; C.Path = "/"; Client.Response.SetCookie(C); } var Rows = Database.Query( String.Format("SELECT id, name, score, time, country, rank, lastonline, kills, deaths FROM player WHERE id IN ({0})", String.Join(",", pids) )); // Loop through each result, and process foreach (Dictionary <string, object> Row in Rows) { // DO Kill Death Ratio double Kills = Int32.Parse(Row["kills"].ToString()); double Deaths = Int32.Parse(Row["deaths"].ToString()); double Kdr = (Deaths > 0) ? Math.Round(Kills / Deaths, 3) : Kills; // Get Score Per Min double Score = Int32.Parse(Row["score"].ToString()); double Mins = Int32.Parse(Row["time"].ToString()) / 60; double SPM = (Mins > 0) ? Math.Round(Score / Mins, 4) : Score; int Pid = Int32.Parse(Row["id"].ToString()); // Add Result Model.MyLeaderboardPlayers.Add(new PlayerResult { Pid = Pid, Name = Row["name"].ToString(), Score = (int)Score, Rank = Int32.Parse(Row["rank"].ToString()), TimePlayed = FormatTime(Int32.Parse(Row["time"].ToString())), LastOnline = FormatDate(Int32.Parse(Row["lastonline"].ToString())), Country = Row["country"].ToString().ToUpperInvariant(), Kdr = Kdr, Spm = SPM, Status = GetOnlineStatus(Pid) }); } // Get a list of our online servers if (GamespyEmulator.IsRunning) { // Get our servers next foreach (GameServer server in MasterServer.Servers.Values) { // Add info if its online Model.Servers.Add(new Server() { AddressInfo = new IPEndPoint(server.AddressInfo.Address, server.hostport), Name = server.hostname, ImagePath = base.CorrectUrls(server.bf2_communitylogo_url, Model), MapName = server.mapname, MaxPlayers = server.maxplayers, PlayerCount = server.numplayers, MapSize = server.bf2_mapsize, GameType = BF2Server.GetGametypeString(server.gametype) }); } } // Send response base.SendTemplateResponse("index", typeof(IndexModel), Model); } } }