public MongoDbContext(MongoDb settings) { var pack = new ConventionPack { new IgnoreIfNullConvention(true), new CamelCaseElementNameConvention(), new IgnoreExtraElementsConvention(true), new EnumRepresentationConvention(BsonType.String) }; ConventionRegistry.Register("flypackDbConventions", pack, x => true); var mongoUrl = new MongoUrl(settings.ConnectionString); var mongoSettings = MongoClientSettings.FromUrl(mongoUrl); #if DEBUG mongoSettings.ClusterConfigurator = cb => { cb.Subscribe <CommandStartedEvent>(e => { Console.WriteLine($"{e.CommandName} - {e.Command.ToJson()}"); }); }; #endif _client = new MongoClient(mongoSettings); database = _client.GetDatabase(settings.DatabaseName); }
public ActionResult SetProperty(Property property) { MongoDb.MongoConnect(property); return(View("SetProperty", property)); }
public async Task UpsertDocument_UpdateDocument_IsUpdatedCorrectly() { // Arrange var db = new MongoDb(ConnectionString, DatabaseId); var documentId = Guid.NewGuid().ToString(); var person = new PersonTest { PersonId = Guid.NewGuid(), Name = "Barney Rubble", Age = 87 }; var personEnvelope = new DocumentBase <PersonTest> { VM = person }; await db.UpsertDocument(CollectionId, documentId, personEnvelope); personEnvelope.VM.Name = "Fred Flintstone"; personEnvelope.VM.Age = 88; await db.UpsertDocument(CollectionId, documentId, personEnvelope); // Assert var doc = await db.ReadDocument <PersonTest>(CollectionId, documentId); doc.VM.Age.Should().Be(88); doc.VM.Name.Should().Be("Fred Flintstone"); doc.VM.PersonId.Should().Be(person.PersonId); }
public static List <PredictedMatch> JustTipFullSeason() { var db = new MongoDb(); //Load tipper var tipper = new Tipper.Tipper(); //Load last completed var year = tipper.League.Seasons.Where(s => s.Rounds.Any()).OrderByDescending(s => s.Year).First().Year; var completedRounds = tipper.League.Seasons.Where(s => s.Rounds.Any()) .OrderByDescending(s => s.Year) .First() .Rounds.Where(r => r.Matches.All(m => m.TotalScore() > 0)) .ToList(); var round = !completedRounds.Any() ? 0 : completedRounds.OrderByDescending(r => r.Number).First().Number; //Load Network var network = db.GetNetworks().ToList(); var first = network.First(n => n.Id == Global.NeuralNetworkId); //Neurons don't seem to plug themselves automatically after being stored. Network.PlugIn(first.ONeurons, first.HLayers, first.INeurons); tipper.Net = first; //Print results var predictions = new List <PredictedMatch>(); foreach (var r in tipper.League.Seasons.Where(s => s.Year == year).SelectMany(s => s.Rounds).Where(r => r.Number > round).ToList()) { //If Interpretation change network will need to change too predictions.AddRange(tipper.PredictWinners(r.Year, r.Number, r.IsFinal, AFLDataInterpreter.Interpretations.BespokeApiInterpretation)); } return(predictions); }
private static void Update(MongoDb db, List <Season> seasons, int year, int number) { var api = new FinalSirenApi(); var numRounds = api.GetNumRounds(year); for (var i = number; i <= numRounds; i++) { var round = api.GetRoundResults(year, i); if (seasons.All(s => s.Year != year)) { seasons.Add(new Season(year, new List <Round>())); } if (seasons.First(s => s.Year == year).Rounds.Count >= i) { seasons.First(s => s.Year == year).Rounds[i - 1] = round; } else { seasons.First(s => s.Year == year).Rounds.Add(round); } } db.UpdateSeasons(seasons); }
public void UpdateFk(String parentCollectionName, String parentPkName, String childCollectionName, String childFkName, bool clearParentPk) { var parents = MongoDb.GetCollection(parentCollectionName); var children = MongoDb.GetCollection(childCollectionName); var found = false; foreach (var parent in parents.Find(null)) { found = true; var key = parent[parentPkName]; var query = Query.EQ(childFkName, key); var update = Update.Set(childFkName, parent["_id"]); var r = children.Update(query, update, UpdateFlags.Multi); } if (!found) { throw new Exception("Unable to locate any " + parentCollectionName); } if (clearParentPk) { ClearOldPk(parentCollectionName, parentPkName); } }
private static List <Season> UpdateFrom(MongoDb db, List <Season> seasons, int year, int number) { if (seasons.Count == 1) { seasons = new List <Season>(); } Console.WriteLine(year + ", " + number); var successful = true; while (successful) { try { Update(db, seasons, year, number); } catch (Exception e) { Console.WriteLine(e.Message); successful = false; } if (successful) { //We're still getting fresh data so loop into next season: year++; number = 1; seasons.Add(new Season(year, new List <Round>())); } } return(seasons); }
public static List <Season> LoadSeasons() { var db = new MongoDb(); var seasons = db.GetSeasons() ?? new List <Season>(); return(seasons.OrderBy(s => s.Year).ToList()); }
public Tipper() { var db = new MongoDb(); League = new League(); //TODO:REMOVE League.Seasons = db.GetSeasons().Where(x => x.Year >= 2003).OrderBy(x => x.Year).ToList(); BBLSeasons = db.GetBBLSeasons().ToList(); WBBLSeasons = db.GetWBBLSeasons().ToList(); /* var playerStats = db.ReadPlayerDocument().ToList(); * foreach (var season in League.Seasons) * { * foreach (var round in season.Rounds) * { * foreach (var match in round.Matches) * { * match.HomePlayerMatches = playerStats.SelectMany(x => x.History).Where( * h => * h.Year == season.Year && h.RoundNo == round.Number && * match.Away.Equals(Util.GetTeamByName(h.Against))).ToList(); * } * } * }*/ Refresh(NumInputs, new List <int>() { DefaultHiddens }, NumOutputs); }
public HttpResponseMessage GetAllTestCases(string category = null, string name = null) { List <TestCase> testcases; if (category != null && name != null) { testcases = MongoDb.GetTestCaseByCategoryAndName(category, name); } else if (category != null) { testcases = MongoDb.GetTestCaseByCategory(category); } else if (name != null) { testcases = MongoDb.GetTestCaseByName(name); } else { testcases = MongoDb.GetAllTestCases(); } var json = JsonConvert.SerializeObject(testcases); return(new HttpResponseMessage() { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") }); }
// GET api/statistics/InterpretedData public string Get() { var db = new MongoDb(); var data = db.GetDataInterpretation().First(); return(Json.Encode(data)); }
public User Save(User user) { if (user == null) { throw new ArgumentNullException("user", "Invalid user data"); } var mongoDb = MongoDb.OpenConnection(); var data = new UserMongoMap().GetMongoMap(user); var collection = mongoDb.GetCollection <BsonDocument>(CollectionsEnum.users.ToString()); if (data.IsNew) { collection.InsertOne(data.ToBsonDocument()); return(data.GetUserModel()); } var builder = Builders <BsonDocument> .Filter; var filter = builder.Eq("_id", new BsonObjectId(data.Id)); collection.FindOneAndReplace(filter, data.ToBsonDocument()); return(data.GetUserModel()); }
public static void Update(List <Season> seasons, int year, int number) { var db = new MongoDb(); var api = new FinalSirenApi(); var newDataStillComingTroughFromApi = true; var numRounds = api.GetNumRounds(year);//TODO:speed up - maybe store in code for now, in DB later for (var i = number; (i <= numRounds && newDataStillComingTroughFromApi); i++) { var round = api.GetRoundResults(year, i); if (round.Matches.TrueForAll(m => m.HomeScore().Total() < 0.1 && m.AwayScore().Total() < 0.1) && seasons.First(s => s.Year == year).Rounds.Count == numRounds) { newDataStillComingTroughFromApi = false; } if (seasons.All(s => s.Year != year)) { seasons.Add(new Season(year, new List <Round>())); } if (seasons.First(s => s.Year == year).Rounds.Count >= i) { seasons.First(s => s.Year == year).Rounds[i - 1] = round; } else { seasons.First(s => s.Year == year).Rounds.Add(round); db.UpdateSeasons(seasons.Where(s => s.Year >= year).ToList()); } } db.UpdateSeasons(seasons.Where(s => s.Year >= year).ToList()); }
public async Task ReadDocument_DocumentExists_ReturnDocumentIsCorrect() { // Arrange var db = new MongoDb(ConnectionString, DatabaseId); var documentId = Guid.NewGuid().ToString(); var person = new PersonTest { PersonId = Guid.NewGuid(), Name = "Barney Rubble", Age = 87 }; var personEnvelope = new DocumentBase <PersonTest> { VM = person }; await db.UpsertDocument(CollectionId, documentId, personEnvelope); // Act var doc = await db.ReadDocument <PersonTest>(CollectionId, documentId); // Assert doc.Should().NotBeNull(); doc.VM.Age.Should().Be(person.Age); doc.VM.Name.Should().Be(person.Name); doc.VM.PersonId.Should().Be(person.PersonId); }
public async Task DeleteDocument_DocumentExists_DocumentIsDeleted() { // Arrange var db = new MongoDb(ConnectionString, DatabaseId); var documentId = Guid.NewGuid().ToString(); var person = new PersonTest { PersonId = Guid.NewGuid(), Name = "Barney Rubble", Age = 87 }; var personEnvelope = new DocumentBase <PersonTest>() { VM = person }; await db.UpsertDocument(CollectionId, documentId, personEnvelope); // Act await db.DeleteDocument(CollectionId, documentId); var exists = db.DocumentExists(CollectionId, documentId); // Assert exists.Should().BeFalse(); }
public CampaignController(DocumentStoreHolder holder, IEnumerable <ICharacterSheet> characterSheetTypes) { MongoDb = holder.GetDefaultDatabase(); CampaignCollection = MongoDb.GetCollection <Campaign>("CampaignCollection"); CharacterCollection = MongoDb.GetCollection <dynamic>("RpgCharModels"); CharacterSheetTypes = characterSheetTypes; }
public ICollection <string> Validate() { var errors = new List <string>(); if (MongoDb != null) { MongoDb.Validate(errors); } if (Backup != null) { Backup.Validate(errors); } if (GoogleStorage != null) { GoogleStorage.Validate(errors); } if (AzureStorage != null) { AzureStorage.Validate(errors); } if (string.Equals(Storage, "GC", StringComparison.OrdinalIgnoreCase) && string.Equals(Storage, "Azure", StringComparison.OrdinalIgnoreCase)) { errors.Add("Either Google Storage or Azure Storage must be configured."); } return(errors); }
public async Task <bool> CollectionExistsAsync(string collectionName) { var filter = new BsonDocument("name", collectionName); var collections = await MongoDb.ListCollectionsAsync(new ListCollectionsOptions { Filter = filter }); return((await collections.ToListAsync()).Any()); }
public UsuariosBusiness(MongoDb databaseContext) { _mongoDb = databaseContext; _usuariosCollection = _mongoDb.MongoDatabaseContext.GetCollection <Usuarios>(typeof(Usuarios).Name.ToLower()); _documentosBusiness = new DocumentosBusiness(databaseContext); _enderecosBusiness = new EnderecosBusiness(databaseContext); _telefonesBusiness = new TelefonesBusiness(databaseContext); }
private static void CheckDatabaseData() { const string databaseName = "aspu"; var database = new MongoDb <BlockModel>(databaseName, "blocks"); var blocks = database.Read(); var database1 = new MongoDb <ProductModel>(databaseName, "products"); var products = database1.Read(); }
public MongoDbTest() { var db = new MongoDb(ConnectionString, DatabaseId); db.DeleteCollection(NewCollectionId).Wait(); db.DeleteCollection(CollectionId).Wait(); db.CreateCollection(CollectionId).Wait(); }
protected MongoCollection<U> GetCollection(string key = "") { if (String.IsNullOrWhiteSpace(key)) { key = GetCollectionKey(); } return MongoDb.GetCollection<U>(key); }
// POST api/statistics/seasons public void Post([FromBody] object value) { var networks = ConvertToNetworkList(value); var db = new MongoDb(); db.UpdateNetworks(networks); }
public void SetUp() { string connectionString = ConfigurationManager.AppSettings["mongoConnectionString"]; _mongo = new MongoDb(connectionString, ConfigurationManager.AppSettings["mongoDatabase"]); MongoUtilities u = new MongoUtilities(_mongo); u.InitializeDatabase(); }
// GET api/statistics/InterpretedData public string Get() { var db = new MongoDb(); var data = db.GetDataInterpretation().First(); var json = JsonConvert.SerializeObject(data); return(json); }
public static void AddSalesProductReportsFromFilesToDatabase(IEnumerable<ProductReportClass> reports) { var db = new MongoDb("MarketSystem"); db.CreateCollection<ProductReportClass>("SaleProducts"); foreach (var report in reports) { db.Collections["SaleProducts"].Insert(report); } }
public HttpResponseMessage GetUniqueTestRunNames() { var uniqueNames = MongoDb.GetUniqueTestRunNames(); var json = JsonConvert.SerializeObject(uniqueNames); return(new HttpResponseMessage() { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") }); }
public HttpResponseMessage GetTestRunById(string id) { var testruns = MongoDb.GetTestRunById(id); var json = JsonConvert.SerializeObject(testruns); return(new HttpResponseMessage() { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") }); }
public static string GetSeasonShortForm(bool filter, int year) { var db = new MongoDb(); var seasons = db.GetSeasons().Where(s => (!filter || s.Year == year)); var seasonsJson = seasons.Select(s => $"{{{{Year:{s.Year}}}, {{Rounds:{s.Rounds.Count(r => !r.Matches.Any(m => m.HomeScore().Total() < 0.01 && m.AwayScore().Total() < 0.01))}}}}}"); var output = seasonsJson.Aggregate("{", (current, seasonJson) => current + (seasonJson + ",")).TrimEnd(',') + "}"; return(output + "}"); }
private async Task <MongoDb> SetupMultiplePersons() { var db = new MongoDb(ConnectionString, DatabaseId); var personA = new PersonTest { PersonId = Guid.NewGuid(), Name = "Barney Rubble", Age = 87, HomeID = new Guid("F79E323E-7BCD-4865-8BE7-5F674BE650CE") }; var personAEnvelope = new MongoDb.MongoDocumentWrapper <PersonTest> { VM = personA, ETag = Guid.NewGuid().ToString() }; var personB = new PersonTest { PersonId = Guid.NewGuid(), Name = "Wilma Flintstone", Age = 88, HomeID = new Guid("F79E323E-7BCD-4865-8BE7-5F674BE650CE") }; var personBEnvelope = new MongoDb.MongoDocumentWrapper <PersonTest> { VM = personB, ETag = Guid.NewGuid().ToString() }; var personC = new PersonTest { PersonId = Guid.NewGuid(), Name = "Wilma Flintstone", Age = 66, HomeID = new Guid("F79E323E-7BCD-4865-8BE7-5F674BE650CE") }; var personCEnvelope = new MongoDb.MongoDocumentWrapper <PersonTest> { VM = personC, ETag = Guid.NewGuid().ToString() }; var personD = new PersonTest { PersonId = Guid.NewGuid(), Name = "Wilma Flintstone", Age = 66, HomeID = new Guid("F79E323E-7BCD-4865-8BE7-5F674BE650CE") }; var personDEnvelope = new MongoDb.MongoDocumentWrapper <PersonTest> { VM = personD, ETag = Guid.NewGuid().ToString() }; await db.UpsertDocument(CollectionId, Guid.NewGuid().ToString(), personAEnvelope); await db.UpsertDocument(CollectionId, Guid.NewGuid().ToString(), personBEnvelope); await db.UpsertDocument(CollectionId, Guid.NewGuid().ToString(), personCEnvelope); await db.UpsertDocument(CollectionId, Guid.NewGuid().ToString(), personDEnvelope); return(db); }
private void LoadDataFromMongoButton_Click(object sender, EventArgs e) { this.SeedMongo(); var sqlserverDb = new SqlServerDb(); var mssqlFactory = new MsSqlModelsFactory(sqlserverDb); var mongo = new MongoDb(mssqlFactory); var mongoDb = MongoDb.GetInstance(MongoServerName, MongoDatabaseName); mongo.TransferToSqlServer(mongoDb, sqlserverDb); MessageBox.Show(DataLoadedFromMongoSuccessfully, string.Empty, MessageBoxButtons.OK); }
public static void Main(string[] args) { _db = new MongoDb<Person>(); }