Example #1
0
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="connectionString"></param>
        public FileContent(string connectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException();
            }

            var setting      = MongoServerSettings.FromUrl(new MongoUrl(connectionString));
            var databaseName = new Uri(connectionString).GetDatabaseName();

            if (!Servers.TryGetValue(connectionString, out MongoServer server))
            {
                server = new MongoServer(setting);
                Servers.TryAdd(connectionString, server);
            }
            Fs = server.GetDatabase(databaseName).GetGridFS(new MongoGridFSSettings()
            {
                Root = "FileContent"
            });
        }
Example #2
0
        private void Initialise()
        {
            MongoServerSettings settings = MongoServerSettings.FromUrl(new MongoUrl("mongodb://localhost:27017"));

            server = new MongoServer(settings);
            MongoServerSettings writeSettings = MongoServerSettings.FromUrl(new MongoUrl("mongodb://localhost:27017"));

            writeServer = new MongoServer(writeSettings);

            var dataSettings = new MongoDatabaseSettings();

            database = new MongoDatabase(server, "iadata20110409", dataSettings);
            var dataWriteSettings = new MongoDatabaseSettings();

            dataWriteSettings.WriteConcern = WriteConcern.Unacknowledged;
            writeDatabase = new MongoDatabase(server, "citablerefs", dataWriteSettings);

            readColl  = database.GetCollection <IAData>("InformationAsset");
            writeColl = writeDatabase.GetCollection <IAData>("CitableRefs");
        }
        public void TestFromUrl()
        {
            // set everything to non default values to test that all settings are converted
            var connectionString =
                "mongodb://*****:*****@somehost/?authSource=db;" +
                "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";
            var builder = new MongoUrlBuilder(connectionString);
            var url     = builder.ToMongoUrl();

            var settings = MongoServerSettings.FromUrl(url);

            Assert.Equal(url.ConnectionMode, settings.ConnectionMode);
            Assert.Equal(url.ConnectTimeout, settings.ConnectTimeout);
            Assert.Equal(1, settings.Credentials.Count());
            Assert.Equal(url.Username, settings.Credentials.Single().Username);
            Assert.Equal(url.AuthenticationMechanism, settings.Credentials.Single().Mechanism);
            Assert.Equal(url.AuthenticationSource, settings.Credentials.Single().Source);
            Assert.Equal(new PasswordEvidence(url.Password), settings.Credentials.Single().Evidence);
            Assert.Equal(url.GuidRepresentation, settings.GuidRepresentation);
            Assert.Equal(url.IPv6, settings.IPv6);
            Assert.Equal(url.MaxConnectionIdleTime, settings.MaxConnectionIdleTime);
            Assert.Equal(url.MaxConnectionLifeTime, settings.MaxConnectionLifeTime);
            Assert.Equal(url.MaxConnectionPoolSize, settings.MaxConnectionPoolSize);
            Assert.Equal(url.MinConnectionPoolSize, settings.MinConnectionPoolSize);
            Assert.Equal(url.ReadPreference, settings.ReadPreference);
            Assert.Equal(url.ReplicaSetName, settings.ReplicaSetName);
            Assert.Equal(url.LocalThreshold, settings.LocalThreshold);
            Assert.True(url.Servers.SequenceEqual(settings.Servers));
            Assert.Equal(url.ServerSelectionTimeout, settings.ServerSelectionTimeout);
            Assert.Equal(url.SocketTimeout, settings.SocketTimeout);
            Assert.Equal(null, settings.SslSettings);
            Assert.Equal(url.UseSsl, settings.UseSsl);
            Assert.Equal(url.VerifySslCertificate, settings.VerifySslCertificate);
            Assert.Equal(url.ComputedWaitQueueSize, settings.WaitQueueSize);
            Assert.Equal(url.WaitQueueTimeout, settings.WaitQueueTimeout);
            Assert.Equal(url.GetWriteConcern(false), settings.WriteConcern);
        }
        public void TestFromUrl()
        {
            // set everything to non default values to test that all settings are converted
            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;secondaryAcceptableLatency=128;socketTimeout=129;" +
                "ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" +
                "w=1;fsync=true;journal=true;w=2;wtimeout=131";
            var builder = new MongoUrlBuilder(connectionString);
            var url     = builder.ToMongoUrl();

            var settings = MongoServerSettings.FromUrl(url);

            Assert.AreEqual(url.ConnectionMode, settings.ConnectionMode);
            Assert.AreEqual(url.ConnectTimeout, settings.ConnectTimeout);
            Assert.AreEqual("{}", settings.CredentialsStore.ToString());
            Assert.AreEqual(url.DefaultCredentials, settings.DefaultCredentials);
            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.SecondaryAcceptableLatency, settings.SecondaryAcceptableLatency);
            Assert.IsTrue(url.Servers.SequenceEqual(settings.Servers));
            Assert.AreEqual(url.SocketTimeout, settings.SocketTimeout);
            Assert.AreEqual(url.UseSsl, settings.UseSsl);
            Assert.AreEqual(url.VerifySslCertificate, settings.VerifySslCertificate);
            Assert.AreEqual(url.ComputedWaitQueueSize, settings.WaitQueueSize);
            Assert.AreEqual(url.WaitQueueTimeout, settings.WaitQueueTimeout);
#pragma warning disable 618
            Assert.AreEqual(url.GetWriteConcern(MongoDefaults.SafeMode.Enabled), settings.WriteConcern);
#pragma warning restore
        }
Example #5
0
        public MongoDatabase GetDB(MongoDBAppender appender)
        {
            Uri           u = GetConnectionString(appender);
            MongoDatabase db;

            if (_dbmap.TryGetValue(u, out db) && db != null)
            {
                return(db);
            }
            else
            {
                MongoUrl            url      = MongoUrl.Create(u.ToString());
                MongoServerSettings settings = MongoServerSettings.FromUrl(url);
                lock (_dbmap) //lock only during creation...
                {
                    var    conn   = new MongoServer(settings);
                    string dbname = string.IsNullOrWhiteSpace(url.DatabaseName) ? DEFAULT_DB : url.DatabaseName;
                    db = conn.GetDatabase(dbname);
                    EnableSharding(db);
                    return(_dbmap.AddOrUpdate(u, db, (uri, currentDb) => db)); //replaces existing ones...
                }
            }
        }
        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;secondaryAcceptableLatency=128;socketTimeout=129;" +
                "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 = MongoServerSettings.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);
        }
Example #7
0
        public void TestClone()
        {
            // set everything to non default values to test except tlsDisableCertificateRevocationCheck
            // so that all settings are cloned (tlsDisableCertificateRevocationCheck cannot be set with tlsInsecure
            // in the connection string)
            var connectionString =
                "mongodb://*****:*****@somehost/?appname=app;" +
                "connect=direct;connectTimeout=123;ipv6=true;heartbeatInterval=1m;heartbeatTimeout=2m;localThreshold=128;" +
                "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" +
                "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;socketTimeout=129;" +
                "serverSelectionTimeout=20s;ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" +
                "w=1;fsync=true;journal=true;w=2;wtimeout=131;gssapiServiceName=other";

#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                connectionString += ";uuidRepresentation=pythonLegacy";
            }
#pragma warning restore 618
            var builder  = new MongoUrlBuilder(connectionString);
            var url      = builder.ToMongoUrl();
            var settings = MongoServerSettings.FromUrl(url);

            // a few settings can only be made in code
#pragma warning disable 618
            settings.Credential = MongoCredential.CreateMongoCRCredential("database", "username", "password").WithMechanismProperty("SERVICE_NAME", "other");
#pragma warning restore 618
            settings.SslSettings = new SslSettings {
                CheckCertificateRevocation = !url.TlsDisableCertificateRevocationCheck
            };
            settings.SdamLogFilename = "unimatrix-zero";

            var clone = settings.Clone();

            Assert.Equal(settings, clone);
        }
Example #8
0
        public void TestFromUrl()
        {
            // set everything to non default values to test that all settings are converted
            // with the exception of tlsDisableCertificateRevocationCheck because setting that with tlsInsecure is
            // not allowed in a connection string
            var connectionString =
                "mongodb://*****:*****@somehost/?authSource=db;appname=app;" +
                "connect=direct;connectTimeout=123;ipv6=true;heartbeatInterval=1m;heartbeatTimeout=2m;localThreshold=128;" +
                "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;" +
                "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;retryReads=false;retryWrites=true;socketTimeout=129;" +
                "serverSelectionTimeout=20s;ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" +
                "w=1;fsync=true;journal=true;w=2;wtimeout=131";

#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                connectionString += ";uuidRepresentation=pythonLegacy";
            }
#pragma warning restore 618
            var builder = new MongoUrlBuilder(connectionString);
            var url     = builder.ToMongoUrl();

            var settings = MongoServerSettings.FromUrl(url);

            Assert.Equal(url.AllowInsecureTls, settings.AllowInsecureTls);
            Assert.Equal(url.ApplicationName, settings.ApplicationName);
            Assert.Equal(url.ConnectionMode, settings.ConnectionMode);
            Assert.Equal(url.ConnectTimeout, settings.ConnectTimeout);
#pragma warning disable 618
            Assert.Equal(1, settings.Credentials.Count());
#pragma warning restore
            Assert.Equal(url.Username, settings.Credential.Username);
            Assert.Equal(url.AuthenticationMechanism, settings.Credential.Mechanism);
            Assert.Equal(url.AuthenticationSource, settings.Credential.Source);
            Assert.Equal(new PasswordEvidence(url.Password), settings.Credential.Evidence);
#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                Assert.Equal(url.GuidRepresentation, settings.GuidRepresentation);
            }
#pragma warning restore 618
            Assert.Equal(url.HeartbeatInterval, settings.HeartbeatInterval);
            Assert.Equal(url.HeartbeatTimeout, settings.HeartbeatTimeout);
            Assert.Equal(url.IPv6, settings.IPv6);
            Assert.Equal(url.LocalThreshold, settings.LocalThreshold);
            Assert.Equal(url.MaxConnectionIdleTime, settings.MaxConnectionIdleTime);
            Assert.Equal(url.MaxConnectionLifeTime, settings.MaxConnectionLifeTime);
            Assert.Equal(url.MaxConnectionPoolSize, settings.MaxConnectionPoolSize);
            Assert.Equal(url.MinConnectionPoolSize, settings.MinConnectionPoolSize);
            Assert.Equal(url.ReadPreference, settings.ReadPreference);
            Assert.Equal(url.ReplicaSetName, settings.ReplicaSetName);
            Assert.Equal(url.RetryReads, settings.RetryReads);
            Assert.Equal(url.RetryWrites, settings.RetryWrites);
            Assert.Equal(url.Scheme, settings.Scheme);
            Assert.True(url.Servers.SequenceEqual(settings.Servers));
            Assert.Equal(url.ServerSelectionTimeout, settings.ServerSelectionTimeout);
            Assert.Equal(url.SocketTimeout, settings.SocketTimeout);
            Assert.Equal(url.TlsDisableCertificateRevocationCheck, !settings.SslSettings.CheckCertificateRevocation);
#pragma warning disable 618
            Assert.Equal(url.UseSsl, settings.UseSsl);
#pragma warning restore 618
            Assert.Equal(url.UseTls, settings.UseTls);
#pragma warning disable 618
            Assert.Equal(url.VerifySslCertificate, settings.VerifySslCertificate);
#pragma warning restore 618
#pragma warning disable 618
            Assert.Equal(url.ComputedWaitQueueSize, settings.WaitQueueSize);
#pragma warning restore 618
            Assert.Equal(url.WaitQueueTimeout, settings.WaitQueueTimeout);
            Assert.Equal(url.GetWriteConcern(false), settings.WriteConcern);
        }
Example #9
0
        /// <summary>
        /// 根据config获得Server,同时更新一些运行时变量
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        public static MongoServer CreateMongoServer(ref ConfigHelper.MongoConnectionConfig config)
        {
            MongoServerSettings mongoSvrSetting = new MongoServerSettings();

            if (String.IsNullOrEmpty(config.ConnectionString))
            {
                mongoSvrSetting.ConnectionMode = ConnectionMode.Direct;
                SetReadPreferenceWriteConcern(mongoSvrSetting, config);
                //Replset时候可以不用设置吗?
                mongoSvrSetting.Server = new MongoServerAddress(config.Host, config.Port);
                //MapReduce的时候将消耗大量时间。不过这里需要平衡一下,太长容易造成并发问题
                //From Driver 1.4 Pay attention to this comment
                //The default value for SocketTimeout has been changed from 30 seconds to 0,
                //which is a special value meaning to use the operating system default value,
                //which in turn is infinity. If you actually want a SocketTimeout you now have to set it yourself.
                //The SocketTimeout is currently a server level setting, but most likely in a future release it will be possible to set it at other levels,
                //including for individual operations.
                if (config.socketTimeoutMS != 0)
                {
                    mongoSvrSetting.SocketTimeout = new TimeSpan(0, 0, (int)(config.socketTimeoutMS / 1000));
                }
                if (config.connectTimeoutMS != 0)
                {
                    mongoSvrSetting.ConnectTimeout = new TimeSpan(0, 0, (int)(config.connectTimeoutMS / 1000));
                }
                if (config.wtimeoutMS != 0)
                {
                    mongoSvrSetting.WaitQueueTimeout = new TimeSpan(0, 0, (int)(config.wtimeoutMS / 1000));
                }
                if (config.WaitQueueSize != 0)
                {
                    mongoSvrSetting.WaitQueueSize = config.WaitQueueSize;
                }
                //运行时LoginAsAdmin的设定
                config.LoginAsAdmin = (config.DataBaseName == String.Empty);
                if (!(String.IsNullOrEmpty(config.UserName) || String.IsNullOrEmpty(config.Password)))
                {
                    //认证的设定:注意,这里的密码是明文
                    //
                }
                if (config.ReplSetName != String.Empty)
                {
                    mongoSvrSetting.ReplicaSetName = config.ReplSetName;
                    config.ServerRole = ConfigHelper.SvrRoleType.ReplsetSvr;
                }
                else
                {
                    config.ServerRole = ConfigHelper.SvrRoleType.DataSvr;
                }
                if (config.ServerRole == ConfigHelper.SvrRoleType.ReplsetSvr)
                {
                    //ReplsetName不是固有属性,可以设置,不过必须保持与配置文件的一致
                    mongoSvrSetting.ConnectionMode = ConnectionMode.ReplicaSet;
                    //添加Replset服务器,注意,这里可能需要事先初始化副本
                    List <MongoServerAddress> ReplsetSvrList = new List <MongoServerAddress>();
                    foreach (String item in config.ReplsetList)
                    {
                        //如果这里的服务器在启动的时候没有--Replset参数,将会出错,当然作为单体的服务器,启动是没有任何问题的
                        MongoServerAddress ReplSrv;
                        if (item.Split(":".ToCharArray()).Length == 2)
                        {
                            ReplSrv = new MongoServerAddress(
                                item.Split(":".ToCharArray())[0],
                                Convert.ToInt16(item.Split(":".ToCharArray())[1]));
                        }
                        else
                        {
                            ReplSrv = new MongoServerAddress(item);
                        }
                        ReplsetSvrList.Add(ReplSrv);
                    }
                    mongoSvrSetting.Servers = ReplsetSvrList;
                }
            }
            else
            {
                //使用MongoConnectionString建立连接
                mongoSvrSetting = MongoServerSettings.FromUrl(MongoUrl.Create(config.ConnectionString));
            }
            //为了避免出现无法读取数据库结构的问题,将读权限都设置为Preferred
            if (mongoSvrSetting.ReadPreference == ReadPreference.Primary)
            {
                mongoSvrSetting.ReadPreference = ReadPreference.PrimaryPreferred;
            }
            if (mongoSvrSetting.ReadPreference == ReadPreference.Secondary)
            {
                mongoSvrSetting.ReadPreference = ReadPreference.SecondaryPreferred;
            }
            MongoServer masterMongoSvr = new MongoServer(mongoSvrSetting);

            return(masterMongoSvr);
        }
Example #10
0
 public MongoConnectionHandler(string connectionString, string database)
 {
     _database = new MongoServer(MongoServerSettings.FromUrl(new MongoUrl(connectionString))).GetDatabase(database);
 }