/// <summary>
        /// Initializes a new instance of the <see cref="MultipleInstanceMongoServerProxy"/> class.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="instances">The instances.</param>
        /// <param name="connectionQueue">The state change queue.</param>
        /// <param name="connectionAttempt">The connection attempt.</param>
        /// <remarks>This constructor is used when the instances have already been instructed to connect.</remarks>
        protected MultipleInstanceMongoServerProxy(MongoServerSettings settings, IEnumerable<MongoServerInstance> instances, BlockingQueue<MongoServerInstance> connectionQueue, int connectionAttempt)
        {
            _state = MongoServerState.Connecting;
            _settings = settings;
            _connectedInstances = new ConnectedInstanceCollection();
            _connectionAttempt = connectionAttempt;

            _outstandingInstanceConnections = connectionQueue.Count;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                while (connectionQueue.Count > 0)
                {
                    var instance = connectionQueue.Dequeue();
                    Interlocked.Decrement(ref _outstandingInstanceConnections);
                }
            });

            // It's important to have our own copy of this list because it might get modified during iteration. 
            _instances = instances.ToList();
            foreach (var instance in instances)
            {
                instance.StateChanged += InstanceStateChanged;
                ProcessInstanceStateChange(instance);
            }
        }
        // public methods
        /// <summary>
        /// Creates an IMongoServerProxy of some type that depends on the server settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <returns>An IMongoServerProxy.</returns>
        public IMongoServerProxy Create(MongoServerSettings settings)
        {
            var connectionMode = settings.ConnectionMode;
            if (settings.ConnectionMode == ConnectionMode.Automatic)
            {
                if (settings.ReplicaSetName != null)
                {
                    connectionMode = ConnectionMode.ReplicaSet;
                }
                else if (settings.Servers.Count() == 1)
                {
                    connectionMode = ConnectionMode.Direct;
                }
            }

            switch (connectionMode)
            {
                case ConnectionMode.Direct:
                    return new DirectMongoServerProxy(settings);
                case ConnectionMode.ReplicaSet:
                    return new ReplicaSetMongoServerProxy(settings);
                case ConnectionMode.ShardRouter:
                    return new ShardedMongoServerProxy(settings);
                default:
                    return new DiscoveringMongoServerProxy(settings);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MultipleInstanceMongoServerProxy"/> class.
        /// </summary>
        /// <param name="settings">The settings.</param>
        protected MultipleInstanceMongoServerProxy(MongoServerSettings settings)
        {
            _settings = settings;
            _connectedInstances = new ConnectedInstanceCollection();
            _instances = new List<MongoServerInstance>();

            MakeInstancesMatchAddresses(settings.Servers);
        }
        // constructors
        internal MongoConnectionPool(MongoServerInstance serverInstance)
        {
            _settings = serverInstance.Settings;
            _serverInstance = serverInstance;
            _poolSize = 0;

            _defaultAcquireConnectionOptions = new AcquireConnectionOptions
            {
                OkToAvoidWaitingByCreatingNewConnection = true,
                OkToExceedMaxConnectionPoolSize = false,
                OkToExceedWaitQueueSize = false,
                WaitQueueTimeout = _settings.WaitQueueTimeout
            };
        }
        public void TestCredential()
        {
            var settings = new MongoServerSettings();

            Assert.Equal(null, settings.Credential);
        }
        public void TestFromClientSettings()
        {
            // set everything to non default values to test that all settings are converted
            // except tlsDisableCertificateRevocationCheck because setting that with tlsInsecure is not allowed in
            // a connection string
            var connectionString =
                "mongodb://*****:*****@somehost/?authSource=db;authMechanismProperties=CANONICALIZE_HOST_NAME:true;" +
                "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;gssapiServiceName=other";

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

            var settings = MongoServerSettings.FromClientSettings(clientSettings);
            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("other", settings.Credential.GetMechanismProperty <string>("SERVICE_NAME", "mongodb"));
            Assert.Equal(true, settings.Credential.GetMechanismProperty <bool>("CANONICALIZE_HOST_NAME", false));
            Assert.Equal(url.AuthenticationSource, settings.Credential.Source);
            Assert.Equal(new PasswordEvidence(builder.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.Equal(clientSettings.SdamLogFilename, settings.SdamLogFilename);
            Assert.True(url.Servers.SequenceEqual(settings.Servers));
            Assert.Equal(url.ServerSelectionTimeout, settings.ServerSelectionTimeout);
            Assert.Equal(url.SocketTimeout, settings.SocketTimeout);
            settings.SslSettings.Should().BeNull();
#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(true), settings.WriteConcern);
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="DiscoveringMongoServerProxy"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public DiscoveringMongoServerProxy(MongoServerSettings settings)
 {
     _state     = MongoServerState.Disconnected;
     _settings  = settings;
     _instances = settings.Servers.Select(a => new MongoServerInstance(settings, a)).ToList().AsReadOnly();
 }
 public static ProfiledMongoServer Create(MongoClient client)
 {
     return(Create(MongoServerSettings.FromClientSettings(client.Settings)));
 }
Example #9
0
        public void TestEquals()
        {
            var settings = new MongoServerSettings();
            var clone    = settings.Clone();

            Assert.True(clone.Equals(settings));

            clone = settings.Clone();
            clone.ApplicationName = "app2";
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ConnectionMode = ConnectionMode.Direct;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ConnectTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone             = settings.Clone();
            clone.Credentials = new[] { MongoCredential.CreateMongoCRCredential("db2", "user2", "password2") };
            Assert.False(clone.Equals(settings));

            clone             = settings.Clone();
            clone.Credentials = new[] { MongoCredential.CreateMongoCRCredential("db1", "user2", "password2") };
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.GuidRepresentation = GuidRepresentation.PythonLegacy;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.HeartbeatInterval = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.HeartbeatTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone      = settings.Clone();
            clone.IPv6 = !settings.IPv6;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionIdleTime = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionLifeTime = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionPoolSize = settings.MaxConnectionPoolSize + 1;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.MinConnectionPoolSize = settings.MinConnectionPoolSize + 1;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.OperationTimeout = TimeSpan.FromMilliseconds(20);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ReadPreference = ReadPreference.Secondary;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ReplicaSetName = "abc";
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.LocalThreshold = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone        = settings.Clone();
            clone.Server = new MongoServerAddress("someotherhost");
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ServerSelectionTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.SocketTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone             = settings.Clone();
            clone.SslSettings = new SslSettings {
                CheckCertificateRevocation = false
            };
            Assert.False(clone.Equals(settings));

            clone        = settings.Clone();
            clone.UseSsl = !settings.UseSsl;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.VerifySslCertificate = !settings.VerifySslCertificate;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.WaitQueueSize = settings.WaitQueueSize + 1;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.WaitQueueTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.WriteConcern = WriteConcern.W2;
            Assert.False(clone.Equals(settings));
        }
Example #10
0
        public void SetUp()
        {
            fixtureComponentExecutor = new MongoDBMapReduceExecutor();
            fixtureDbReduceMongoDb   = fixtureComponentExecutor;
            fixtureDbReduceMongoDb.ConnectionString = "mongodb://*****:*****@"function Map() {					
						for (var i = 0; i < this.grades.length; i++) 
						{
							emit(this._id, this.grades[i].score);
						}			
				}"                ;

            reduceFunction = @"function Reduce(key, values) 
					{
						total = { count: 0, sum: 0 };
						total.count = values.length;
						for (var i = 0; i < values.length; i++)
						{
							total.sum += values[i];
						}
						return total;
					}"                    ;
        }
Example #11
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ReplicaSetMongoServerProxy"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public ReplicaSetMongoServerProxy(MongoServerSettings settings)
     : base(settings)
 {
     _replicaSetName = settings.ReplicaSetName;
 }
 // constructors
 internal MongoConnectionPool(MongoServerInstance serverInstance)
 {
     _settings       = serverInstance.Settings;
     _serverInstance = serverInstance;
     _poolSize       = 0;
 }
 // constructors
 internal MongoConnectionPool(MongoServerInstance serverInstance)
 {
     _settings = serverInstance.Settings;
     _serverInstance = serverInstance;
     _poolSize = 0;
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ShardedMongoServerProxy"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public ShardedMongoServerProxy(MongoServerSettings settings)
     : base(settings)
 {
 }
        private void InitializeMongoDB()
        {
            MongoServerSettings mongoServerSettings = new MongoServerSettings();

            mongoServerSettings.MinConnectionPoolSize = ApplicationSettings.MaximumNumberOfCrawlThreads;
            mongoServerSettings.Server = new MongoServerAddress("127.0.0.1");

            _mongoServer = new MongoServer(mongoServerSettings);

            _mongoServer.Connect(TimeSpan.FromSeconds(60));

            _mongoDatabase = _mongoServer.GetDatabase("arachnodedotnet");

            //pre-load the collections...

            //CrawlRequests...
            if (!_mongoDatabase.CollectionExists("CrawlRequests"))
            {
                CommandResult commandResult = _mongoDatabase.CreateCollection("CrawlRequests");

                if (!commandResult.Ok)
                {
                    throw new Exception(commandResult.ErrorMessage);
                }
            }

            _crawlRequestsCollection = _mongoDatabase.GetCollection("CrawlRequests");

            //Discoveries...
            if (!_mongoDatabase.CollectionExists("Discoveries"))
            {
                CommandResult commandResult = _mongoDatabase.CreateCollection("Discoveries");

                if (!commandResult.Ok)
                {
                    throw new Exception(commandResult.ErrorMessage);
                }
            }

            _discoveriesCollection = _mongoDatabase.GetCollection("Discoveries");

            //Exceptions...
            if (!_mongoDatabase.CollectionExists("Exceptions"))
            {
                CommandResult commandResult = _mongoDatabase.CreateCollection("Exceptions");

                if (!commandResult.Ok)
                {
                    throw new Exception(commandResult.ErrorMessage);
                }
            }

            _exceptionsCollection = _mongoDatabase.GetCollection("Exceptions");

            //cfg.Version...
            if (!_mongoDatabase.CollectionExists("cfg.Version"))
            {
                CommandResult commandResult = _mongoDatabase.CreateCollection("cfg.Version");

                if (!commandResult.Ok)
                {
                    throw new Exception(commandResult.ErrorMessage);
                }
            }

            _versionCollection = _mongoDatabase.GetCollection("cfg.Version");
        }
Example #16
0
        protected override MongoServer CreateMongoServer()
        {
            var mongoServerSettings = new MongoServerSettings();
            var server = new MongoServer(mongoServerSettings);

            //create data if none exists...
            var db              = server.GetDatabase("odata_blogs");
            var userCollection  = db.GetCollection <User>("users");
            var blogCollection  = db.GetCollection <BlogApi>("blogs");
            var postsCollection = db.GetCollection <Post>("posts");

            if (userCollection.Count() > 0)
            {
                return(server);
            }

            var user1 = new User
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Jack",
                LastName         = "McJack",
                DisplayName      = "jmcjack",
                LastLoginDateUtc = new DateTime(2012, 5, 17, 21, 53, 32).ToUniversalTime()
            };

            var user2 = new User
            {
                Id               = Guid.NewGuid(),
                FirstName        = "Jane",
                LastName         = "McJane",
                DisplayName      = "jmcjane",
                LastLoginDateUtc = new DateTime(2012, 5, 16, 3, 24, 31).ToUniversalTime()
            };

            userCollection.InsertBatch(new[] { user1, user2 });

            var blog = new Blog
            {
                Id     = Guid.NewGuid(),
                Author = new UserSummary {
                    Id = user1.Id, DisplayName = user1.DisplayName
                },
                Name = "Test Blog",
            };

            var post1 = new Post
            {
                Id          = Guid.NewGuid(),
                BlogId      = blog.Id,
                Title       = "New OData Support",
                Abstract    = "MongoDB supports OData!!!",
                Content     = "MongoDB supports OData with the new MongoDB.OData provider",
                PostTimeUtc = new DateTime(2012, 5, 13, 23, 47, 58).ToUniversalTime(),
                Comments    = new List <Comment>
                {
                    new Comment {
                        Id = Guid.NewGuid(), Author = new UserSummary {
                            Id = user2.Id, DisplayName = user2.DisplayName
                        }, Content = "Love it!!!"
                    }
                }
            };

            var post2 = new Post
            {
                Id          = Guid.NewGuid(),
                BlogId      = blog.Id,
                Title       = "Updating with mongodb-dotnet-odata",
                Abstract    = "Updating with mongodb-dotnet-odata",
                Content     = "In order to update mongodb through odata, follow the below code samples.",
                PostTimeUtc = new DateTime(2012, 5, 17, 22, 12, 14).ToUniversalTime()
            };

            blog.Posts.Add(new BlogPostSummary {
                Id = post1.Id, Abstract = post1.Abstract, Title = post1.Title, PostTimeUtc = post1.PostTimeUtc
            });
            blog.Posts.Add(new BlogPostSummary {
                Id = post2.Id, Abstract = post2.Abstract, Title = post2.Title, PostTimeUtc = post2.PostTimeUtc
            });

            blogCollection.Insert(blog);
            postsCollection.InsertBatch(new[] { post1, post2 });

            return(server);
        }
Example #17
0
        public void TestFromUrl()
        {
            // set everything to non default values to test that all settings are converted
            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(null, settings.SslSettings);
#pragma warning disable 618
            Assert.Equal(url.UseSsl, settings.UseSsl);
            Assert.Equal(url.VerifySslCertificate, settings.VerifySslCertificate);
#pragma warning restore 618
            Assert.Equal(url.UseTls, settings.UseTls);
#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);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ReplicaSetMongoServerProxy"/> class.
 /// </summary>
 /// <param name="serverSettings">The server settings.</param>
 /// <param name="instances">The instances.</param>
 /// <param name="stateChangeQueue">The state change queue.</param>
 /// <param name="connectionAttempt">The connection attempt.</param>
 public ReplicaSetMongoServerProxy(MongoServerSettings serverSettings, IEnumerable<MongoServerInstance> instances, BlockingQueue<MongoServerInstance> stateChangeQueue, int connectionAttempt)
     : base(serverSettings, instances, stateChangeQueue, connectionAttempt)
 { }
Example #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ReplicaSetMongoServerProxy"/> class.
 /// </summary>
 /// <param name="serverSettings">The server settings.</param>
 /// <param name="instances">The instances.</param>
 /// <param name="stateChangeQueue">The state change queue.</param>
 /// <param name="connectionAttempt">The connection attempt.</param>
 public ReplicaSetMongoServerProxy(MongoServerSettings serverSettings, IEnumerable <MongoServerInstance> instances, BlockingQueue <MongoServerInstance> stateChangeQueue, int connectionAttempt)
     : base(serverSettings, instances, stateChangeQueue, connectionAttempt)
 {
 }
Example #20
0
        public MainViewModel()
        {
            // Login View Model initialization
            if (ViewModelHelper.IsInDesignModeStatic == false)
            {
                this.initializeAllCommands();
                this.getAllUser();
            }

            //#region TestData
            //Product elma = new Product("ELMA", "MANAV");
            //Product kiraz = new Product("KIRAZ", "MANAV");
            //Product kavurma = new Product("KAVURMA", "KASAP");

            //// elma test prices
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 02, 20), 1.55, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 08, 20), 1.95, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 11, 20), 1.85, m_validatedUserName));

            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 02, 20), 2.15, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 08, 20), 2.35, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 11, 20), 2.55, m_validatedUserName));

            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 02, 20), 2.45, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 08, 20), 2.85, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 11, 20), 2.95, m_validatedUserName));

            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 01, 10), 3.00, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 02, 20), 2.85, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 03, 20), 2.45, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 04, 20), 2.25, m_validatedUserName));
            //elma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 05, 02), 2.55, m_validatedUserName));

            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 02, 20), 1.55, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 08, 20), 1.95, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 11, 20), 1.85, m_validatedUserName));

            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 02, 20), 2.15, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 08, 20), 2.35, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 11, 20), 2.55, m_validatedUserName));

            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 02, 20), 2.45, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 08, 20), 2.85, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 11, 20), 2.95, m_validatedUserName));

            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 01, 10), 3.00, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 02, 20), 2.85, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 03, 20), 2.45, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 04, 20), 2.25, m_validatedUserName));
            //kiraz.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 05, 02), 2.55, m_validatedUserName));

            //// kavurma test prices
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 02, 20), 51.55, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 08, 20), 53.95, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2012, 11, 20), 55.85, m_validatedUserName));

            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 02, 20), 60.15, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 08, 20), 58.35, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2013, 11, 20), 56.55, m_validatedUserName));

            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 02, 20), 63.45, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 08, 20), 64.85, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2014, 11, 20), 65.95, m_validatedUserName));

            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 01, 10), 70.00, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 02, 20), 71.85, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 03, 20), 75.45, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 04, 20), 73.25, m_validatedUserName));
            //kavurma.PriceHistory.Add(new PriceUpdate(new DateTime(2015, 05, 02), 78.55, m_validatedUserName));

            //MarketBranch merkez = new MarketBranch("MERKEZ", "TÜRKİYE", "İSTANBUL", "PENDİK");
            //MarketBranch sahil = new MarketBranch("SAHIL", "TÜRKİYE", "BURSA", "YENİSEHİR");
            //MarketBranch schoolstreet = new MarketBranch("SCHOOLSTREET", "ALMANYA", "BERLİN", "HERTZ");
            //MarketBranch carsi = new MarketBranch("CARSI", "TÜRKİYE", "ADIYAMAN", "MERKEZ");

            //merkez.Products.Add(elma);
            //merkez.Products.Add(kavurma);
            //merkez.Products.Add(kiraz);

            //sahil.Products.Add(kavurma);
            //sahil.Products.Add(elma);
            //sahil.Products.Add(kiraz);

            //schoolstreet.Products.Add(elma);
            //schoolstreet.Products.Add(kiraz);
            //schoolstreet.Products.Add(kavurma);

            //carsi.Products.Add(elma);
            //carsi.Products.Add(kiraz);
            //carsi.Products.Add(kavurma);

            //SubCity yenisehir = new SubCity("YENISEHIR");
            //SubCity pendik = new SubCity("PENDİK");
            //SubCity hertz = new SubCity("HERTZ");
            //SubCity adiMerkez = new SubCity("MERKEZ");

            //City bursa = new City("BURSA");
            //City istanbul = new City("İSTANBUL");
            //City berlin = new City("BERLİN");
            //City adiyaman = new City("ADIYAMAN");

            //yenisehir.MarketBranches.Add(sahil);
            //pendik.MarketBranches.Add(merkez);
            //hertz.MarketBranches.Add(schoolstreet);
            //adiMerkez.MarketBranches.Add(carsi);

            //bursa.SubCities.Add(yenisehir);
            //istanbul.SubCities.Add(pendik);
            //berlin.SubCities.Add(hertz);
            //adiyaman.SubCities.Add(adiMerkez);

            //Country turkiye = new Country("TÜRKİYE");
            //Country almanya = new Country("ALMANYA");

            //turkiye.Cities.Add(bursa);
            //turkiye.Cities.Add(istanbul);
            //turkiye.Cities.Add(adiyaman);
            //almanya.Cities.Add(berlin);

            //#endregion TestData

            m_contries = new ObservableCollection <Country>();
            //m_contries.Add(turkiye);
            //m_contries.Add(almanya);

            // connect to database to get user informations
            MongoServerSettings settings = new MongoServerSettings();
            MongoServer         server   = new MongoServer(settings);

            server.Connect();

            MongoDatabase db = server.GetDatabase("DigitalPriceCenter");

            var countries = db.GetCollection("Countries");

            foreach (Country country in countries.FindAllAs <Country>())
            {
                m_contries.Add(country);
            }

            //countries.Insert<Country>(turkiye);
            //countries.Insert<Country>(almanya);

            server.Disconnect();

            InfoTypes = new UpdateType[] { UpdateType.Price, UpdateType.Image, UpdateType.Info };
            addAppLog("Price manager is started");
            addAppLog("Price manager is ready to serve");

            Messenger <Msg> .Default.AddHandler <string>(Msg.UpdateInfoLog, addUpdateInfoLog);
        }
        public void TestEquals()
        {
            var settings = new MongoServerSettings();
            var clone    = settings.Clone();

            Assert.IsTrue(clone.Equals(settings));

            clone = settings.Clone();
            clone.ConnectionMode = ConnectionMode.Direct;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.ConnectTimeout = new TimeSpan(1, 2, 3);
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.CredentialsStore = new MongoCredentialsStore();
            clone.CredentialsStore.AddCredentials("db2", new MongoCredentials("user2", "password2"));
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.DefaultCredentials = new MongoCredentials("user2", "password2");
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.GuidRepresentation = GuidRepresentation.PythonLegacy;
            Assert.IsFalse(clone.Equals(settings));

            clone      = settings.Clone();
            clone.IPv6 = !settings.IPv6;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionIdleTime = new TimeSpan(1, 2, 3);
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionLifeTime = new TimeSpan(1, 2, 3);
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionPoolSize = settings.MaxConnectionPoolSize + 1;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.MinConnectionPoolSize = settings.MinConnectionPoolSize + 1;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.ReadPreference = ReadPreference.Secondary;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.ReplicaSetName = "abc";
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.SecondaryAcceptableLatency = new TimeSpan(1, 2, 3);
            Assert.IsFalse(clone.Equals(settings));

            clone        = settings.Clone();
            clone.Server = new MongoServerAddress("someotherhost");
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.SocketTimeout = new TimeSpan(1, 2, 3);
            Assert.IsFalse(clone.Equals(settings));

            clone        = settings.Clone();
            clone.UseSsl = !settings.UseSsl;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.VerifySslCertificate = !settings.VerifySslCertificate;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.WaitQueueSize = settings.WaitQueueSize + 1;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.WaitQueueTimeout = new TimeSpan(1, 2, 3);
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.WriteConcern = WriteConcern.W2;
            Assert.IsFalse(clone.Equals(settings));
        }
Example #22
0
        public void TestCredentials()
        {
            var settings = new MongoServerSettings();

            Assert.Equal(0, settings.Credentials.Count());
        }
Example #23
0
        /// <summary>
        /// Set ReadPreference And WriteConcern
        /// </summary>
        /// <param name="mongoSvrSetting"></param>
        /// <param name="config"></param>
        private static void SetReadPreferenceWriteConcern(MongoServerSettings mongoSvrSetting, ConfigHelper.MongoConnectionConfig config)
        {
            //----------------------------------------------
            //            New MongoClient class and default WriteConcern
            //----------------------------------------------

            //The new default WriteConcern is Acknowledged, but we have introduced the new
            //default in a way that doesn't alter the behavior of existing programs. We
            //are introducing a new root class called MongoClient that defaults the
            //WriteConcern to Acknowledged. The existing MongoServer Create methods are
            //deprecated but when used continue to default to a WriteConcern of Unacknowledged.

            //In prior releases you would start using the C# driver with code like this:

            //    var connectionString = "mongodb://localhost";
            //    var server = MongoServer.Create(connectionString); // deprecated
            //    var database = server.GetDatabase("test"); // WriteConcern defaulted to Unacknowledged

            //The new way to start using the C# driver is:

            //    var connectionString = "mongodb://localhost";
            //    var client = new MongoClient(connectionString);
            //    var server = client.GetServer();
            //    var database = server.GetDatabase("test"); // WriteConcern defaulted to Acknowledged

            //If you use the old way to start using the driver the default WriteConcern will
            //be Unacknowledged, but if you use the new way (using MongoClient) the default
            //WriteConcern will be Acknowledged.

            //当一个服务器作为从属服务器,副本组中的备用服务器,这里一定要设置为SlaveOK,默认情况下是不可以读取的
            //SlaveOK 过时,使用ReadPreference
            if (config.ReadPreference == ReadPreference.Primary.ToString())
            {
                mongoSvrSetting.ReadPreference = ReadPreference.Primary;
            }
            if (config.ReadPreference == ReadPreference.PrimaryPreferred.ToString())
            {
                mongoSvrSetting.ReadPreference = ReadPreference.PrimaryPreferred;
            }
            if (config.ReadPreference == ReadPreference.Secondary.ToString())
            {
                mongoSvrSetting.ReadPreference = ReadPreference.Secondary;
            }
            if (config.ReadPreference == ReadPreference.SecondaryPreferred.ToString())
            {
                mongoSvrSetting.ReadPreference = ReadPreference.SecondaryPreferred;
            }
            if (config.ReadPreference == ReadPreference.Nearest.ToString())
            {
                mongoSvrSetting.ReadPreference = ReadPreference.Nearest;
            }
            //Default ReadPreference is Primary
            //安全模式
            if (config.WriteConcern == WriteConcern.Unacknowledged.ToString())
            {
                mongoSvrSetting.WriteConcern = WriteConcern.Unacknowledged;
            }
            if (config.WriteConcern == WriteConcern.Acknowledged.ToString())
            {
                mongoSvrSetting.WriteConcern = WriteConcern.Acknowledged;
            }
            if (config.WriteConcern == WriteConcern.W2.ToString())
            {
                mongoSvrSetting.WriteConcern = WriteConcern.W2;
            }
            if (config.WriteConcern == WriteConcern.W3.ToString())
            {
                mongoSvrSetting.WriteConcern = WriteConcern.W3;
            }
            if (config.WriteConcern == WriteConcern.W4.ToString())
            {
                mongoSvrSetting.WriteConcern = WriteConcern.W4;
            }
            if (config.WriteConcern == WriteConcern.WMajority.ToString())
            {
                mongoSvrSetting.WriteConcern = WriteConcern.WMajority;
            }
            //Default WriteConcern is w=0
        }
Example #24
0
        public void ToClusterKey_should_copy_relevant_values()
        {
#pragma warning disable 618
            var credential = MongoCredential.CreateMongoCRCredential("source", "username", "password");
#pragma warning restore 618
            var servers     = new[] { new MongoServerAddress("localhost") };
            var sslSettings = new SslSettings
            {
                CheckCertificateRevocation = true,
                EnabledSslProtocols        = SslProtocols.Tls
            };

            var subject = new MongoServerSettings
            {
                ApplicationName    = "app",
                ConnectionMode     = ConnectionMode.Direct,
                ConnectTimeout     = TimeSpan.FromSeconds(1),
                Credential         = credential,
                GuidRepresentation = GuidRepresentation.Standard,
                HeartbeatInterval  = TimeSpan.FromMinutes(1),
                HeartbeatTimeout   = TimeSpan.FromMinutes(2),
                IPv6 = true,
                MaxConnectionIdleTime = TimeSpan.FromSeconds(2),
                MaxConnectionLifeTime = TimeSpan.FromSeconds(3),
                MaxConnectionPoolSize = 10,
                MinConnectionPoolSize = 5,
                ReplicaSetName        = "rs",
                LocalThreshold        = TimeSpan.FromMilliseconds(20),
                SdamLogFilename       = "navi",
                Servers = servers,
                ServerSelectionTimeout = TimeSpan.FromSeconds(6),
                SocketTimeout          = TimeSpan.FromSeconds(4),
                SslSettings            = sslSettings,
                UseSsl = true,
                VerifySslCertificate = true,
                WaitQueueSize        = 20,
                WaitQueueTimeout     = TimeSpan.FromSeconds(5)
            };

            var result = subject.ToClusterKey();

            result.ApplicationName.Should().Be(subject.ApplicationName);
            result.ConnectionMode.Should().Be(subject.ConnectionMode);
            result.ConnectTimeout.Should().Be(subject.ConnectTimeout);
#pragma warning disable 618
            result.Credentials.Should().Equal(subject.Credentials);
#pragma warning restore
            result.HeartbeatInterval.Should().Be(subject.HeartbeatInterval);
            result.HeartbeatTimeout.Should().Be(subject.HeartbeatTimeout);
            result.IPv6.Should().Be(subject.IPv6);
            result.MaxConnectionIdleTime.Should().Be(subject.MaxConnectionIdleTime);
            result.MaxConnectionLifeTime.Should().Be(subject.MaxConnectionLifeTime);
            result.MaxConnectionPoolSize.Should().Be(subject.MaxConnectionPoolSize);
            result.MinConnectionPoolSize.Should().Be(subject.MinConnectionPoolSize);
            result.ReplicaSetName.Should().Be(subject.ReplicaSetName);
            result.LocalThreshold.Should().Be(subject.LocalThreshold);
            result.SdamLogFilename.Should().Be(subject.SdamLogFilename);
            result.Servers.Should().Equal(subject.Servers);
            result.ServerSelectionTimeout.Should().Be(subject.ServerSelectionTimeout);
            result.SocketTimeout.Should().Be(subject.SocketTimeout);
            result.SslSettings.Should().Be(subject.SslSettings);
            result.UseSsl.Should().Be(subject.UseSsl);
            result.VerifySslCertificate.Should().Be(subject.VerifySslCertificate);
            result.WaitQueueSize.Should().Be(subject.WaitQueueSize);
            result.WaitQueueTimeout.Should().Be(subject.WaitQueueTimeout);
        }
Example #25
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);
        }
        public ICluster GetOrCreateCluster(MongoServerSettings serverSettings)
        {
            var clusterKey = new ClusterKey(serverSettings);

            return(GetOrCreateCluster(clusterKey));
        }
Example #27
0
 public IRepository GetRepository(MongoServerSettings settings, string databaseName)
 {
     return(new MongoRepository(settings, databaseName));
 }
 public ProfiledMongoServer(MongoServerSettings settings) : base(settings)
 {
 }
 public MongoServerTestHelper(MongoServerSettings settings)
     : base(settings)
 {
 }
        public void ToClusterKey_should_copy_relevant_values()
        {
            var clusterConfigurator = new Action <ClusterBuilder>(b => { });

#pragma warning disable 618
            var credential = MongoCredential.CreateMongoCRCredential("source", "username", "password");
#pragma warning restore 618
            var servers     = new[] { new MongoServerAddress("localhost") };
            var sslSettings = new SslSettings
            {
                CheckCertificateRevocation = true,
                EnabledSslProtocols        = SslProtocols.Tls
            };

            var subject = new MongoServerSettings
            {
                AllowInsecureTls    = false,
                ApplicationName     = "app",
                ClusterConfigurator = clusterConfigurator,
                ConnectionMode      = ConnectionMode.Direct,
                ConnectTimeout      = TimeSpan.FromSeconds(1),
                Credential          = credential,
                HeartbeatInterval   = TimeSpan.FromMinutes(1),
                HeartbeatTimeout    = TimeSpan.FromMinutes(2),
                IPv6                   = true,
                LocalThreshold         = TimeSpan.FromMilliseconds(20),
                MaxConnectionIdleTime  = TimeSpan.FromSeconds(2),
                MaxConnectionLifeTime  = TimeSpan.FromSeconds(3),
                MaxConnectionPoolSize  = 10,
                MinConnectionPoolSize  = 5,
                ReplicaSetName         = "rs",
                Scheme                 = ConnectionStringScheme.MongoDBPlusSrv,
                SdamLogFilename        = "navi",
                Servers                = servers,
                ServerSelectionTimeout = TimeSpan.FromSeconds(6),
                SocketTimeout          = TimeSpan.FromSeconds(4),
                SslSettings            = sslSettings,
                UseTls                 = true,
#pragma warning disable 618
                WaitQueueSize = 20,
#pragma warning restore 618
                WaitQueueTimeout = TimeSpan.FromSeconds(5)
            };
#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                subject.GuidRepresentation = GuidRepresentation.Standard;
            }
#pragma warning restore 618

            var result = subject.ToClusterKey();

            result.AllowInsecureTls.Should().Be(subject.AllowInsecureTls);
            result.ApplicationName.Should().Be(subject.ApplicationName);
            result.ClusterConfigurator.Should().BeSameAs(subject.ClusterConfigurator);
            result.ConnectionMode.Should().Be(subject.ConnectionMode);
            result.ConnectTimeout.Should().Be(subject.ConnectTimeout);
#pragma warning disable 618
            result.Credentials.Should().Equal(subject.Credentials);
#pragma warning restore
            result.HeartbeatInterval.Should().Be(subject.HeartbeatInterval);
            result.HeartbeatTimeout.Should().Be(subject.HeartbeatTimeout);
            result.IPv6.Should().Be(subject.IPv6);
            result.LocalThreshold.Should().Be(subject.LocalThreshold);
            result.MaxConnectionIdleTime.Should().Be(subject.MaxConnectionIdleTime);
            result.MaxConnectionLifeTime.Should().Be(subject.MaxConnectionLifeTime);
            result.MaxConnectionPoolSize.Should().Be(subject.MaxConnectionPoolSize);
            result.MinConnectionPoolSize.Should().Be(subject.MinConnectionPoolSize);
            result.ReceiveBufferSize.Should().Be(MongoDefaults.TcpReceiveBufferSize);
            result.ReplicaSetName.Should().Be(subject.ReplicaSetName);
            result.Scheme.Should().Be(subject.Scheme);
            result.SdamLogFilename.Should().Be(subject.SdamLogFilename);
            result.SendBufferSize.Should().Be(MongoDefaults.TcpSendBufferSize);
            result.Servers.Should().Equal(subject.Servers);
            result.ServerSelectionTimeout.Should().Be(subject.ServerSelectionTimeout);
            result.SocketTimeout.Should().Be(subject.SocketTimeout);
            result.SslSettings.Should().Be(subject.SslSettings);
            result.UseTls.Should().Be(subject.UseTls);
#pragma warning disable 618
            result.WaitQueueSize.Should().Be(subject.WaitQueueSize);
#pragma warning restore 618
            result.WaitQueueTimeout.Should().Be(subject.WaitQueueTimeout);
        }
Example #31
0
        public void SetUp()
        {
            var settings = new MongoServerSettings();

            _mongo = Substitute.For <MongoServerTestHelper>(settings);
        }
        public void TestEquals()
        {
            var settings = new MongoServerSettings();
            var clone    = settings.Clone();

            Assert.True(clone.Equals(settings));

            clone = settings.Clone();
            clone.AllowInsecureTls = !settings.AllowInsecureTls;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ApplicationName = "app2";
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ConnectionMode = ConnectionMode.Direct;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ConnectTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
#pragma warning disable 618
            clone.Credential = MongoCredential.CreateMongoCRCredential("db2", "user2", "password2");
#pragma warning restore 618
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
#pragma warning disable 618
            clone.Credential = MongoCredential.CreateMongoCRCredential("db1", "user2", "password2");
#pragma warning restore 618
            Assert.False(clone.Equals(settings));

#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                clone = settings.Clone();
                clone.GuidRepresentation = settings.GuidRepresentation == GuidRepresentation.CSharpLegacy ? GuidRepresentation.PythonLegacy : GuidRepresentation.CSharpLegacy;
                Assert.False(clone.Equals(settings));
            }
#pragma warning restore 618

            clone = settings.Clone();
            clone.HeartbeatInterval = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.HeartbeatTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone      = settings.Clone();
            clone.IPv6 = !settings.IPv6;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.LocalThreshold = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionIdleTime = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionLifeTime = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.MaxConnectionPoolSize = settings.MaxConnectionPoolSize + 1;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.MinConnectionPoolSize = settings.MinConnectionPoolSize + 1;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.OperationTimeout = TimeSpan.FromMilliseconds(20);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ReadPreference = ReadPreference.Secondary;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ReplicaSetName = "abc";
            Assert.False(clone.Equals(settings));

            clone            = settings.Clone();
            clone.RetryReads = false;
            Assert.False(clone.Equals(settings));

            clone             = settings.Clone();
            clone.RetryWrites = false;
            Assert.False(clone.Equals(settings));

            clone        = settings.Clone();
            clone.Scheme = ConnectionStringScheme.MongoDBPlusSrv;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.SdamLogFilename = "osiris";
            Assert.False(clone.Equals(settings));

            clone        = settings.Clone();
            clone.Server = new MongoServerAddress("someotherhost");
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.ServerSelectionTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.SocketTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone             = settings.Clone();
            clone.SslSettings = new SslSettings {
                CheckCertificateRevocation = false
            };
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
#pragma warning disable 618
            clone.UseSsl = !settings.UseSsl;
#pragma warning restore 618
            Assert.False(clone.Equals(settings));

            clone        = settings.Clone();
            clone.UseTls = !settings.UseTls;
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
#pragma warning disable 618
            clone.VerifySslCertificate = !settings.VerifySslCertificate;
#pragma warning restore 618
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
#pragma warning disable 618
            clone.WaitQueueSize = settings.WaitQueueSize + 1;
#pragma warning restore 618
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.WaitQueueTimeout = new TimeSpan(1, 2, 3);
            Assert.False(clone.Equals(settings));

            clone = settings.Clone();
            clone.WriteConcern = WriteConcern.W2;
            Assert.False(clone.Equals(settings));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="mongoConnKey"></param>
        /// <param name="config"></param>
        /// <param name="mongoConn"></param>
        /// <param name="mServerInstace"></param>
        /// <param name="mServer"></param>
        /// <returns></returns>
        private static TreeNode GetInstanceNode(String mongoConnKey, ConfigHelper.MongoConnectionConfig config,
                                                MongoServer mongoConn, MongoServerInstance mServerInstace, MongoServer mServer)
        {
            Boolean isServer = false;

            //无论如何,都改为主要服务器读优先
            if (mServerInstace == null)
            {
                isServer = true;
            }
            TreeNode SvrInstanceNode = new TreeNode();
            String   ConnSvrKey;

            if (isServer)
            {
                ConnSvrKey = mongoConnKey + "/" + mongoConnKey;
            }
            else
            {
                ConnSvrKey = mongoConnKey + "/" + mServerInstace.Address.ToString().Replace(":", "@");
            }
            SvrInstanceNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.WebServer;
            SvrInstanceNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.WebServer;
            if (isServer)
            {
                SvrInstanceNode.Text = "Connection";
            }
            else
            {
                SvrInstanceNode.Text = "Server[" + mServerInstace.Address.ToString() + "]";
            }
            if ((!String.IsNullOrEmpty(config.UserName)) & (!String.IsNullOrEmpty(config.Password)))
            {
                config.AuthMode = true;
            }
            //获取ReadOnly
            config.IsReadOnly = false;
            List <String> databaseNameList = new List <String>();

            if (!String.IsNullOrEmpty(config.DataBaseName))
            {
                //单数据库模式
                TreeNode mongoSingleDBNode;
                if (isServer)
                {
                    mongoSingleDBNode = FillDataBaseInfoToTreeNode(config.DataBaseName, mServer, mongoConnKey + "/" + mongoConnKey);
                }
                else
                {
                    mongoSingleDBNode = FillDataBaseInfoToTreeNode(config.DataBaseName, MongoServer.Create(mServerInstace.Settings), mongoConnKey + "/" + mServerInstace.Address.ToString());
                }
                mongoSingleDBNode.Tag = SINGLE_DATABASE_TAG + ":" + ConnSvrKey + "/" + config.DataBaseName;
                mongoSingleDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                mongoSingleDBNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.Database;
                SvrInstanceNode.Nodes.Add(mongoSingleDBNode);
                SvrInstanceNode.Tag = SINGLE_DB_SERVER_TAG + ":" + ConnSvrKey;
                if (config.AuthMode)
                {
                    config.IsReadOnly = mongoConn.GetDatabase(config.DataBaseName).FindUser(config.UserName).IsReadOnly;
                }
            }
            else
            {
                MongoServer InstantSrv;
                if (isServer)
                {
                    InstantSrv       = mServer;
                    databaseNameList = mServer.GetDatabaseNames().ToList <String>();
                }
                else
                {
                    MongoServerSettings setting = mongoConn.Settings.Clone();
                    setting.ConnectionMode = ConnectionMode.Direct;
                    //When Replset Case,Application need to read admin DB information
                    //if Primary,there will be exception
                    setting.ReadPreference = ReadPreference.PrimaryPreferred;
                    setting.Server         = mServerInstace.Address;
                    InstantSrv             = new MongoServer(setting);
                    databaseNameList       = InstantSrv.GetDatabaseNames().ToList <String>();
                }
                foreach (String strDBName in databaseNameList)
                {
                    TreeNode mongoDBNode;
                    try
                    {
                        mongoDBNode                    = FillDataBaseInfoToTreeNode(strDBName, InstantSrv, ConnSvrKey);
                        mongoDBNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.Database;
                        mongoDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                        SvrInstanceNode.Nodes.Add(mongoDBNode);
                        if (strDBName == MongoDBHelper.DATABASE_NAME_ADMIN)
                        {
                            if (config.AuthMode)
                            {
                                config.IsReadOnly = mongoConn.GetDatabase(strDBName).FindUser(config.UserName).IsReadOnly;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        SystemManager.ExceptionDeal(ex, strDBName + "Exception", strDBName + "Exception");
                        mongoDBNode                    = new TreeNode(strDBName + " (Exception)");
                        mongoDBNode.ImageIndex         = (int)GetSystemIcon.MainTreeImageType.Database;
                        mongoDBNode.SelectedImageIndex = (int)GetSystemIcon.MainTreeImageType.Database;
                        SvrInstanceNode.Nodes.Add(mongoDBNode);
                    }
                }
                if (isServer)
                {
                    SvrInstanceNode.Tag = SERVER_TAG + ":" + mongoConnKey + "/" + mongoConnKey;
                }
                else
                {
                    if (mongoConn.ReplicaSetName != null)
                    {
                        SvrInstanceNode.Tag = SERVER_REPLSET_MEMBER_TAG + ":" + mongoConnKey + "/" + mServerInstace.Address.ToString().Replace(":", "@");
                    }
                }
            }
            if (_mongoInstanceLst.ContainsKey(ConnSvrKey))
            {
                _mongoInstanceLst.Remove(ConnSvrKey);
            }
            if (!isServer)
            {
                _mongoInstanceLst.Add(ConnSvrKey, mServerInstace);
            }
            return(SvrInstanceNode);
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ReplicaSetMongoServerProxy"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public ReplicaSetMongoServerProxy(MongoServerSettings settings)
     : base(settings)
 {
     _replicaSetName = settings.ReplicaSetName;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DirectMongoServerProxy"/> class.
 /// </summary>
 /// <param name="serverSettings">The server settings.</param>
 /// <param name="instance">The instance.</param>
 /// <param name="connectionAttempt">The connection attempt.</param>
 public DirectMongoServerProxy(MongoServerSettings serverSettings, MongoServerInstance instance, int connectionAttempt)
 {
     _settings = serverSettings;
     _instance = instance;
     _connectionAttempt = connectionAttempt;
 }
 /// <summary>
 /// Gets an existing cluster or creates a new one.
 /// </summary>
 /// <param name="serverSettings">The server settings.</param>
 /// <returns></returns>
 public ICluster GetOrCreateCluster(MongoServerSettings serverSettings)
 {
     var clusterKey = new ClusterKey(serverSettings);
     return GetOrCreateCluster(clusterKey);
 }
Example #37
0
        public void UpdateProductInfo()
        {
            ClearUpdateInfoLog();

            // evaluete local server from db
            string localServer = m_selectedProduct.LocalServer;

            UpdateEventArgs args = new UpdateEventArgs(m_selectedType, m_updateInfoValue, localServer, m_selectedProduct.Name);

            // start a connection with market branch and wait request, Tcp client part
            AsynchronousClient tcpClient = new AsynchronousClient(m_selectedMarketBranch.TcpServiceInfo, args);
            bool response = tcpClient.StartClient();

            // according to response do smthg here

            if (response)
            {
                if (m_selectedType == UpdateType.Image)
                {
                    m_selectedProduct.UpdateImage(new ImageUpdate(DateTime.Now, args.NewValue, m_validatedUserName));
                    addUpdateInfoLog(string.Format("Product Image is updated to -> {0}", args.NewValue));

                    // update db records
                    // connect to database to update product informations
                    MongoServerSettings settings = new MongoServerSettings();
                    MongoServer         server   = new MongoServer(settings);
                    server.Connect();

                    MongoDatabase db = server.GetDatabase("DigitalPriceCenter");

                    var countries = db.GetCollection("Countries");

                    countries.Save <Country>(m_selectedCountry);

                    server.Disconnect();
                }
                else if (m_selectedType == UpdateType.Info)
                {
                    m_selectedProduct.UpdateInfo(new InfoUpdate(DateTime.Now, args.NewValue, m_validatedUserName));
                    addUpdateInfoLog(string.Format("Product Info is updated to -> {0}", args.NewValue));

                    // update db records
                    // connect to database to update product informations
                    MongoServerSettings settings = new MongoServerSettings();
                    MongoServer         server   = new MongoServer(settings);
                    server.Connect();

                    MongoDatabase db = server.GetDatabase("DigitalPriceCenter");

                    var countries = db.GetCollection("Countries");

                    countries.Save <Country>(m_selectedCountry);

                    server.Disconnect();
                }
                else if (m_selectedType == UpdateType.Price)
                {
                    App.Current.Dispatcher.Invoke((Action) delegate
                    {
                        double price;
                        if (double.TryParse(m_updateInfoValue, out price))
                        {
                            m_selectedProduct.UpdatePrice(new PriceUpdate(DateTime.Now, price, m_validatedUserName));
                        }
                    });

                    addUpdateInfoLog(string.Format("Product Price is updated to -> {0}", args.NewValue));

                    // update db records
                    // connect to database to update product informations
                    MongoServerSettings settings = new MongoServerSettings();
                    MongoServer         server   = new MongoServer(settings);
                    server.Connect();

                    MongoDatabase db = server.GetDatabase("DigitalPriceCenter");

                    var countries = db.GetCollection("Countries");

                    countries.Save <Country>(m_selectedCountry);

                    server.Disconnect();
                }
            }

            // fail message
            else
            {
                if (m_selectedType == UpdateType.Image)
                {
                    addUpdateInfoLog(string.Format("SORRY : Product Image is not updated, TRY AGAIN!"));
                }
                else if (m_selectedType == UpdateType.Info)
                {
                    addUpdateInfoLog(string.Format("SORRY : Product Info is not updated, TRY AGAIN!"));
                }
                else if (m_selectedType == UpdateType.Price)
                {
                    addUpdateInfoLog(string.Format("SORRY : Product Price is not updated, TRY AGAIN!"));
                }
            }
        }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="DiscoveringMongoServerProxy"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public DiscoveringMongoServerProxy(MongoServerSettings settings)
 {
     _state = MongoServerState.Disconnected;
     _settings = settings;
     _instances = settings.Servers.Select(a => new MongoServerInstance(settings, a)).ToList().AsReadOnly();
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ShardedMongoServerProxy"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public ShardedMongoServerProxy(MongoServerSettings settings)
     : base(settings)
 { }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="DirectMongoServerProxy"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public DirectMongoServerProxy(MongoServerSettings settings)
 {
     _settings = settings;
     _instance = new MongoServerInstance(settings, settings.Servers.First());
 }
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="DirectMongoServerProxy"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 public DirectMongoServerProxy(MongoServerSettings settings)
 {
     _settings = settings;
     _instance = new MongoServerInstance(settings, settings.Servers.First());
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DirectMongoServerProxy"/> class.
 /// </summary>
 /// <param name="serverSettings">The server settings.</param>
 /// <param name="instance">The instance.</param>
 /// <param name="connectionAttempt">The connection attempt.</param>
 public DirectMongoServerProxy(MongoServerSettings serverSettings, MongoServerInstance instance, int connectionAttempt)
 {
     _settings          = serverSettings;
     _instance          = instance;
     _connectionAttempt = connectionAttempt;
 }
 public ClusterKey(MongoServerSettings serverSettings)
 {
     _connectionMode = serverSettings.ConnectionMode;
     _connectTimeout = serverSettings.ConnectTimeout;
     _credentials = serverSettings.Credentials.ToList();
     _heartbeatInterval = __defaultHeartbeatInterval; // TODO: add HeartbeatInterval to MongoServerSettings?
     _heartbeatTimeout = __defaultHeartbeatTimeout; // TODO: add HeartbeatTimeout to MongoServerSettings?
     _ipv6 = serverSettings.IPv6;
     _maxConnectionIdleTime = serverSettings.MaxConnectionIdleTime;
     _maxConnectionLifeTime = serverSettings.MaxConnectionLifeTime;
     _maxConnectionPoolSize = serverSettings.MaxConnectionPoolSize;
     _minConnectionPoolSize = serverSettings.MinConnectionPoolSize;
     _receiveBufferSize = __defaultReceiveBufferSize; // TODO: add ReceiveBufferSize to MongoServerSettings?
     _replicaSetName = serverSettings.ReplicaSetName;
     _sendBufferSize = __defaultSendBufferSize; // TODO: add SendBufferSize to MongoServerSettings?
     _servers = serverSettings.Servers.ToList();
     _socketTimeout = serverSettings.SocketTimeout;
     _sslSettings = serverSettings.SslSettings;
     _useSsl = serverSettings.UseSsl;
     _verifySslCertificate = serverSettings.VerifySslCertificate;
     _waitQueueSize = serverSettings.WaitQueueSize;
     _waitQueueTimeout = serverSettings.WaitQueueTimeout;
     _hashCode = CalculateHashCode();
 }