public virtual IPersistStreams Build()
 {
     string connectionString = _connectionStringProvider();
     var builder = new MongoUrlBuilder(connectionString);
     MongoDatabase database = (new MongoClient(connectionString)).GetServer().GetDatabase(builder.DatabaseName);
     return new MongoPersistenceEngine(database, _serializer);
 }
Ejemplo n.º 2
0
        IMongoDatabase database; // база данных

        public UserContext()
        {
            var connectionString = "mongodb+srv://kotlvit:[email protected]/test?retryWrites=true";
            var connection       = new MongoUrlBuilder(connectionString);
            var client           = new MongoClient(connectionString);

            database = client.GetDatabase(connection.DatabaseName);
        }
Ejemplo n.º 3
0
        public MongoContext(string connectionString, string collectionName)
        {
            CollectionName = collectionName;
            var         connection = new MongoUrlBuilder(connectionString);
            MongoClient client     = new MongoClient(connectionString);         // получаем клиента для взаимодействия с базой данных

            database = client.GetDatabase(connection.DatabaseName);             // получаем доступ к самой базе данных
        }
Ejemplo n.º 4
0
        // private methods
        private IEnumerable <MongoUrl> EnumerateBuiltAndParsedUrls(
            MongoUrlBuilder built,
            string connectionString)
        {
            yield return(built.ToMongoUrl());

            yield return(new MongoUrl(connectionString));
        }
Ejemplo n.º 5
0
        public DbContext(string connectionString)
        {
            var builder = new MongoUrlBuilder(connectionString);

            IMongoClient client = new MongoClient(connectionString);

            _database = client.GetDatabase(builder.DatabaseName);
        }
Ejemplo n.º 6
0
        public MongoRepository(string connection_string)
        {
            var            con      = new MongoUrlBuilder(connection_string);
            MongoClient    client   = new MongoClient(connection_string);
            IMongoDatabase database = client.GetDatabase(con.DatabaseName);

            _database = database;
        }
Ejemplo n.º 7
0
        public virtual IPersistStreams Build()
        {
            var connectionString = this.TransformConnectionString(this.GetConnectionString());
            var builder          = new MongoUrlBuilder(connectionString);
            var database         = (new MongoClient(connectionString)).GetServer().GetDatabase(builder.DatabaseName);

            return(new MongoPersistenceEngine(database, this.serializer));
        }
Ejemplo n.º 8
0
        public void MongoUriConstructor()
        {
            var uriBuilder = new MongoUrlBuilder("mongodb://*****:*****@localhost/myDatabase");
            IMongoDatabaseFactory mongoDbFactory = new SimpleMongoDatabaseFactory(uriBuilder.ToMongoUrl());

            Assert.That(ReflectionUtils.GetInstanceFieldValue(mongoDbFactory, "_credentials"), Is.EqualTo(new MongoCredentials("myUsername", "myPassword")));
            Assert.That(ReflectionUtils.GetInstanceFieldValue(mongoDbFactory, "_databaseName").ToString(), Is.EqualTo("myDatabase"));
        }
Ejemplo n.º 9
0
        public IMongoContext GetMongoContext(string connectionString)
        {
            var mongoUrlBuilder = new MongoUrlBuilder(connectionString);

            var mongoClient = new MongoClient(connectionString);

            return(new MongoContext(mongoClient, mongoUrlBuilder.DatabaseName));
        }
        /// <summary>
        /// Connects to NEvenstore Mongo database
        /// </summary>
        /// <param name="connectionString">Connection string</param>
        /// <returns>nevenstore mongodatabase store</returns>
        public virtual IMongoDatabase ConnectToDatabase(string connectionString)
        {
            var builder        = new MongoUrlBuilder(connectionString);
            var clientSettings = MongoClientSettings.FromConnectionString(connectionString);

            ConfigureClientSettingsAction?.Invoke(clientSettings);
            return((new MongoClient(clientSettings)).GetDatabase(builder.DatabaseName));
        }
        protected override string GetConnectionStringWithLoginInfo(string userName, string password)
        {
            MongoUrlBuilder builder = new MongoUrlBuilder(ConnectionString);

            builder.Username = userName;
            builder.Password = password;
            return(builder.ToString());
        }
        public IMongoDatabase Create()
        {
            var    mongoUrlBuilder = new MongoUrlBuilder(_connectionString);
            var    client          = new MongoClient(mongoUrlBuilder.ToMongoUrl());
            string databaseName    = mongoUrlBuilder.DatabaseName;

            return(client.GetDatabase(databaseName));
        }
Ejemplo n.º 13
0
        public UserService()
        {
            const string connectionString = "mongodb://localhost:27017/ShowcaseDB";
            var          connection       = new MongoUrlBuilder(connectionString);
            var          client           = new MongoClient(connectionString);
            var          database         = client.GetDatabase(connection.DatabaseName);

            Users = database.GetCollection <User>("users");
        }
Ejemplo n.º 14
0
        public BookContext()
        {
            string connectionString = "mongodb://localhost:27017/Store";

            MongoUrlBuilder urlBuilder = new MongoUrlBuilder(connectionString);
            MongoClient     client     = new MongoClient(connectionString);

            _database = client.GetDatabase(urlBuilder.DatabaseName);
        }
Ejemplo n.º 15
0
        public DataContext(string connectionString)
        {
            var con = new MongoUrlBuilder(connectionString);

            client   = new MongoClient(connectionString);
            database = client.GetDatabase(con.DatabaseName);
            books    = database.GetCollection <Book>("Book");
            users    = database.GetCollection <User>("User");
        }
Ejemplo n.º 16
0
        public static IMongoDatabase GetDatabase(string connectionString, string databaseName)
        {
            var urlBuilder = new MongoUrlBuilder(connectionString)
            {
                DatabaseName = databaseName
            };

            return(GetDatabase(urlBuilder.ToMongoUrl()));
        }
        public LibraryMongoDbContext() : base()
        {
            string connectionString = "mongodb://localhost:27017/Library";
            var    connection       = new MongoUrlBuilder(connectionString);

            client   = new MongoClient(connectionString);
            database = client.GetDatabase(connection.DatabaseName);
            MDb      = database;
        }
Ejemplo n.º 18
0
        public CupContext()
        {
            string connectionString = "mongodb://localhost:27017/CricketManager";

            MongoUrlBuilder connection = new MongoUrlBuilder(connectionString);
            MongoClient     client     = new MongoClient(connectionString);

            _database = client.GetDatabase(connection.DatabaseName);
        }
Ejemplo n.º 19
0
        public MongoClient BuildDirecetClient()
        {
            var urlBuilder = new MongoUrlBuilder(ConnectionString);

            urlBuilder.ConnectionMode = ConnectionMode.Direct;
            urlBuilder.Server         = urlBuilder.Servers.First();

            return(new MongoClient(urlBuilder.ToMongoUrl()));
        }
Ejemplo n.º 20
0
        public CrudRepository(string connectionString, string name = null)
        {
            var connection = new MongoUrlBuilder(connectionString);
            var client     = new MongoClient(connectionString);

            _database  = client.GetDatabase(connection.DatabaseName);
            _tableName = string.IsNullOrEmpty(name) ? typeof(TData).Name : name;
            Collection.EnsureIndexes();
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Создает объект DataBase с указанными параметрами.
 /// </summary>
 /// <param name="connectionString">Строка подключения к серверу MongoDb.</param>
 /// <param name="dbName">Название базы данных.</param>
 /// <param name="login">Логин для подключения к MongoDb.</param>
 /// <param name="password">Пароль для подключения к MongoDb.</param>
 private DataBase(string connectionString, string dbName, string login = null, string password = null)
 {
     _connectionString = connectionString;
     _mongoUrl         = new MongoUrlBuilder(_connectionString);
     _login            = login ?? "";
     _password         = password ?? "";
     SetClient();
     ChooseDatabase(dbName);
 }
Ejemplo n.º 22
0
        public MongoDbContext(string mongoUrlString)
        {
            Check.ArgumentNotNullOrEmpty(mongoUrlString);

            var builder = new MongoUrlBuilder(mongoUrlString);

            Client   = new MongoClient(builder.ToMongoUrl());
            Database = Client.GetDatabase(builder.ToMongoUrl().DatabaseName);
        }
Ejemplo n.º 23
0
        public MobileContext()
        {
            string      connectionString = "mongodb://localhost:27017/mobilestore";
            var         connection       = new MongoUrlBuilder(connectionString);
            MongoClient client           = new MongoClient(connectionString);

            database = client.GetDatabase(connection.DatabaseName);
            gridFS   = new GridFSBucket(database);
        }
Ejemplo n.º 24
0
        public static IMongoDbConnection GetConnection()
        {
            var urlBuilder = new MongoUrlBuilder(ConnectionString)
            {
                DatabaseName = GetDatabaseName()
            };

            return(MongoDbConnection.FromUrl(urlBuilder.ToMongoUrl()));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 获取指定集合
        /// </summary>
        /// <typeparam name="T">集合类型</typeparam>
        /// <param name="dbName">数据库名称</param>
        /// <param name="document">集合名称</param>
        /// <returns></returns>
        public IMongoCollection <T> GetMongoCollection <T>(string dbName, string document) where T : class
        {
            var mongoUrl   = new MongoUrlBuilder(_config.GetConnectionString(DbNameEnum.MongodServer.ToString()));
            var client     = new MongoClient(mongoUrl.ToMongoUrl());
            var database   = client.GetDatabase(dbName);
            var collection = database.GetCollection <T>(document);

            return(collection);
        }
Ejemplo n.º 26
0
        public MyTaskRepository(IConfiguration appConfiguration)
        {
            string connectionUrl = appConfiguration.GetConnectionString("MongoConnection");
            var    connection    = new MongoUrlBuilder(connectionUrl);
            var    client        = new MongoClient(connectionUrl);

            database             = client.GetDatabase(connection.DatabaseName);
            TASK_COLLECTION_NAME = appConfiguration.GetSection("MongoCollection")["MyTask"];
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Gets the database connection string.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <returns></returns>
        internal static string GetDatabaseConnectionString(MongoDbWebSection mongoDbWebSection, NameValueCollection config)
        {
            string connectionString = GetConnectionString(mongoDbWebSection, config);
            var    builder          = new MongoUrlBuilder(connectionString);

            builder.DatabaseName = GetDatabaseName(mongoDbWebSection, connectionString, config);

            return(builder.ToString());
        }
Ejemplo n.º 28
0
        private static IMongoDatabase GetDatabase(string connectionStringName, IConfiguration config, ITenantAccessor tenantAccessor)
        {
            var connectionString = Settings.GetInstance(config, tenantAccessor.Tenant).ConnectionStrings.GetOrDefault(connectionStringName);

            var mongoUrl = new MongoUrlBuilder(connectionString);
            var client   = new MongoClient(MongoClientSettings.FromUrl(mongoUrl.ToMongoUrl()));

            return(client.GetDatabase(mongoUrl.DatabaseName));
        }
Ejemplo n.º 29
0
        public MongoBeeRepository()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["MongoDb"].ConnectionString;
            var    con = new MongoUrlBuilder(connectionString);

            client        = new MongoClient(connectionString);
            database      = client.GetDatabase(con.DatabaseName);
            BeeCollection = database.GetCollection <IBee>("gamesave");
        }
Ejemplo n.º 30
0
        public static IMongoCollection <T> GetMongoCollection <T>(string tableName)
        {
            string          connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            MongoUrlBuilder connection       = new MongoUrlBuilder(connectionString);
            MongoClient     client           = new MongoClient(connectionString);
            IMongoDatabase  database         = client.GetDatabase(connection.DatabaseName);

            return(database.GetCollection <T>(tableName));
        }
Ejemplo n.º 31
0
        public WordBookContext(IConnections connections)
        {
            string      connectionString = connections.GetConnectionStringByName(nameDB);
            var         connection       = new MongoUrlBuilder(connectionString);
            MongoClient client           = new MongoClient(connectionString);

            _database = client.GetDatabase(connection.DatabaseName);
            _gridFS   = new GridFSBucket(_database);
        }
        public void TestClone()
        {
            // set everything to non default values to test that all settings are cloned
            var connectionString =
                "mongodb://*****:*****@somehost/?" +
                "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;" +
                "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" +
                "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;localThreshold=128;socketTimeout=129;" +
                "serverSelectionTimeout=20s;ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" +
                "w=1;fsync=true;journal=true;w=2;wtimeout=131;gssapiServiceName=other";
            var builder = new MongoUrlBuilder(connectionString);
            var url = builder.ToMongoUrl();
            var settings = MongoClientSettings.FromUrl(url);

            // a few settings can only be made in code
            settings.Credentials = new[] { MongoCredential.CreateMongoCRCredential("database", "username", "password").WithMechanismProperty("SERVICE_NAME", "other") };
            settings.SslSettings = new SslSettings { CheckCertificateRevocation = false };

            var clone = settings.Clone();
            Assert.AreEqual(settings, clone);
        }
        public void TestFromUrl()
        {
            // set everything to non default values to test that all settings are converted
            var connectionString =
                "mongodb://*****:*****@somehost/?authSource=db;authMechanismProperties=CANONICALIZE_HOST_NAME:true;" +
                "connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;" +
                "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" +
                "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;localThreshold=128;socketTimeout=129;" +
                "serverSelectionTimeout=20s;ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" +
                "w=1;fsync=true;journal=true;w=2;wtimeout=131;gssapiServiceName=other";
            var builder = new MongoUrlBuilder(connectionString);
            var url = builder.ToMongoUrl();

            var settings = MongoClientSettings.FromUrl(url);
            Assert.AreEqual(url.ConnectionMode, settings.ConnectionMode);
            Assert.AreEqual(url.ConnectTimeout, settings.ConnectTimeout);
            Assert.AreEqual(1, settings.Credentials.Count());
            Assert.AreEqual(url.Username, settings.Credentials.Single().Username);
            Assert.AreEqual(url.AuthenticationMechanism, settings.Credentials.Single().Mechanism);
            Assert.AreEqual("other", settings.Credentials.Single().GetMechanismProperty<string>("SERVICE_NAME", "mongodb"));
            Assert.AreEqual(true, settings.Credentials.Single().GetMechanismProperty<bool>("CANONICALIZE_HOST_NAME", false));
            Assert.AreEqual(url.AuthenticationSource, settings.Credentials.Single().Source);
            Assert.AreEqual(new PasswordEvidence(url.Password), settings.Credentials.Single().Evidence);
            Assert.AreEqual(url.GuidRepresentation, settings.GuidRepresentation);
            Assert.AreEqual(url.IPv6, settings.IPv6);
            Assert.AreEqual(url.MaxConnectionIdleTime, settings.MaxConnectionIdleTime);
            Assert.AreEqual(url.MaxConnectionLifeTime, settings.MaxConnectionLifeTime);
            Assert.AreEqual(url.MaxConnectionPoolSize, settings.MaxConnectionPoolSize);
            Assert.AreEqual(url.MinConnectionPoolSize, settings.MinConnectionPoolSize);
            Assert.AreEqual(url.ReadPreference, settings.ReadPreference);
            Assert.AreEqual(url.ReplicaSetName, settings.ReplicaSetName);
            Assert.AreEqual(url.LocalThreshold, settings.LocalThreshold);
            Assert.IsTrue(url.Servers.SequenceEqual(settings.Servers));
            Assert.AreEqual(url.ServerSelectionTimeout, settings.ServerSelectionTimeout);
            Assert.AreEqual(url.SocketTimeout, settings.SocketTimeout);
            Assert.AreEqual(null, settings.SslSettings);
            Assert.AreEqual(url.UseSsl, settings.UseSsl);
            Assert.AreEqual(url.VerifySslCertificate, settings.VerifySslCertificate);
            Assert.AreEqual(url.ComputedWaitQueueSize, settings.WaitQueueSize);
            Assert.AreEqual(url.WaitQueueTimeout, settings.WaitQueueTimeout);
            Assert.AreEqual(url.GetWriteConcern(true), settings.WriteConcern);
        }
//	    public virtual string GetInsertCommitScript()
//	    {
//	        return @"function (commit) {
//    var result;
//    while (1) {
//        var cursor = db.Commits.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit(1);

//        var seq = cursor.hasNext() ? cursor.next()._id + 1 : 1;

//        commit._id = NumberLong(seq);

//        db.Commits.insert(commit);
        
//        var err = db.getLastErrorObj();

//        if( err && err.code ) {
//            if( err.code == 11000 /* dup key */  && 
//                err.err.indexOf('$_id_') != -1  /* dup checkpoint id */){
//                continue;
//            }
//            else{
//                result = err ;
//                break;
//            }
//        }

//        result = {id: commit._id};
//        break;
//    }
//    return result;
//}";
//	    }

	    /// <summary>
		/// Connects to NEvenstore Mongo database
		/// </summary>
		/// <param name="connectionString">Connection string</param>
		/// <returns>nevenstore mongodatabase store</returns>
		public virtual IMongoDatabase ConnectToDatabase(string connectionString)
		{
			var builder = new MongoUrlBuilder(connectionString);
            var client = new MongoClient(connectionString);

            var database = client.GetDatabase(builder.DatabaseName);
			return database;
		}
	    /// <summary>
		/// Connects to NEvenstore Mongo database
		/// </summary>
		/// <param name="connectionString">Connection string</param>
		/// <returns>nevenstore mongodatabase store</returns>
		public virtual MongoDatabase ConnectToDatabase(string connectionString)
		{
			var builder = new MongoUrlBuilder(connectionString);
			MongoDatabase database = (new MongoClient(connectionString)).GetServer().GetDatabase(builder.DatabaseName);
			return database;
		}