Represents a client to MongoDB.
        private async Task MainAsync()
        {
            var connStr = "mongodb://localhost:27017";
            var client = new MongoClient(connStr);
            var db = client.GetDatabase("store");
            var col = db.GetCollection<Product>("products");
            await db.DropCollectionAsync("products");

            Random random = new Random();

            List<string> descriptions = new List<string>() { "aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj" };
            List<string> categories = new List<string>() { "sports", "food", "clothing", "electronics" };
            List<string> brands = new List<string>() { "GE", "nike", "adidas", "toyota", "mitsubishi" };

            var docs = Enumerable.Range(0, 100)
                .Select(i => new Product
                {
                    Id = i,
                    SKU = String.Format("{0:D8}", i),
                    Price = random.NextDouble() * (100 - 1) + 1,
                    Description = descriptions[random.Next(descriptions.Count)],
                    Category = categories[random.Next(categories.Count)],
                    Brand = brands[random.Next(brands.Count)],
                    Reviews = new List<Review>(),
                });
            await col.InsertManyAsync(docs);

            await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.SKU), new CreateIndexOptions() { Unique = true });
            await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Descending(x => x.Price));
            await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.Description));
            await col.Indexes.CreateOneAsync(Builders<Product>.IndexKeys.Ascending(x => x.Category).Ascending(x => x.Brand));
            await col.Indexes.CreateOneAsync("{'reviews.author':1}");
        }
        public void Post(UserModel model)
        {
            var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017");
            var mongoDbServer = mongoDbClient.GetDatabase("SocialNetworks");
            BsonArray arr = new BsonArray();            
            dynamic jobj = JsonConvert.DeserializeObject<dynamic>(model.Movies.ToString());
            foreach (var item in jobj)
            {
                foreach(var subitem in item)
                {
                    arr.Add(subitem.Title.ToString());
                }
            }

            var document = new BsonDocument
            {
                { "Facebook_ID",  model.Facebook_ID },
                { "Ime",  model.Ime  },
                { "Prezime",  model.Prezime  },
                { "Email",  model.Email  },
                { "DatumRodjenja",  model.DatumRodjenja  },
                { "Hometown", model.Hometown},
                { "ProfilePictureLink", model.ProfilePictureLink  },
                { "Movies",  arr },
            };

            var collection = mongoDbServer.GetCollection<BsonDocument>("UserInfo");
            collection.InsertOneAsync(document);
        }
Esempio n. 3
0
        public IMongoDatabase GetDatabase()
        {
            var client = new MongoClient(this.ConnectionString);
            var db = client.GetDatabase(this.DatabaseName);

            return db;
        }
 public TodoItemRepository(string mongoConnection, string databaseName)
 {
     collectionName = "todoitems";
     var client = new MongoClient(mongoConnection);
     this.database = client.GetDatabase(databaseName);
     this.collection = database.GetCollection<TodoItem>(collectionName);
 }
Esempio n. 5
0
 private MongoDatabase getDatabase()
 {
     var connectionString = "mongodb://*****:*****@ds047387.mongolab.com:47387/cards";
     var client = new MongoClient(connectionString);
     var server = client.GetServer();
     return server.GetDatabase("cards");
 }
Esempio n. 6
0
 public Logger(string logger)
 {
     var client = new MongoClient(Properties.Settings.Default.Mongo_log);
     _db = client.GetDatabase("patientcarelog");
     _logCollection = _db.GetCollection<BsonDocument>("Logs");
     _logger = logger;
 }
Esempio n. 7
0
 public static MongoCollection<BsonDocument> GetCollection(string collectionName)
 {
     var mongoclient = new MongoClient(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
         var server = mongoclient.GetServer();
         var MongoDatabase = server.GetDatabase("CVServicePoc");
         return MongoDatabase.GetCollection(collectionName);
 }
 public static MongoDbWorkflowStore MongoDbStore()
 {
     var client = new MongoClient("mongodb://localhost");
     var server = client.GetServer();
     var database = server.GetDatabase("StatelessWorkflowTest");
     return new MongoDbWorkflowStore(database);
 }
Esempio n. 9
0
 public MongoDbBase(string connectionString, string database)
 {
     this.connectionString = connectionString;
     this.database = database;
     Client = new MongoClient(connectionString);
     Database = Client.GetDatabase(database);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MongoSystemEventLogger"/> class.
 /// </summary>
 /// <param name="configuration">The configuration options.</param>
 public MongoSystemEventLogger(IMongoConfiguration configuration)
 {
     this.Configuration = configuration;
     MongoClient client = new MongoClient(configuration.ToMongoClientSettings());
     this.Server = client.GetServer();
     this.Database = this.Server.GetDatabase(configuration.Database);
 }
Esempio n. 11
0
        static async Task MainAsync(string[] args)
        {
            var urlString = "mongodb://localhost:27017";
            var client = new MongoClient(urlString);
            var db = client.GetDatabase("students");
            var collection = db.GetCollection<BsonDocument>("grades");
            var filter = new BsonDocument("type","homework");
           // var count = 0;
            var sort = Builders<BsonDocument>.Sort.Ascending("student_id").Ascending("score");
            var result = await collection.Find(filter).Sort(sort).ToListAsync();
           var previous_id=-1 ;
           var student_id=-1;
            int count = 0;
            foreach (var doc in result)         
            {
                
                student_id = (int)doc["student_id"];
                    //Console.WriteLine(student_id);
                if (student_id != previous_id)
                {
                    count++;
                    previous_id = student_id;
                    Console.WriteLine("removing :{0} ", doc);
                   // await collection.DeleteOneAsync(doc);

                    await collection.DeleteManyAsync(doc);
                }



              // process document
            }
            Console.WriteLine(count);
            //Console.WriteLine(coll.FindAsync<"">);
        }
Esempio n. 12
0
		public async void TestMongoDB()
		{
			const string connectionString = "mongodb://localhost";
			MongoClient client = new MongoClient(connectionString);
			IMongoDatabase database = client.GetDatabase("test");
			IMongoCollection<Unit> collection = database.GetCollection<Unit>("Unit");

			World world = World.Instance;

			// 加载配置
			world.AddComponent<ConfigComponent>();
			world.AddComponent<EventComponent<EventAttribute>>();
			world.AddComponent<TimerComponent>();
			world.AddComponent<UnitComponent>();
			world.AddComponent<FactoryComponent<Unit>>();
			world.AddComponent<BehaviorTreeComponent>();
			world.AddComponent<NetworkComponent>();
			world.Load();

			Unit player1 = world.GetComponent<FactoryComponent<Unit>>().Create(UnitType.GatePlayer, 1);
			player1["hp"] = 10;

			await collection.InsertOneAsync(player1);

			Unit player3 = player1.Clone();

			Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player3));

			//Thread.Sleep(20 * 1000);
			//world.Load();
			//
			//Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player2));
		}
Esempio n. 13
0
 /// <summary />
 public PatientRepository()
 {
     var client = new MongoClient(ConfigurationManager.ConnectionStrings["Mongo_patientcare_datamock"].ConnectionString);
     _log = new Logger("WebAPI : PatientRepository");
     _db = client.GetDatabase("patientcare_datamock");
     _patients = _db.GetCollection<BsonDocument>("Patients");
 }
Esempio n. 14
0
        private void button10_Click(object sender, EventArgs e)
        {
            var client = new MongoClient("mongodb://localhost");
            var database = client.GetDatabase("docs");
            var fs = new GridFSBucket(database);

            //var aaa = fs.Find()
            var test = fs.DownloadAsBytesByName("Muzika");

            MemoryStream memStream = new MemoryStream(test);

            //OpenFileDialog open = new OpenFileDialog();
            //open.Filter = "Audio File (*.mp3;*.wav)|*.mp3;*.wav;";
            //if (open.ShowDialog() != DialogResult.OK) return;

            DisposeWave();

               // if (open.FileName.EndsWith(".mp3"))
               // {
                NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(memStream));
                stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
               // }
               // else if (open.FileName.EndsWith(".wav"))
            //{
            //    NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(open.FileName));
            //    stream = new NAudio.Wave.BlockAlignReductionStream(pcm);
            //}
            //else throw new InvalidOperationException("Not a correct audio file type.");

            output = new NAudio.Wave.DirectSoundOut();
            output.Init(stream);
            output.Play();
        }
    static void Main()
    {
        var client = new MongoClient("mongodb://localhost/");
        var server = client.GetServer();
        var dictionaryDb = server.GetDatabase("Dictionary");
        var english = dictionaryDb.GetCollection("English");

        Console.WriteLine("Enter command - Add, Change, Find or Exit");
        string command = Console.ReadLine();
        while (command != exit)
        {
            if (command == add)
            {
                AddToDictionary(english);
            }
            else if (command == change)
            {
                ChangeTranslation(english);
            }
            else if (command == find)
            {
                ShowTranslation(english);
            }
            else if (command != exit)
            {
                Console.WriteLine("Enter invalid command. Please try again.");
            }

            Console.WriteLine("Enter command - Add, Change, Find or Exit");
            command = Console.ReadLine();
        }
    }
Esempio n. 16
0
 public MongoDbDriver(string connectionString, string collectionName)
 {
     var builder = new SqlConnectionStringBuilder(connectionString);
     _client = new MongoClient(builder.DataSource);
     _database = _client.GetDatabase(builder.InitialCatalog);
     _collectionName = collectionName;
 }
        public async Task<UserModel> Get(string Facebook_ID)
        {
            var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017");
            var mongoDbServer = mongoDbClient.GetDatabase("SocialNetworks");
            string facebookID = '"' + Facebook_ID + '"';

            UserModel user = new UserModel();
            int i = 0;
            var collection = mongoDbServer.GetCollection<BsonDocument>("UserInfo");
            var filter = Builders<BsonDocument>.Filter.Eq("Facebook_ID", facebookID);
            var result = await collection.Find(filter).ToListAsync();
            foreach (BsonDocument item in result)
            {
                user.Facebook_ID = item.GetElement("Facebook_ID").Value.ToString();
                user.Ime = item.GetElement("Ime").Value.ToString();
                user.Prezime = item.GetElement("Prezime").Value.ToString();
                user.Email = item.GetElement("Email").Value.ToString();
                user.DatumRodjenja = item.GetElement("DatumRodjenja").Value.ToString();
                user.Hometown = item.GetElement("Hometown").Value.ToString();
                user.ProfilePictureLink = item.GetElement("ProfilePictureLink").Value.ToString();
              //  foreach (var movie in item.GetElement("Movies").Value.AsBsonArray)
              //  {
              //      user.Movies[i] = movie.ToString();
              //      i++;
              //  }
                i = 0;
                user._id = item.GetElement("_id").Value.ToString();

            }
            var json = new JavaScriptSerializer().Serialize(user);
            return user;
        }
Esempio n. 18
0
    public bool IsRestored(string connectionName)
    {
      MongoServer server = null;
      var connectionString = ConfigurationManager.ConnectionStrings[connectionName]?.ConnectionString;

      if (string.IsNullOrEmpty(connectionString))
      {
        return false;
      }

      try
      {
        var mongoUrl = new MongoUrl(connectionString);
        var mongoClient = new MongoClient(mongoUrl);
        server = mongoClient.GetServer();

        return server.GetDatabase(mongoUrl.DatabaseName).CollectionExists(MongoRestoreSettings.RestoredDbTokenCollection);
      }
      catch (FormatException ex)
      {
        Log.Error("Wrong connection string format", ex, this);
        throw;
      }
      finally
      {
        server?.Disconnect();
      }
    }
Esempio n. 19
0
 public MongoDatabase GetMongoContext()
 {
     MongoClient client = new MongoClient(path);
     MongoServer server = client.GetServer();
     MongoDatabase dbContext = server.GetDatabase("mongotelerikchat");
     return dbContext;
 }
Esempio n. 20
0
 public BaseRepository(string collection)
 {
     _collectionName = collection;
     var client = new MongoClient(ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString);
     var db = client.GetServer().GetDatabase(ConfigurationManager.ConnectionStrings["mongodb"].ProviderName);
     _collection = db.GetCollection(_collectionName);
 }
Esempio n. 21
0
        public static int Main(string[] args)
        {
            var client = new MongoClient("");
            var db = client.GetDatabase("guess-what");
            var templateCollection = db.GetCollection<BsonDocument>("templates");
            // Use this to delete single items or spam:

            // templateCollection.DeleteOne(new BsonDocument(new BsonElement("_id", BsonValue.Create("Zp-ifMYR_0W6D0GwKsuoSw"))));
            // templateCollection.DeleteOne(new BsonDocument(new BsonElement("_id", BsonValue.Create("Ss0ISYQbSEyUsYVnMjbDAw"))));

            /*
            var regex = new Regex("^<a href=\"http://.*#\\d*\">.*</a>,$");
            foreach (var template in templateCollection.Find(new BsonDocument()).ToList())
            {
                var description = template.GetElement("Description").Value.ToString().Trim();
                if (regex.Matches(description).Count > 0)
                {
                    templateCollection.DeleteOne(new BsonDocument (template.GetElement("_id")));
                }
                else
                {
                    Console.WriteLine("OK  :" + description);
                }
            }
            */
            Console.WriteLine("END.");
            Console.ReadLine();
            return 0;
        }
Esempio n. 22
0
 private MongoCollection<BsonDocument> GetMongoCollection()
 {
     var client = new MongoClient(_connectionString);
     var db = client.GetServer().GetDatabase(new MongoUrl(_connectionString).DatabaseName);
     var collection = db.GetCollection(_collectionName);
     return collection;
 }
Esempio n. 23
0
        public async Task<ActionResult> AddWord()
        {
            var client = new MongoClient(_connection);
            var db = client.GetDatabase(_database);

            var words = db.GetCollection<BsonDocument>("Word");

            var word1 = new Word
            {
                Text = "Ape",
                Type = Enums.WordType.Noun.ToString()
            };

            var bsonObject = word1.ToBsonDocument();

            try
            {
                await words.InsertOneAsync(bsonObject);
            }
            catch (Exception ex)
            {
                return Json(ex.Message, JsonRequestBehavior.AllowGet);
            }

            return Json("success", JsonRequestBehavior.AllowGet);
        }
 public static void EstablishConnection()
 {
     client = new MongoClient(connectionString);
     server = client.GetServer();
     database = server.GetDatabase(DbName);
     entries = database.GetCollection<JSonReport>(collectionName);
 }
        public static bool InitMongoDB(this Funq.Container container)
        {
            try
            {
                // Register the MySql Database Connection Factory
                var mongoDbConnectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
                var client = new MongoClient(mongoDbConnectionString);
                var server = client.GetServer();
                var database = server.GetDatabase("hello_world");
                container.Register<MongoDatabase>(c => database);

                BsonClassMap.RegisterClassMap<World>(cm => {
                    cm.MapProperty(c => c.id);
                    cm.MapProperty(c => c.randomNumber);
                });

                BsonClassMap.RegisterClassMap<Fortune>(cm => {
                    cm.MapProperty(c => c.id);
                    cm.MapProperty(c => c.message);
                });

                // Create needed tables in MySql Server if they do not exist
                return database.CreateWorldTable() && database.CreateFortuneTable();
            }
            catch
            {
                // Unregister failed database connection factory
                container.Register<MongoDatabase>(c => null);

                return false;
            }

        }
 static MongoRepositoryContext() {
     settings = new MongoRepositorySettings();
     var url = new MongoUrl(ConfigurationManager.ConnectionStrings["SysDB"].ConnectionString);
     client = new MongoClient(url);
     server = client.GetServer();
     database = server.GetDatabase(url.DatabaseName);
 }
Esempio n. 27
0
        public MongoContext()
        {
            var client = new MongoClient(ConfigurationManager.ConnectionStrings[DATABASE].ConnectionString);
            var server = client.GetServer();

            _database = server.GetDatabase(DATABASE);
        }
Esempio n. 28
0
 public MongoUtil()
 {
     connectionString = "mongodb://localhost";
     client  = new MongoClient(connectionString);
     server = client.GetServer();
     database = server.GetDatabase("testwechat");
 }
        public void Connect(string name = DefaultDbName)
        {
            var client = new MongoClient(DefaultConnectionString);
            var server = client.GetServer();

            this.Database = server.GetDatabase(name);
        }
Esempio n. 30
0
        private void ConfigurePersistence()
        {
            var mongoDbConnectionString = ConfigurationManager.ConnectionStrings["Merp-Registry-EventStore"].ConnectionString;
            var mongoDbDatabaseName     = MongoDB.Driver.MongoUrl.Create(mongoDbConnectionString).DatabaseName;
            var mongoClient             = new MongoDB.Driver.MongoClient(mongoDbConnectionString);

            Container.RegisterInstance(mongoClient.GetDatabase(mongoDbDatabaseName));
            Container.RegisterType <IEventStore, Memento.Persistence.MongoDB.MongoDbEventStore>();
            Container.RegisterType <IRepository, Memento.Persistence.Repository>();
        }
Esempio n. 31
0
        protected override void ConfigureEventStore()
        {
            var mongoDbConnectionString = Configuration.GetConnectionString("OnTime-TaskManagement-EventStore");
            var mongoDbDatabaseName     = MongoDB.Driver.MongoUrl.Create(mongoDbConnectionString).DatabaseName;
            var mongoClient             = new MongoDB.Driver.MongoClient(mongoDbConnectionString);

            Services.AddSingleton(mongoClient.GetDatabase(mongoDbDatabaseName));
            Services.AddTransient <IEventStore, MementoFX.Persistence.MongoDB.MongoDbEventStore>();
            Services.AddTransient <IRepository, MementoFX.Persistence.Repository>();
        }
Esempio n. 32
0
        private void LoadDesherbage()
        {
            var collDesherbage = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio").GetCollection <Desherbage>("Desherbage");
            var l = collDesherbage.Find(_ => true).SortByDescending(bson => bson.dt).ToList();

            dgvDesherbage.DataSource = l;
            dgvDesherbage.AutoResizeColumns();
            dgvDesherbage.Columns["_id"].Visible      = false;
            dgvDesherbage.Columns["idNotice"].Visible = false;
        }
Esempio n. 33
0
    public static void Set(MongoDB.Driver.MongoClient c, String k, BsonDocument v)
    {
        var    db     = c.GetServer().GetDatabase("db");
        var    coll   = db.GetCollection(k);
        Entity entity = new Entity {
            data = v, _id = k
        };

        coll.Save(entity);
    }
Esempio n. 34
0
        private void btnEnregistrerNotice_Click(object sender, EventArgs e)
        {
            Notice notice = ctrlNotices1.GetNotice();

            if (notice != null)
            {
                var coll = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio").GetCollection <Notice>("Notice");
                coll.ReplaceOne(Builders <Notice> .Filter.Eq(a => a._id, notice._id), notice);
            }
        }
        public ConfigItemRepository()
        {
            string connectionString =
                ConfigurationManager.ConnectionStrings["MongoDb"].ConnectionString;

            var            mongoClient = new MongoDB.Driver.MongoClient(connectionString);
            IMongoDatabase database    = mongoClient.GetDatabase("ConfigAdmin");

            this.itemRepository = database.GetCollection <ConfigItem>("ConfigItems");
        }
Esempio n. 36
0
        public DTOFigureTemplate[] AllFigures()
        {
            var client = new MongoDB.Driver.MongoClient("mongodb://*****:*****@gameoflife-shard-00-00-iohzq.mongodb.net:27017,gameoflife-shard-00-01-iohzq.mongodb.net:27017,gameoflife-shard-00-02-iohzq.mongodb.net:27017/admin?replicaSet=GameOfLife-shard-0&ssl=true");

            var database   = client.GetDatabase("gameOfLife");
            var collection = database.GetCollection <BsonDocument>("Figures");

            var result = collection.Find(Builders <BsonDocument> .Filter.Empty).ToList();

            return(result.Select(doc => BsonSerializer.Deserialize <DTOFigureTemplate>(doc)).ToArray());
        }
Esempio n. 37
0
        public DaoAtributo()
        {
            var cliente = new MongoDB.Driver.MongoClient(connect);

            server = cliente.GetServer();

            database = server.GetDatabase("sojaBD");


            coll = database.GetCollection <Atributo>("atrib_values");
        }
Esempio n. 38
0
        public void InsertBson()
        {
            MongoDB.Driver.MongoClient mc = new MongoDB.Driver.MongoClient();
            var db    = mc.GetDatabase("Test");
            var col   = db.GetCollection <BsonDocument>("Brand");
            var brand = new BsonDocument {
                { "Id", 2 }, { "Name", "test" }
            };

            col.InsertOne(brand);
        }
Esempio n. 39
0
        public DaoCaso()
        {
            var cliente = new MongoDB.Driver.MongoClient(connect);

            server = cliente.GetServer();

            database = server.GetDatabase("sojaBD");


            coll = database.GetCollection <Caso>("casos");
        }
Esempio n. 40
0
        public void Insert()
        {
            MongoDB.Driver.MongoClient mc = new MongoDB.Driver.MongoClient();
            var db    = mc.GetDatabase("Test");
            var col   = db.GetCollection <Brand>("Brand");
            var brand = new Brand {
                Id = 67, Name = "test"
            };

            col.InsertOne(brand);
        }
Esempio n. 41
0
        // Connect to Mongo
        public void connect(MongoRequest request)
        {
            // If any of the parameters are empty, check if the appropriate environment variable is there

            LambdaLogger.Log("Contacting mongo");

            if (dbClient == null)
            {
                dbClient = new MongoDB.Driver.MongoClient(request.connectionString);
            }
        }
Esempio n. 42
0
        public List <Emprunt> TrouverEmprunt()
        {
            var collEmprunt = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio").GetCollection <Emprunt>("Emprunt");

            return(collEmprunt.Find(
                       Builders <Emprunt> .Filter.And(
                           Builders <Emprunt> .Filter.Eq(a => a.idLecteur, _id),
                           Builders <Emprunt> .Filter.Eq(a => a.etat, 1)
                           )
                       ).ToList());
        }
        public EmployeeValidator()
        {
            var cs     = string.Format("mongodb://{0}:{1}@{2}", Properties.Settings.Default.username, Properties.Settings.Default.pwd, Properties.Settings.Default.server);
            var client = new MongoDB.Driver.MongoClient(cs);

            _db = client.GetDatabase("Common");

            _specialities = _db.GetCollection <Speciality>("Specialities").Find(x => true).ToList();
            _positions    = _db.GetCollection <Position>("Positions").Find(x => true).ToList();
            _duties       = _db.GetCollection <Duty>("Duties").Find(x => true).ToList();
            _emails       = _db.GetCollection <Employee>("Employees").Find(x => true).Project <Employee>(Builders <Employee> .Projection.Include(x => x.ContactInfo)).ToList().Select(x => x.ContactInfo.EMail).ToList();
        }
Esempio n. 44
0
        public static List <LecteurResult> TrouverLecteursParSearch(string search)
        {
            List <LecteurResult> result = new List <LecteurResult>();
            var db = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio");
            var s  = new MongoDB.Bson.BsonRegularExpression(search, "/i");

            foreach (InfoLecteur il in db.GetCollection <InfoLecteur>("InfoLecteur").Find(
                         Builders <InfoLecteur> .Filter.And(
                             Builders <InfoLecteur> .Filter.Eq(a => a.localisation, Properties.Settings.Default.Localisation),
                             Builders <InfoLecteur> .Filter.Or(
                                 Builders <InfoLecteur> .Filter.Regex(a => a.nom, s),
                                 Builders <InfoLecteur> .Filter.Regex(a => a.prénom, s),
                                 Builders <InfoLecteur> .Filter.Regex(a => a.commentaires, s)
                                 )
                             )
                         ).ToList())
            {
                LecteurResult lr = new LecteurResult()
                {
                    infoLecteur = il,
                    lecteur     = db.GetCollection <Lecteur>("Lecteur").Find(Builders <Lecteur> .Filter.Eq(a => a._id, il.lecteurId)).FirstOrDefault()
                };
                result.Add(lr);
            }

            // Rechercher par titre
            foreach (Lecteur lecteur in db.GetCollection <Lecteur>("Lecteur").Find(Builders <Lecteur> .Filter.Regex(a => a.titre, s)).ToList())
            {
                foreach (InfoLecteur il in db.GetCollection <InfoLecteur>("InfoLecteur").Find(Builders <InfoLecteur> .Filter.Eq(a => a.lecteurId, lecteur._id)).ToList())
                {
                    if (result.Find(a => a.infoLecteur._id == il._id) == null)
                    {
                        result.Add(new LecteurResult()
                        {
                            infoLecteur = il, lecteur = lecteur
                        });
                    }
                }
            }

            result.Sort((a, b) => {
                if (a.infoLecteur.nom.ToLower() != b.infoLecteur.nom.ToLower())
                {
                    return(a.infoLecteur.nom.ToLower().CompareTo(b.infoLecteur.nom.ToLower()));
                }
                else
                {
                    return(a.infoLecteur.prénom.ToLower().CompareTo(b.infoLecteur.prénom.ToLower()));
                }
            });

            return(result);
        }
Esempio n. 45
0
    public static Object Get(MongoDB.Driver.MongoClient c, String k)
    {
        var db    = c.GetServer().GetDatabase("db");
        var coll  = db.GetCollection(k);
        var query = Query <Entity> .EQ(e => e._id, k);

        var entity = coll.FindOne(query);
        var v      = entity.GetElement("data");

        //return read_string.invoke(v.Value.ToString());
        return(v.Value);
    }
Esempio n. 46
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            // Ajouter ou supprimer un exemplaire
            var           collNotice  = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio").GetCollection <Notice>("Notice");
            var           collEmprunt = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio").GetCollection <Emprunt>("Emprunt");
            List <Notice> tmp         = collNotice.Find(new BsonDocument("exemplaires.codeBarre", txtNewExplaire.Text)).ToList();

            if (tmp != null && tmp.Count == 1)
            {
                // Cet exemplaire est-il disponible?
                List <Emprunt> emprunts = collEmprunt.Find(
                    Builders <Emprunt> .Filter.And(
                        Builders <Emprunt> .Filter.Eq(a => a.IdExemplaire, tmp[0].exemplaires.Find(a => a.codeBarre == txtNewExplaire.Text)._id),
                        Builders <Emprunt> .Filter.Eq(a => a.etat, 1)
                        )
                    ).ToList();
                if (emprunts == null || emprunts.Count == 0)
                {
                    // L'ajouter pour ce lecteur
                    Emprunt emprunt = new Emprunt()
                    {
                        idLecteur        = m_lecteurId,
                        IdExemplaire     = tmp[0].exemplaires.Find(a => a.codeBarre == txtNewExplaire.Text)._id,
                        etat             = 1,
                        dateEmprunt      = DateTime.Now,
                        dateRetourPrévue = DateTime.Now.AddDays(21)
                    };
                    collEmprunt.InsertOne(emprunt);
                    FillPrêts();
                }
                else if (emprunts.Count > 0)
                {
                    // Est-ce le lecteur en cours
                    if (emprunts[0].idLecteur == m_lecteurId)
                    {
                        // Le supprimer de la liste des emprunts de ce lecteur
                        collEmprunt.UpdateOne(Builders <Emprunt> .Filter.Eq(a => a._id, emprunts[0]._id),
                                              Builders <Emprunt> .Update.Set(a => a.etat, 2).CurrentDate(a => a.dateRetourEffective));
                        FillPrêts();
                    }
                    else
                    {
                        // Retrouver le lecteur
                        LecteurResult lr = Lecteur.TrouverLecteurParId(emprunts[0].idLecteur);
                        if (lr != null)
                        {
                            MessageBox.Show($"Ce document est déjà emprunté par {lr.infoLecteur.nom} {lr.infoLecteur.prénom} ({lr.lecteur.titre})");
                        }
                    }
                }
            }
            txtNewExplaire.SelectAll();
        }
        public void Setup()
        {
            var client = new MongoClient();
            var db     = client.GetDatabase("TestDb");

            _collection = db.GetCollection <GeoIp>("TestCollection2");

            var oldClient = new MongoDB.Driver.MongoClient("mongodb://localhost:27017");
            var oldDb     = oldClient.GetDatabase("TestDb");

            _oldCollection = oldDb.GetCollection <GeoIp>("TestCollection2");
        }
Esempio n. 48
0
        public void Read()
        {
            MongoDB.Driver.MongoClient mc = new MongoDB.Driver.MongoClient();
            var db     = mc.GetDatabase("Test");
            var col    = db.GetCollection <Brand>("Brand");
            var filter = Builders <Brand> .Filter.Eq("Id", 1);

            var projection = Builders <Brand> .Projection.Include("Name");

            var sort = Builders <Brand> .Sort.Descending("Name");

            var brand = col.Find(filter).Project(projection).Sort(sort);
        }
Esempio n. 49
0
 private void supprimerToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (dgvNotices.SelectedRows.Count > 0)
     {
         if (MessageBox.Show("Confirmez-vous la suppression ?", "Suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
         {
             var    coll   = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio").GetCollection <Notice>("Notice");
             Notice notice = ((List <Notice>)dgvNotices.DataSource)[dgvNotices.SelectedRows[0].Index];
             coll.DeleteOne(Builders <Notice> .Filter.Eq(a => a._id, notice._id));
             btnSearch_Click(null, null);
         }
     }
 }
Esempio n. 50
0
        void FillPrêts()
        {
            flowLayoutPanel1.Controls.Clear();
            // Retrouver les prêts en cours du lecteur
            var            collNotice  = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio").GetCollection <Notice>("Notice");
            var            collEmprunt = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio").GetCollection <Emprunt>("Emprunt");
            List <Emprunt> emprunts    = collEmprunt.Find(
                Builders <Emprunt> .Filter.And(
                    Builders <Emprunt> .Filter.Eq(a => a.idLecteur, m_lecteur.infoLecteur._id),
                    Builders <Emprunt> .Filter.Eq(a => a.etat, 1)
                    )
                ).ToList();

            foreach (Emprunt e in emprunts)
            {
                List <Notice> tmp = collNotice.Find(new BsonDocument("exemplaires._id", e.IdExemplaire)).ToList();
                if (tmp != null && tmp.Count > 0)
                {
                    ctrlPret p = new ctrlPret();
                    p.txtTitre.Text      = tmp[0].titre;
                    p.txtAuteur.Text     = tmp[0].auteur;
                    p.txtExemplaire.Text = tmp[0].exemplaires.Find(a => a._id == e.IdExemplaire).codeBarre;
                    p.txtDatepret.Text   = e.dateEmprunt.ToString("dd/MM/yyyy");
                    p.txtDateRetour.Text = e.dateRetourPrévue.ToString("dd/MM/yyyy");
                    p.Tag          = e.IdExemplaire;
                    p.RetourEvent += P_RetourEvent;
                    flowLayoutPanel1.Controls.Add(p);
                }
                else
                {
                    ctrlPret p = new ctrlPret();
                    p.txtTitre.Text      = "!!Sans notice";
                    p.txtAuteur.Text     = "N/A";
                    p.txtExemplaire.Text = "N/A";
                    p.txtDatepret.Text   = e.dateEmprunt.ToString("dd/MM/yyyy");
                    p.txtDateRetour.Text = e.dateRetourPrévue.ToString("dd/MM/yyyy");
                    p.Tag          = ObjectId.Empty;
                    p.RetourEvent += P_RetourEvent;
                    flowLayoutPanel1.Controls.Add(p);
                }
            }
            if (flowLayoutPanel1.Controls.Count > 1)
            {
                lblExemplaires.Text = $"{flowLayoutPanel1.Controls.Count} emprunts";
            }
            else
            {
                lblExemplaires.Text = $"{flowLayoutPanel1.Controls.Count} emprunt";
            }
        }
        public DbAppTenantResolver(
            ILoggerFactory loggerFactory
            )
            : base(loggerFactory)
        {
            //this.tenants = options.Value.Tenants;
            var client = new MongoDB.Driver.MongoClient("mongodb://localhost"); // mongodb://admin:abc123!@localhost/database

            MongoDB.Driver.IMongoDatabase _database = client.GetDatabase("mydb");

            var collection = _database.GetCollection <AppTenant>("tenants");

            this.tenants = collection.Find(Builders <AppTenant> .Filter.Empty).ToList();
        }
        async public Task <List <Message> > GetLatestDataAsync()
        {
            var client            = new MongoDB.Driver.MongoClient(_config.GetConnectionString("socialEvolutionConnectionString"));
            var database          = client.GetDatabase("socialEvolutionDb");
            var messageCollection = database.GetCollection <Message>(messagesCollectionName);
            var messagesListChunk = await messageCollection
                                    .Find(x => true)
                                    .Skip(latestIndex)
                                    .Limit(step)
                                    .ToListAsync();

            latestIndex += step;
            return(messagesListChunk);
        }
Esempio n. 53
0
        public MongoClient(object connectionStringOrOptions)
        {
            BlendedJSEngine.Clients.Value.Add(this);
            _connectionString = connectionStringOrOptions is string s ? s : connectionStringOrOptions.GetProperty("connectionString").ToStringOrDefault();
            _client           = new MongoDB.Driver.MongoClient(_connectionString.ToStringOrDefault());
            string databaseName = MongoUrl.Create(_connectionString.ToStringOrDefault()).DatabaseName;

            foreach (var collectionName in _client.GetDatabase(databaseName).ListCollections().ToList())
            {
                string name       = collectionName.GetValue("name").ToString();
                var    collection = _client.GetDatabase(databaseName).GetCollection <BsonDocument>(name);
                this[name] = new MongoCollection(name, collection, _console);
            }
        }
Esempio n. 54
0
        private MongoClient CreateClient(string connectionString)
        {
            void SocketConfigurator(Socket s) => s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

            var settings = MongoClientSettings.FromConnectionString(connectionString);

            settings.SocketTimeout         = TimeSpan.FromSeconds(60);
            settings.MaxConnectionIdleTime = TimeSpan.FromSeconds(60);
            settings.ClusterConfigurator   = builder =>
                                             builder.ConfigureTcp(tcp => tcp.With(socketConfigurator: (Action <Socket>)SocketConfigurator));
            var mongoclient = new MongoDB.Driver.MongoClient(settings);

            return(mongoclient);
        }
Esempio n. 55
0
        public static LecteurResult TrouverLecteurParId(ObjectId id)
        {
            var           db     = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio");
            LecteurResult result = new LecteurResult()
            {
                infoLecteur = db.GetCollection <InfoLecteur>("InfoLecteur").Find(a => a._id == id /*&& a.deleted == false*/).FirstOrDefault()
            };

            if (result.infoLecteur != null)
            {
                result.lecteur = db.GetCollection <Lecteur>("Lecteur").Find(a => a._id == result.infoLecteur.lecteurId /*&& a.deleted == false*/).FirstOrDefault();
            }
            return(result);
        }
Esempio n. 56
0
        public static LecteurResult TrouverLecteurParId(ObjectId id)
        {
            var           db     = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio");
            LecteurResult result = new LecteurResult()
            {
                infoLecteur = db.GetCollection <InfoLecteur>("InfoLecteur").Find(Builders <InfoLecteur> .Filter.Eq(a => a._id, id)).FirstOrDefault()
            };

            if (result.infoLecteur != null)
            {
                result.lecteur = db.GetCollection <Lecteur>("Lecteur").Find(Builders <Lecteur> .Filter.Eq(a => a._id, result.infoLecteur.lecteurId)).FirstOrDefault();
            }
            return(result);
        }
        public CachingMongoDbAppTenantResolver(
            IMemoryCache cache,
            ILoggerFactory loggerFactory,
            IOptions <MultitenancyOptions> options)
            : base(cache, loggerFactory)
        {
            //this.tenants = options.Value.Tenants;
            var client = new MongoDB.Driver.MongoClient("mongodb://localhost"); // mongodb://admin:abc123!@localhost

            MongoDB.Driver.IMongoDatabase _database = client.GetDatabase("kiralikbul");

            var collection = _database.GetCollection <AppTenant>("tenants");

            this.tenants = collection.Find(Builders <AppTenant> .Filter.Empty).ToList();
        }
Esempio n. 58
0
        public void Init(ObjectId lecteur)
        {
            LecteurResult lr = Lecteur.TrouverLecteurParId(lecteur);

            if (lr != null)
            {
                var db = new MongoDB.Driver.MongoClient(Properties.Settings.Default.MongoDB).GetDatabase("wfBiblio");
                infoLecteurBindingSource.DataSource = db.GetCollection <InfoLecteur>("InfoLecteur").Find(a => a.lecteurId == lr.lecteur._id).ToList();
                lecteurBindingSource.DataSource     = new List <Lecteur>()
                {
                    lr.lecteur
                };
                lecteurBindingSource.Position = 0;
            }
        }
        public void PersistData(List <Message> messages)
        {
            var client             = new MongoDB.Driver.MongoClient(_config.GetConnectionString("socialEvolutionConnectionString"));
            var database           = client.GetDatabase("socialEvolutionDb");
            var messagesCollection = database.GetCollection <Message>(messagesCollectionName);

            try
            {
                messagesCollection.InsertMany(messages);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        protected void SetUp()
        {
            var f = new FileStream("config.json", FileMode.Open);
            var sr = new StreamReader(f);
            try
            {
                var settings = JsonConvert
                    .DeserializeObject<MongoSettings>(sr.ReadToEnd());
                var client = new MongoClient(new MongoUrl(settings.Url));
                _database = client.GetDatabase(settings.DatabaseName);
            }
            catch (FileNotFoundException)
            {
                throw new Exception("Talk to John about why this one fails");
            }
            finally
            {
                f.Dispose();
                sr.Dispose();
            }

            _collectionName = Guid.NewGuid().ToString();
            _collection = _database.GetCollection<Container>(_collectionName);
            var mapper = new StringMapper<BasePaymentModel>(x => x.PaymentType)
                .Register<AchInputModel>("ach")
                .Register<CreditCardInputModel>("cc")
                .Register<PayPalInputModel>("paypal");
            BsonSerializer.RegisterDiscriminatorConvention(
                typeof(BasePaymentModel),
                new DiscriminatorConvention<string, BasePaymentModel>(mapper));
        }