private static void WriteObjectId(SqlDataReader dr, int index, BsonDocument document) { string result = (string)dr.GetValue(index); BsonObjectId bsonObjectId = BsonObjectId.Parse(result); document.Add("_id", bsonObjectId); }
public static bool operator >=( string lhs, MongoObjectId rhs ) { return(!(BsonObjectId.Parse(lhs) < rhs.BsonObjectId)); }
protected void skipBtn_Click(object sender, EventArgs e) { var queryResult = mongoCollection.Remove(Query.EQ("_id", BsonObjectId.Parse(ImgID))); //Response.Redirect(Request.RawUrl); Page_Load(null, EventArgs.Empty); }
public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options ) { BsonType bsonType = bsonReader.CurrentBsonType; switch (bsonType) { case BsonType.ObjectId: int timestamp; int machine; short pid; int increment; bsonReader.ReadObjectId(out timestamp, out machine, out pid, out increment); return(new MongoObjectId(new BsonObjectId(timestamp, machine, pid, increment))); case BsonType.String: return(new MongoObjectId(BsonObjectId.Parse(bsonReader.ReadString()))); case BsonType.Null: bsonReader.ReadNull(); return(null); default: var message = string.Format("Cannot deserialize ObjectId from BsonType: {0}", bsonType); throw new FormatException(message); } }
public static bool operator ==( string lhs, MongoObjectId rhs ) { return(object.Equals(BsonObjectId.Parse(lhs), rhs.BsonObjectId)); }
private static void WriteObjectId(PropertyInfo property, object o, BsonDocument document) { string objectId = property.GetValue(o, null).ToString(); BsonObjectId bsonObjectId = BsonObjectId.Parse(objectId); document.Add("_id", bsonObjectId); }
public ActionResult Unsubscribe(string id) { var userId = BsonObjectId.Parse(id); userRepository.RemoveById(userId); context.UserId = null; return(View("Unsubscribed")); }
public static void SaveAccessToken(AccessToken accessToken) { var accessTokenCollection = MongoDatabase.GetCollection <AccessToken>("AccessTokens"); // Remove previously set AccessTokens before setting a new one. accessTokenCollection.Remove(Query.EQ("UserId", BsonObjectId.Parse(accessToken.UserId))); accessTokenCollection.Save(accessToken); }
public static Player GetPlayer(string id) { if (string.IsNullOrEmpty(id)) { throw new Exception("id parameter cannot be null or empty"); } return(Dbh.GetCollection <Player>("Players").FindOne(Query.EQ("_id", BsonObjectId.Parse(id)))); }
public JsonResult GetPlayerRatingData(string playerId) { var chartData = new PlayerRatingChartData(); const int defaultRating = 1000; chartData.DataPoints.Add(new PlayerRatingChartDataPoint { TimeSet = new List <string>(), Rating = defaultRating }); if (playerId != null) { var playerCollection = Dbh.GetCollection <Player>("Players"); var player = playerCollection.Find(Query.EQ("_id", BsonObjectId.Parse(playerId))).FirstOrDefault(); var matches = Dbh.GetCollection <Match>("Matches") .FindAll() .SetSortOrder(SortBy.Ascending("GameOverTime")) .ToList() .Where(match => match.ContainsPlayer(playerId)) .Where(match => match.GameOverTime != DateTime.MinValue); var playedMatches = matches as List <Match> ?? matches.ToList(); double minRating = 10000; double maxRating = 0; foreach (var match in playedMatches) { var matchPlayer = match.GetPlayer(playerId); minRating = (minRating > matchPlayer.Rating) ? matchPlayer.Rating : minRating; maxRating = (maxRating < matchPlayer.Rating) ? matchPlayer.Rating : maxRating; var time = new List <string> { match.GameOverTime.ToLocalTime().Year.ToString(CultureInfo.InvariantCulture), match.GameOverTime.ToLocalTime().Month.ToString(CultureInfo.InvariantCulture), match.GameOverTime.ToLocalTime().Day.ToString(CultureInfo.InvariantCulture), match.GameOverTime.ToLocalTime().Hour.ToString(CultureInfo.InvariantCulture), match.GameOverTime.ToLocalTime().Minute.ToString(CultureInfo.InvariantCulture), match.GameOverTime.ToLocalTime().Second.ToString(CultureInfo.InvariantCulture) }; chartData.DataPoints.Add(new PlayerRatingChartDataPoint { TimeSet = time, Rating = matchPlayer.Rating }); } chartData.MinimumValue = minRating; chartData.MaximumValue = maxRating; chartData.Player = player; } return(Json(chartData, JsonRequestBehavior.AllowGet)); }
public ActionResult Delete(string id) { var currentUser = Main.Session.GetCurrentUser(); if (currentUser != null) { var matchCollection = Dbh.GetCollection <Match>("Matches"); matchCollection.Remove(Query.EQ("_id", BsonObjectId.Parse(id))); } return(new HttpStatusCodeResult(200)); }
private void SaveImageToGridFs(string label) { try { var mongoClient = new MongoClient(""); // Connection String var server = mongoClient.GetServer(); gridFSDatabase = server.GetDatabase("gridfs1"); // Database Name // Get image from URL or API WebRequest webRequest = System.Net.WebRequest.Create(ImgUrl); WebResponse webResponse = webRequest.GetResponse(); Response.Write("Response length is " + webResponse.ContentLength + " bytes"); // Copy from WebResponse to MemoryStream MemoryStream memoryStream; using (Stream responseStream = webResponse.GetResponseStream()) { memoryStream = new MemoryStream(); byte[] buffer = new byte[1024]; int byteCount; do { byteCount = responseStream.Read(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, byteCount); } while (byteCount > 0); responseStream.Close(); } // Reset to beginning of stream memoryStream.Seek(0, SeekOrigin.Begin); // Save to GridFS var gridFsInfo = gridFSDatabase.GridFS.Upload(memoryStream, ImgUrl); string gridFsImageID = gridFsInfo.Id.ToString(); gridFsCollection = gridFSDatabase.GetCollection("fs.files"); UpdateBuilder updateBuilder2 = MongoDB.Driver.Builders.Update .Set("category", "added"); mongoCollection.Update(Query.EQ("_id", BsonObjectId.Parse(ImgID)), updateBuilder2); UpdateBuilder updateBuilder = MongoDB.Driver.Builders.Update .Set("category", label); gridFsCollection.Update(Query.EQ("_id", BsonObjectId.Parse(gridFsImageID)), updateBuilder); } catch (Exception err) { Response.Write("Something went wrong: " + err.Message); } }
public void TestParse() { #pragma warning disable 618 var objectId1 = BsonObjectId.Parse("0102030405060708090a0b0c"); // lower case var objectId2 = BsonObjectId.Parse("0102030405060708090A0B0C"); // upper case Assert.True(objectId1.ToByteArray().SequenceEqual(objectId2.ToByteArray())); Assert.True(objectId1.ToString() == "0102030405060708090a0b0c"); // ToString returns lower case Assert.True(objectId1.ToString() == objectId2.ToString()); Assert.Throws <FormatException>(() => BsonObjectId.Parse("102030405060708090a0b0c")); // too short Assert.Throws <FormatException>(() => BsonObjectId.Parse("x102030405060708090a0b0c")); // invalid character Assert.Throws <FormatException>(() => BsonObjectId.Parse("00102030405060708090a0b0c")); // too long #pragma warning restore }
public void TestParse() { byte[] bytes = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; var objectId1 = BsonObjectId.Parse("0102030405060708090a0b0c"); // lower case var objectId2 = BsonObjectId.Parse("0102030405060708090A0B0C"); // upper case Assert.IsTrue(objectId1.ToByteArray().SequenceEqual(objectId2.ToByteArray())); Assert.IsTrue(objectId1.ToString() == "0102030405060708090a0b0c"); // ToString returns lower case Assert.IsTrue(objectId1.ToString() == objectId2.ToString()); Assert.Throws <FormatException>(() => BsonObjectId.Parse("102030405060708090a0b0c")); // too short Assert.Throws <FormatException>(() => BsonObjectId.Parse("x102030405060708090a0b0c")); // invalid character Assert.Throws <FormatException>(() => BsonObjectId.Parse("00102030405060708090a0b0c")); // too long }
public ActionResult Delete(string id) { var currentUser = (User)Session["User"]; if (currentUser != null) { var matchCollection = Dbh.GetCollection <Match>("Matches"); var query = Query.EQ("_id", BsonObjectId.Parse(id)); var match = matchCollection.FindOne(query); Events.SubmitEvent(EventType.MatchDelete, match, currentUser.Id); matchCollection.Remove(query); } return(RedirectToAction("Index")); }
public string GetImageUrl() { try { var url = (Url)mongoCollection.FindOneAs(typeof(Url), Query.EQ("category", "notAdded")); // This gives ImgUrl = url.image; ImgID = url._id; ImgUrlNrml = url.image; HttpWebRequest request = WebRequest.Create(ImgUrl) as HttpWebRequest; // instruct the server to return headers only request.Method = "HEAD"; // make the connection try { HttpWebResponse response = request.GetResponse() as HttpWebResponse; HttpStatusCode status = response.StatusCode; } catch (Exception) { UpdateBuilder updateBuilder2 = MongoDB.Driver.Builders.Update .Set("category", "notFound"); mongoCollection.Update(Query.EQ("_id", BsonObjectId.Parse(ImgID)), updateBuilder2); Page_Load(null, EventArgs.Empty); } if (ImgUrl.Contains("_normal")) { ImgUrl = ImgUrl.Replace("_normal", ""); } return(ImgUrl); } catch (Exception) { radioButtonList.Visible = false; btn.Visible = false; Response.Write("Db Query Error"); return("http://www.dioceseofmarquette.org/images/images/404.png"); } }
public static bool operator <=( string lhs, MongoObjectId rhs ) { if (object.ReferenceEquals(lhs, null) && object.ReferenceEquals(rhs, null)) { return(true); } if (object.ReferenceEquals(lhs, null)) { return(true); } if (object.ReferenceEquals(rhs, null)) { return(false); } return(BsonObjectId.Parse(lhs).CompareTo(rhs.BsonObjectId) <= 0); }
public void ReplayMatches() { var currentUser = (User)Session["User"]; if (currentUser != null && Settings.AdminAccounts.Contains(currentUser.Email)) { var allMatches = Dbh.GetCollection <Match>("Matches").FindAll().SetSortOrder(SortBy.Ascending("GameOverTime")); var allPlayers = Dbh.GetCollection <Player>("Players").FindAll(); var copyMatches = Dbh.GetCollection <Match>("CopyMatches"); var copyPlayers = Dbh.GetCollection <Player>("CopyPlayers"); // Empty the Copies copyMatches.RemoveAll(); copyPlayers.RemoveAll(); // Reset all Players foreach (var player in allPlayers) { player.Lost = 0; player.Won = 0; player.Played = 0; player.Rating = 1000; copyPlayers.Save(player); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// // replay each match in chronological order ///////////////////////////////////////////////////////////////////////////////////////////////////////// foreach (var match in allMatches) { // Update players from the match with players from the Db. match.RedPlayer1 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer1.Id))); if (match.CountRedPlayers() == 2) { match.RedPlayer2 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer2.Id))); } match.BluePlayer1 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer1.Id))); if (match.CountBluePlayers() == 2) { match.BluePlayer2 = copyPlayers.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer2.Id))); } // Determine the winners and the losers var winners = new Team(); var losers = new Team(); if (match.RedScore > match.BlueScore) { winners.Players.Add(match.RedPlayer1); winners.Players.Add(match.RedPlayer2); losers.Players.Add(match.BluePlayer1); losers.Players.Add(match.BluePlayer2); } else { winners.Players.Add(match.BluePlayer1); winners.Players.Add(match.BluePlayer2); losers.Players.Add(match.RedPlayer1); losers.Players.Add(match.RedPlayer2); } // Get the rating modifier match.DistributedRating = Rating.GetRatingModifier(winners.GetTeamRating(), losers.GetTeamRating()); // Propagate the rating and stats to the team members of both teams foreach (var member in winners.Players.Where(member => member.Id != null)) { member.Rating += match.DistributedRating; member.Won++; member.Played++; copyPlayers.Save(member); } foreach (var member in losers.Players.Where(member => member.Id != null)) { member.Rating -= match.DistributedRating; member.Lost++; member.Played++; copyPlayers.Save(member); } // Save the data to Db copyMatches.Save(match); } // Copy data into Production tables var matches = Dbh.GetCollection <Match>("Matches"); var players = Dbh.GetCollection <Match>("Players"); matches.RemoveAll(); players.RemoveAll(); foreach (var player in copyPlayers.FindAll()) { players.Save(player); } foreach (var match in copyMatches.FindAll()) { matches.Save(match); } } }
private Match ResolveMatch(Match match) { var redScore = match.RedScore; var blueScore = match.BlueScore; if (redScore != blueScore) { var playerCollection = Dbh.GetCollection <Player>("Players"); // Update players from the match with players from the Db. if (match.RedPlayer1.Id != null) { match.RedPlayer1 = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer1.Id))); } if (match.RedPlayer2.Id != null) { match.RedPlayer2 = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.RedPlayer2.Id))); } if (match.BluePlayer1.Id != null) { match.BluePlayer1 = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer1.Id))); } if (match.BluePlayer2.Id != null) { match.BluePlayer2 = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(match.BluePlayer2.Id))); } var currentUser = (User)Session["User"]; if (currentUser != null) { // Get the scores match.RedScore = redScore; match.BlueScore = blueScore; // Determine the winners and the losers var winners = new Team(); var losers = new Team(); if (match.RedScore > match.BlueScore) { winners.Players.Add(match.RedPlayer1); winners.Players.Add(match.RedPlayer2); losers.Players.Add(match.BluePlayer1); losers.Players.Add(match.BluePlayer2); } else { winners.Players.Add(match.BluePlayer1); winners.Players.Add(match.BluePlayer2); losers.Players.Add(match.RedPlayer1); losers.Players.Add(match.RedPlayer2); } // Get the rating modifier match.DistributedRating = Rating.GetRatingModifier(winners.GetTeamRating(), losers.GetTeamRating()); // Propagate the rating and stats to the team members of both teams foreach (var member in winners.Players.Where(member => member.Id != null)) { member.Rating += match.DistributedRating; member.Won++; member.Played++; playerCollection.Save(member); } foreach (var member in losers.Players.Where(member => member.Id != null)) { member.Rating -= match.DistributedRating; member.Lost++; member.Played++; playerCollection.Save(member); } // Update match time stats match.GameOverTime = DateTime.Now; } } return(match); }
public ActionResult GetPlayerStatistics(string playerId) { using (Profiler.Step("Calculating Player Statistics")) { if (playerId == null) { return(new HttpStatusCodeResult(403, "Invalid request")); } else { var playerCollection = Dbh.GetCollection <Player>("Players"); var matches = Dbh.GetCollection <Match>("Matches") .FindAll() .SetSortOrder(SortBy.Ascending("GameOverTime")) .ToList() .Where(match => match.ContainsPlayer(playerId)) .Where(match => match.GameOverTime != DateTime.MinValue); var playedMatches = matches as List <Match> ?? matches.ToList(); var player = playerCollection.FindOne(Query.EQ("_id", BsonObjectId.Parse(playerId))); var stats = new PlayerStatsViewModel { Player = player, PlayedMatches = playedMatches.OrderByDescending(x => x.GameOverTime), LatestMatch = playedMatches.Last() }; if (playedMatches.Count == 0) { return(Json(stats, JsonRequestBehavior.AllowGet)); } var bff = StatsControllerHelpers.GetBestFriendForever(playerId, playedMatches); var rbff = StatsControllerHelpers.GetRealBestFriendForever(playerId, playedMatches); var eae = StatsControllerHelpers.GetEvilArchEnemy(playerId, playedMatches); var preferredColor = StatsControllerHelpers.GetPreferredColor(playerId, playedMatches); var winningColor = StatsControllerHelpers.GetWinningColor(playerId, playedMatches); var highestRating = StatsControllerHelpers.GetHighestRating(playerId, playedMatches); var lowestRating = StatsControllerHelpers.GetLowestRating(playerId, playedMatches); var longestWinningStreak = StatsControllerHelpers.GetPlayersLongestWinningStreak(playerId, playedMatches); var longestLosingStreak = StatsControllerHelpers.GetPlayersLongestLosingStreak(playerId, playedMatches); foreach (var match in playedMatches) { stats.Played++; stats.Won = match.WonTheMatch(playerId) ? ++stats.Won : stats.Won; stats.Lost = !match.WonTheMatch(playerId) ? ++stats.Lost : stats.Lost; stats.Ranking = playerCollection.FindAll() .SetSortOrder(SortBy.Descending("Rating")) .Where(x => x.Played > 0 && x.Deactivated == false) .ToList() .FindIndex(x => x.Id == playerId) + 1; stats.TotalNumberOfPlayers = (int)playerCollection.Count(Query.GT("Played", 0)); } stats.Bff = bff.OrderByDescending(x => x.Value.Occurrences) .Select(x => x.Value) .FirstOrDefault(); stats.Rbff = rbff.OrderByDescending(x => x.Value.Occurrences).Select(x => x.Value).FirstOrDefault(); stats.Eae = eae.OrderByDescending(x => x.Value.Occurrences) .ThenByDescending(x => x.Value.GoalDiff) .Select(x => x.Value) .FirstOrDefault(); stats.PreferredColor = preferredColor.OrderByDescending(x => x.Value.Occurrences) .Select(x => x.Value) .FirstOrDefault(); stats.WinningColor = winningColor.OrderByDescending(x => x.Value.Occurrences) .Select(x => x.Value) .FirstOrDefault(); stats.HighestRating = highestRating; stats.LowestRating = lowestRating; stats.LongestWinningStreak = longestWinningStreak; stats.LongestLosingStreak = longestLosingStreak; return(Json(stats, JsonRequestBehavior.AllowGet)); } } }