Example #1
0
        } // End Sub Test2

        // http://stackoverflow.com/questions/7201847/how-to-get-the-mongo-database-specified-in-connection-string-in-c-sharp
        public void Test3()
        {
            string      connectionString = "mongodb://localhost:27020/mydb";
            MongoServer _server          = new MongoClient(connectionString).GetServer();

            // var _serverOld = MongoServer.Create(connectionString);

            //take database name from connection string
            string _databaseName = MongoUrl.Create(connectionString).DatabaseName;


            //and then get database by database name:
            MongoDB.Driver.MongoDatabase thedb = _server.GetDatabase(_databaseName);


            // Connectionstring:
            MongoDB.Driver.MongoUrl csb = MongoUrl.Create(connectionString);
            string omdb = csb.DatabaseName;

            // E.g.
            MongoClient   client = new MongoClient(connectionString);
            MongoDatabase db     = client.GetServer().GetDatabase(new MongoUrl(connectionString).DatabaseName);
            MongoCollection <MongoDB.Bson.BsonDocument> collection = db.GetCollection("mycollection");

            // var spec = new Document("Name", new MongoRegex(string.Format("^{0}",searchKey), "i"));
            // collection.Find(spec);
        } // End Sub Test3
 public MongoRepository(MongoUrl mongoUrl, string databaseName)
 {
     _client = new MongoClient(mongoUrl);
     _server = _client.GetServer();
     _database = databaseName;
     _server.Connect();
 }
Example #3
0
 public MongoGateway(string mongoConnectionString)
 {
     var mongoUrl = new MongoUrl(mongoConnectionString);
     var client = new MongoClient(mongoConnectionString); 
     _dataBase = client.GetDatabase(mongoUrl.DatabaseName);
     CreateIndex();
 }
        private static void PurgeOrphanedBlobs(HashSet<String> blobsToDelete, String connectionString, String format)
        {
            Console.WriteLine("Found {0} orphaned blobs in BlobStorage named {1}", blobsToDelete.Count, format);
            if (blobsToDelete.Count > 0)
            {
                Console.WriteLine("Press y if you want to delete them, any other key to list without deletion");
                var key = Console.ReadKey();
                Console.WriteLine();
                if (Char.ToLower(key.KeyChar) == 'y')
                {
                    var uri = new MongoUrl(ConfigurationManager.AppSettings[connectionString]);
                    var client = new MongoClient(uri);

                    var database = client.GetServer().GetDatabase(uri.DatabaseName);
                    var settings = new MongoGridFSSettings()
                    {
                        Root = format
                    };
                    var gridfs = database.GetGridFS(settings);
                    foreach (var blobToDelete in blobsToDelete)
                    {
                        gridfs.DeleteById(blobToDelete);
                        Console.WriteLine("Deleted {0} in database {1}", blobToDelete, ConfigurationManager.AppSettings[connectionString]);
                    }
                }
                else
                {
                    foreach (var blobToDelete in blobsToDelete)
                    {
                        Console.WriteLine("Blob {0} in database {1} is orphaned", blobToDelete, ConfigurationManager.AppSettings[connectionString]);
                    }
                }
            }

        }
 public void SetUp()
 {
     var url = new MongoUrl(ConnectionString);
     var server = MongoServer.Create(url);
     var database = server.GetDatabase(url.DatabaseName);
     database.Drop();
 }
Example #6
0
 public static MongoDatabase GetDatabase(string cstringName)
 {
     var cstring = ConfigurationManager.ConnectionStrings[cstringName].ConnectionString;
     var mongoUrl = new MongoUrl(cstring);
     var server = new MongoClient(mongoUrl).GetServer();
     return server.GetDatabase(mongoUrl.DatabaseName, new MongoDatabaseSettings());
 }
Example #7
0
 public void Initialize(string connectionString)
 {
   var mongoUrl = new MongoUrl( connectionString );
   var client = new MongoClient( mongoUrl );
   _server = client.GetServer();
   _database = _server.GetDatabase( mongoUrl.DatabaseName );
 }
Example #8
0
 private static void ConfigureDatabase(string connection_string)
 {
     var url = new MongoUrl(connection_string);
     var client = new MongoClient(url);
     var server = client.GetServer();
     Configuration.Database = server.GetDatabase(url.DatabaseName);
 }
Example #9
0
 protected BaseController()
 {
     var url = new MongoUrl(ConnectionString());
     var client = new MongoClient(url);
     var server = client.GetServer();
     _mongoDatabase = server.GetDatabase(url.DatabaseName);
 }
Example #10
0
 /// <summary>
 /// Construct a sink posting to the specified database.
 /// </summary>
 /// <param name="databaseUrl">The URL of a CouchDB database.</param>
 /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param>
 /// <param name="period">The time to wait between checking for event batches.</param>
 /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
 public MongoDBSink(string databaseUrl, int batchPostingLimit, TimeSpan period, IFormatProvider formatProvider)
     : base(batchPostingLimit, period)
 {
     if (databaseUrl == null) throw new ArgumentNullException("databaseUrl");
     _formatProvider = formatProvider;
     _mongoUrl = new MongoUrl(databaseUrl);
 }
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            var logUrl = new MongoUrl(_config.LogsConnectionString);
            var logDb = new MongoClient(logUrl).GetDatabase(logUrl.DatabaseName);
          
               
            container.Register(
                 Component
                    .For<IMessagesTracker>()
                    .ImplementedBy<MongoDbMessagesTracker>()
                    .DependsOn(Dependency.OnValue<IMongoDatabase>(logDb)),
                Component
                    .For<ICommandBus, IInProcessCommandBus>()
                    .ImplementedBy<DocumentStoreMultiTenantCommandBus>()
                );

            container.Register(
                Component
                    .For<IDocumentFormatTranslator>()
                    .ImplementedBy<StandardDocumentFormatTranslator>(),
                Component
                    .For<DocumentDescriptor>()
                    .LifestyleCustom(typeof(TransientNotTrackingLifestyle))
            );
        }
Example #12
0
 public MongoStationRepository(String connectionString)
 {
     var url = new MongoUrl(connectionString);
     var client = new MongoClient(connectionString);
     var server = client.GetServer();
     database = server.GetDatabase(url.DatabaseName);
 }
Example #13
0
        public MongoLogger() {
            var mongoUrl = new MongoUrl(ConfigurationManager.ConnectionStrings["LogDB"].ConnectionString);
            var client = new MongoClient(mongoUrl);
            var database = client.GetServer().GetDatabase(mongoUrl.DatabaseName);

            collection = database.GetCollection<MongoDBLogDo>("Log", WriteConcern.Unacknowledged);
        }
Example #14
0
 public DropDatabaseTask(IAppConfig appConfig)
 {
     var url = new MongoUrl(appConfig.ProxyDbConnectionString);
     _mongoDatabase = new MongoClient(url)
         .GetServer()
         .GetDatabase(url.DatabaseName);
 }
        public void TestDefaults()
        {
            string connectionString = "mongodb://localhost";
            MongoUrl url = new MongoUrl(connectionString);
            Assert.IsNull(url.DefaultCredentials);
            Assert.AreEqual(1, url.Servers.Count());
            Assert.AreEqual("localhost", url.Servers.Single().Host);
            Assert.AreEqual(27017, url.Servers.Single().Port);
            Assert.IsNull(url.DatabaseName);
            Assert.AreEqual(ConnectionMode.Automatic, url.ConnectionMode);
            Assert.AreEqual(MongoDefaults.ConnectTimeout, url.ConnectTimeout);
            Assert.AreEqual(MongoDefaults.GuidRepresentation, url.GuidRepresentation);
            Assert.AreEqual(false, url.IPv6);
            Assert.AreEqual(MongoDefaults.MaxConnectionIdleTime, url.MaxConnectionIdleTime);
            Assert.AreEqual(MongoDefaults.MaxConnectionLifeTime, url.MaxConnectionLifeTime);
            Assert.AreEqual(MongoDefaults.MaxConnectionPoolSize, url.MaxConnectionPoolSize);
            Assert.AreEqual(null, url.ReplicaSetName);
            Assert.AreEqual(null, url.SafeMode);
            Assert.AreEqual(MongoDefaults.SecondaryAcceptableLatency, url.SecondaryAcceptableLatency);
#pragma warning disable 618
            Assert.AreEqual(false, url.SlaveOk);
#pragma warning restore
            Assert.AreEqual(MongoDefaults.SocketTimeout, url.SocketTimeout);
            Assert.AreEqual(false, url.UseSsl);
            Assert.AreEqual(MongoDefaults.WaitQueueMultiple, url.WaitQueueMultiple);
            Assert.AreEqual(MongoDefaults.WaitQueueSize, url.WaitQueueSize);
            Assert.AreEqual(MongoDefaults.WaitQueueTimeout, url.WaitQueueTimeout);
            Assert.AreEqual(connectionString, url.ToString());
        }
Example #16
0
        // ---------- PROPERTIES ----------
        // ---------- CONSTRUCTORS ----------
        /// <summary>
        /// Creates a utility object that can be used to perform operations against a MongoDB server.
        /// Note:
        /// Uses the authentication and database information from the supplied configuration item.
        /// </summary>
        /// <param name="configurationFolderPath">The path to the folder containing the encrypted configuration file containing information required to establish the connection to the server.</param>
        /// <param name="configurationItemName">The name of configuration item containing the information required to connect to the server. (Typically it's filename without the extension.)</param>
        public MongoDBUtility(string configurationFolderPath, string configurationItemName)
        {
            if (!string.IsNullOrWhiteSpace(configurationFolderPath) && !string.IsNullOrWhiteSpace(configurationItemName))
            {
                ConfigurationItem configItem = new ConfigurationItem(configurationFolderPath, configurationItemName, true);

                try
                {
                    // Read the connection string from the configuration file.
                    url = MongoUrl.Create(configItem.Value);
                    client = new MongoClient(url);
                    server = client.GetServer();
                    database = server.GetDatabase(url.DatabaseName);
                }
                catch
                {
                    throw new FormatException("Could not load configuration data from file. File is not of the correct format.");
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(configurationFolderPath))
                {
                    throw new ArgumentNullException("configurationFolderPath", "A path to a configuration items folder must be supplied.");
                }
                else
                {
                    throw new ArgumentNullException("configurationItemName", "The name of the configuration item to load must be supplied.");
                }
            }
        }
Example #17
0
        public UseCaseUpdateTask(IAppConfig appConfig, IDataList<UseCase> useCases)
        {
            var url = new MongoUrl(appConfig.ProxyDbConnectionString);
            _db = new MongoClient(url).GetServer().GetDatabase(url.DatabaseName);

            _useCases = useCases;
        }
Example #18
0
 public MongoGateway(string mongoConnectionString)
 {
     var mongoUrl = new MongoUrl(mongoConnectionString);
     var server = new MongoClient(mongoUrl).GetServer();
     dataBase = server.GetDatabase(mongoUrl.DatabaseName);
     CreateIndex();
 }
Example #19
0
        private static void ReadView(IServiceProvider provider)
        {
            //MongoDB.Bson.Serialization.Conventions.ConventionRegistry.Register("IgnoreExtraElements",
            //    new MongoDB.Bson.Serialization.Conventions.ConventionPack { new MongoDB.Bson.Serialization.Conventions.IgnoreExtraElementsConvention(true) }, type => true);

            var configuration = provider.GetRequiredService <IConfiguration>();

            var connectionString = configuration.GetValue <string>("mongo:SnapshootConnection");
            var connectionDbName = configuration.GetValue <string>("mongo:SnapshootDbName");

            var url      = new MongoDB.Driver.MongoUrl(connectionString);
            var client   = new MongoDB.Driver.MongoClient(url);
            var database = client.GetDatabase(connectionDbName);
            var colls    = database.GetCollection <Dto.View.UserView>(nameof(Dto.View.UserView).Replace("View", ""));

            var colls2 = database.GetCollection <Domain.User>(nameof(Domain.User));

            var loggerFactory = provider.GetRequiredService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger <Program>();

            do
            {
                var ls  = colls.AsQueryable().Take(1).ToList();
                var ls2 = colls2.AsQueryable().Take(1).ToList();
                logger.LogDebug($"获取userview {Newtonsoft.Json.JsonConvert.SerializeObject(ls)}");
                logger.LogDebug($"user {Newtonsoft.Json.JsonConvert.SerializeObject(ls2)}");
                Thread.Sleep(3000);
            } while (true);
        }
 static MongoRepositoryContext() {
     settings = new MongoRepositorySettings();
     var url = new MongoUrl(ConfigurationManager.ConnectionStrings["SysDB"].ConnectionString);
     client = new MongoClient(url);
     server = client.GetServer();
     database = server.GetDatabase(url.DatabaseName);
 }
 public void TestOneIPv6AddressWithPort()
 {
     var connectionString = "mongodb://[::1:]:1234/?w=1";
     var url = new MongoUrl(connectionString);
     Assert.AreEqual("[::1:]", url.Server.Host);
     Assert.AreEqual(1234, url.Server.Port);
 }
 private static void DropDb()
 {
     var events = ConfigurationManager.ConnectionStrings["events"].ConnectionString;
     var eventsUri = new MongoUrl(events);
     var client = new MongoClient(eventsUri);
     client.GetServer().GetDatabase(eventsUri.DatabaseName).Drop();
 }
Example #23
0
    public bool IsRestored(string connectionName)
    {
      MongoServer server = null;
      var connectionString = ConfigurationManager.ConnectionStrings[connectionName]?.ConnectionString;

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

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

        return server.GetDatabase(mongoUrl.DatabaseName).CollectionExists(MongoRestoreSettings.RestoredDbTokenCollection);
      }
      catch (FormatException ex)
      {
        Log.Error("Wrong connection string format", ex, this);
        throw;
      }
      finally
      {
        server?.Disconnect();
      }
    }
Example #24
0
        public FullTextSearch(string databaseName = "test", MongoUrl url = null)
        {
            mongoClient = url == null ? new MongoClient() : new MongoClient(url);
            database = mongoClient.GetDatabase(databaseName);

            database.CreateCollectionAsync("Students").Wait();
        }
        public GameInfoActor(String gameId)
        {
            _gameId = gameId;
            _dict = new Dictionary<String, String>();

            var url = new MongoUrl("mongodb://localhost:27020/BaseballRetro");
            var client = new MongoClient(url);
            var db = client.GetDatabase(url.DatabaseName);


            Receive<GameInfoMessage>(msg =>
            {
                _dict.Add(msg.Key, msg.Value);

                if (msg.Key.Equals("visteam", StringComparison.OrdinalIgnoreCase))
                {
                    _visitor = msg.Value;
                }
                if (msg.Key.Equals("hometeam", StringComparison.OrdinalIgnoreCase))
                {
                    _home = msg.Value;
                }
            });

            Receive<GameInfoSaveMessage>(msg =>
            {
                var coll = db.GetCollection<GameInfo>("gameInfo");
                coll.InsertOneAsync(new GameInfo(_gameId, _home, _visitor, _dict)).Wait();
            });
        }
        public void TestConnectTimeout()
        {
            string connectionString = "mongodb://localhost/?connectTimeout=123";
            MongoUrl url = new MongoUrl(connectionString);
            Assert.AreEqual(TimeSpan.FromSeconds(123), url.ConnectTimeout);
            Assert.AreEqual(connectionString + "s", url.ToString()); // "s" units added

            connectionString = "mongodb://localhost/?connectTimeout=123ms";
            url = new MongoUrl(connectionString);
            Assert.AreEqual(TimeSpan.FromMilliseconds(123), url.ConnectTimeout);
            Assert.AreEqual(connectionString, url.ToString());

            connectionString = "mongodb://localhost/?connectTimeout=123s";
            url = new MongoUrl(connectionString);
            Assert.AreEqual(TimeSpan.FromSeconds(123), url.ConnectTimeout);
            Assert.AreEqual(connectionString, url.ToString());

            connectionString = "mongodb://localhost/?connectTimeout=123m";
            url = new MongoUrl(connectionString);
            Assert.AreEqual(TimeSpan.FromMinutes(123), url.ConnectTimeout);
            Assert.AreEqual(connectionString, url.ToString());

            connectionString = "mongodb://localhost/?connectTimeout=123h";
            url = new MongoUrl(connectionString);
            Assert.AreEqual(TimeSpan.FromHours(123), url.ConnectTimeout);
            Assert.AreEqual(connectionString, url.ToString());

            connectionString = "mongodb://localhost/?connectTimeoutMS=123";
            url = new MongoUrl(connectionString);
            Assert.AreEqual(TimeSpan.FromMilliseconds(123), url.ConnectTimeout);
            Assert.AreEqual("mongodb://localhost/?connectTimeout=123ms", url.ToString()); // changed to "ms" suffix
        }
Example #27
0
        public void RegisterServices(Container container) {
            container.RegisterSingle<IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container));

            if (Settings.Current.EnableAppStats)
                container.RegisterSingle<IAppStatsClient>(() => new AppStatsClient(Settings.Current.AppStatsServerName, Settings.Current.AppStatsServerPort));
            else
                container.RegisterSingle<IAppStatsClient, NullAppStatsClient>();

            if (Settings.Current.RedisConnectionInfo == null)
                throw new ConfigurationErrorsException("RedisConnectionString was not found in the Web.config.");

            container.RegisterSingle<IDependencyResolver>(() => new SimpleInjectorCoreDependencyResolver(container));

            container.RegisterSingle<IRedisClientsManager>(() => new PooledRedisClientManager(Settings.Current.RedisConnectionInfo.ToString()));
            container.Register<ICacheClient>(() => container.GetInstance<IRedisClientsManager>().GetCacheClient());

            container.RegisterSingle<MongoDatabase>(() => {
                if (String.IsNullOrEmpty(Settings.Current.MongoConnectionString))
                    throw new ConfigurationErrorsException("MongoConnectionString was not found in the Web.config.");

                MongoDefaults.MaxConnectionIdleTime = TimeSpan.FromMinutes(1);
                var url = new MongoUrl(Settings.Current.MongoConnectionString);
                string databaseName = url.DatabaseName;
                if (Settings.Current.AppendMachineNameToDatabase)
                    databaseName += String.Concat("-", Environment.MachineName.ToLower());

                MongoServer server = new MongoClient(url).GetServer();
                return server.GetDatabase(databaseName);
            });

            container.Register<ErrorStatsHelper>();

            container.RegisterSingle<IErrorStackRepository, ErrorStackRepository>();
            container.RegisterSingle<IErrorRepository, ErrorRepository>();
            container.RegisterSingle<IOrganizationRepository, OrganizationRepository>();
            container.RegisterSingle<IJobLockInfoRepository, JobLockRepository>();
            container.RegisterSingle<IJobHistoryRepository, JobHistoryRepository>();
            container.RegisterSingle<IProjectRepository, ProjectRepository>();
            container.RegisterSingle<IUserRepository, UserRepository>();
            container.RegisterSingle<IProjectHookRepository, ProjectHookRepository>();
            container.RegisterSingle<MongoCollection<User>>(() => container.GetInstance<UserRepository>().Collection);

            container.RegisterSingle<IEmailGenerator>(() => new RazorEmailGenerator(@"Mail\Templates"));
            container.RegisterSingle<IMailer, Mailer>();

            container.RegisterSingle<IMessageService, ExceptionlessMqServer>();
            container.Register<IMessageFactory>(() => container.GetInstance<IMessageService>().MessageFactory);

            container.Register<IDependencyResolver, SimpleInjectorCoreDependencyResolver>();

            container.Register<MongoJobHistoryProvider>();
            container.Register<MongoJobLockProvider>();
            container.Register<MongoMachineJobLockProvider>();
            container.Register<StartMqJob>();
            container.Register<ErrorSignatureFactory>();
            container.Register<StripeEventHandler>();
            container.RegisterSingle<BillingManager>();
            container.RegisterSingle<DataHelper>();
        }
    static void Main()
    {

      // Create seed data

      BsonDocument[] seedData = CreateSeedData();

      // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname

      String uri = "mongodb://*****:*****@host:port/db";
      
      MongoUrl url = new MongoUrl(uri);
      MongoClient client = new MongoClient(url);
      MongoServer server = client.GetServer();
      MongoDatabase db = server.GetDatabase(url.DatabaseName);
      
      /*
       * First we'll add a few songs. Nothing is required to create the
       * songs collection; it is created automatically when we insert.
       */
      
      var songs = db.GetCollection<BsonDocument>("songs");

       // Use Insert for single BsonDocument insertion.

      songs.InsertBatch(seedData);

      /*
       * Then we need to give Boyz II Men credit for their contribution to
       * the hit "One Sweet Day".
       */
    
      QueryDocument updateQuery = new QueryDocument{ { "Title", "One Sweet Day" } };

      songs.Update(updateQuery, new UpdateDocument{ { "$set", new BsonDocument( "Artist", "Mariah Carey ft. Boyz II Men") } });

      /*
       * Finally we run a query which returns all the hits that spent 10 
       * or more weeks at number 1.
       */

      QueryDocument findQuery = new QueryDocument{ { "WeeksAtOne", new BsonDocument{ { "$gte", 10 } } } };
      var cursor = songs.Find(findQuery).SetSortOrder(SortBy.Ascending("Decade"));
      
      foreach (var song in cursor) 
      {
        var test = song["Decade"];
        Console.WriteLine("In the {0}, {1} by {2} topped the charts for {3} straight weeks",
          song["Decade"], song["Title"], song["Artist"], song["WeeksAtOne"]);
      }

      // Since this is an example, we'll clean up after ourselves.

      songs.Drop();

      // Only disconnect when your app is terminating.

      server.Disconnect();
    }
        public BatterActor(String playerId)
        {
            _playerId = playerId;
            _batterInfo = new BatterInfo();
            _batterInfo.Id = playerId;

            var url = new MongoUrl("mongodb://localhost:27020/BaseballRetro");
            var client = new MongoClient(url);
            var db = client.GetDatabase(url.DatabaseName);

            Receive<BatterEventMessage>(msg =>
            {
                BatterEventType hitType = BatterEventParser.BatterEventResult(msg.BatterEvent);
                switch (hitType)
                {
                    case BatterEventType.Double:
                        _batterInfo.Doubles++;
                        _batterInfo.Hits++;
                        _batterInfo.PlateAppearances++;
                        _batterInfo.AtBats++;
                        break;
                    case BatterEventType.Homer:
                        _batterInfo.HomeRuns++;
                        _batterInfo.Hits++;
                        _batterInfo.PlateAppearances++;
                        _batterInfo.AtBats++;
                        break;
                    case BatterEventType.Single:
                        _batterInfo.Hits++;
                        _batterInfo.PlateAppearances++;
                        _batterInfo.AtBats++;
                        break;
                    case BatterEventType.Triple:
                        _batterInfo.Hits++;
                        _batterInfo.Triples++;
                        _batterInfo.PlateAppearances++;
                        _batterInfo.AtBats++;
                        break;
                    case BatterEventType.Walk:
                        _batterInfo.Walks++;
                        _batterInfo.PlateAppearances++;
                        break;
                    case BatterEventType.NoPlay:
                        _batterInfo.PlateAppearances++;
                        break;
                    default:
                        _batterInfo.PlateAppearances++;
                        _batterInfo.AtBats++;
                        break;
                }

            });

            Receive<EndOfFeed>(msg =>
            {
                var coll = db.GetCollection<BatterInfo>("batterInfo");
                coll.ReplaceOneAsync(new BsonDocument("_id", _batterInfo.Id), _batterInfo, new UpdateOptions { IsUpsert = true });
            });
        }
        public MongoScriptRunner(string mongoClientPath, MongoUrl mongoUrl)
        {
            if (mongoClientPath == null) throw new ArgumentNullException("mongoClientPath");
            if (mongoUrl == null) throw new ArgumentNullException("mongoUrl");

            _mongoUrl = mongoUrl;
            _mongoClientPath = Path.GetFullPath(mongoClientPath);
        }
Example #31
0
        public Crud(string databaseName="shmest", MongoUrl url = null)
        {
            mongoClient = url == null ? new MongoClient() : new MongoClient(url);            
            database = mongoClient.GetDatabase(databaseName);



        }
		public MongoDbItemsRepository()
		{
			var url = new MongoUrl("mongodb://localhost/KumikoTodo");
			var client = new MongoClient(url);
			var server = client.GetServer();

			_database = server.GetDatabase(url.DatabaseName);
		}
Example #33
0
        // private static methods
        private static MongoClientSettings ParseConnectionString(string connectionString)
        {
            var url = new MongoUrl(connectionString);

            return(MongoClientSettings.FromUrl(url));
        }
Example #34
0
        /// <summary>
        /// Gets a MongoServerSettings object intialized with values from a MongoUrl.
        /// </summary>
        /// <param name="url">The MongoUrl.</param>
        /// <returns>A MongoServerSettings.</returns>
        public static MongoServerSettings FromUrl(MongoUrl url)
        {
            var credential = url.GetCredential();

            var serverSettings = new MongoServerSettings();

            serverSettings.AllowInsecureTls = url.AllowInsecureTls;
            serverSettings.ApplicationName  = url.ApplicationName;
            serverSettings.Compressors      = url.Compressors;
            serverSettings.ConnectionMode   = url.ConnectionMode;
            serverSettings.ConnectTimeout   = url.ConnectTimeout;
            if (credential != null)
            {
                foreach (var property in url.AuthenticationMechanismProperties)
                {
                    if (property.Key.Equals("CANONICALIZE_HOST_NAME", StringComparison.OrdinalIgnoreCase))
                    {
                        credential = credential.WithMechanismProperty(property.Key, bool.Parse(property.Value));
                    }
                    else
                    {
                        credential = credential.WithMechanismProperty(property.Key, property.Value);
                    }
                }
                serverSettings.Credential = credential;
            }
#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                serverSettings.GuidRepresentation = url.GuidRepresentation;
            }
#pragma warning restore 618
            serverSettings.HeartbeatInterval = url.HeartbeatInterval;
            serverSettings.HeartbeatTimeout  = url.HeartbeatTimeout;
            serverSettings.IPv6 = url.IPv6;
            serverSettings.MaxConnectionIdleTime = url.MaxConnectionIdleTime;
            serverSettings.MaxConnectionLifeTime = url.MaxConnectionLifeTime;
            serverSettings.MaxConnectionPoolSize = url.MaxConnectionPoolSize;
            serverSettings.MinConnectionPoolSize = url.MinConnectionPoolSize;
            serverSettings.ReadConcern           = new ReadConcern(url.ReadConcernLevel);
            serverSettings.ReadEncoding          = null; // ReadEncoding must be provided in code
            serverSettings.ReadPreference        = (url.ReadPreference == null) ? ReadPreference.Primary : url.ReadPreference;
            serverSettings.ReplicaSetName        = url.ReplicaSetName;
            serverSettings.RetryReads            = url.RetryReads ?? true;
            serverSettings.RetryWrites           = url.RetryWrites ?? true;
            serverSettings.LocalThreshold        = url.LocalThreshold;
            serverSettings.Scheme                 = url.Scheme;
            serverSettings.SdamLogFilename        = null; // SdamLogFilename must be provided in code
            serverSettings.Servers                = new List <MongoServerAddress>(url.Servers);
            serverSettings.ServerSelectionTimeout = url.ServerSelectionTimeout;
            serverSettings.SocketTimeout          = url.SocketTimeout;
            serverSettings.SslSettings            = null;
            if (url.TlsDisableCertificateRevocationCheck)
            {
                serverSettings.SslSettings = new SslSettings {
                    CheckCertificateRevocation = false
                };
            }
            serverSettings.UseTls = url.UseTls;
#pragma warning disable 618
            serverSettings.WaitQueueSize = url.ComputedWaitQueueSize;
#pragma warning restore 618
            serverSettings.WaitQueueTimeout = url.WaitQueueTimeout;
            serverSettings.WriteConcern     = url.GetWriteConcern(false);
            serverSettings.WriteEncoding    = null; // WriteEncoding must be provided in code
            return(serverSettings);
        }
        /// <summary>
        /// Gets a MongoClientSettings object intialized with values from a MongoURL.
        /// </summary>
        /// <param name="url">The MongoURL.</param>
        /// <returns>A MongoClientSettings.</returns>
        public static MongoClientSettings FromUrl(MongoUrl url)
        {
            if (!url.IsResolved)
            {
                var connectionMode = url.ConnectionMode;
                var resolveHosts   = connectionMode == ConnectionMode.Direct || connectionMode == ConnectionMode.Standalone;
                url = url.Resolve(resolveHosts);
            }

            var credential = url.GetCredential();

            var clientSettings = new MongoClientSettings();

            clientSettings.AllowInsecureTls      = url.AllowInsecureTls;
            clientSettings.ApplicationName       = url.ApplicationName;
            clientSettings.AutoEncryptionOptions = null; // must be configured via code
            clientSettings.Compressors           = url.Compressors;
            clientSettings.ConnectionMode        = url.ConnectionMode;
            clientSettings.ConnectTimeout        = url.ConnectTimeout;
            if (credential != null)
            {
                foreach (var property in url.AuthenticationMechanismProperties)
                {
                    if (property.Key.Equals("CANONICALIZE_HOST_NAME", StringComparison.OrdinalIgnoreCase))
                    {
                        credential = credential.WithMechanismProperty(property.Key, bool.Parse(property.Value));
                    }
                    else
                    {
                        credential = credential.WithMechanismProperty(property.Key, property.Value);
                    }
                }
                clientSettings.Credential = credential;
            }
#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                clientSettings.GuidRepresentation = url.GuidRepresentation;
            }
#pragma warning restore 618
            clientSettings.HeartbeatInterval = url.HeartbeatInterval;
            clientSettings.HeartbeatTimeout  = url.HeartbeatTimeout;
            clientSettings.IPv6 = url.IPv6;
            clientSettings.MaxConnectionIdleTime = url.MaxConnectionIdleTime;
            clientSettings.MaxConnectionLifeTime = url.MaxConnectionLifeTime;
            clientSettings.MaxConnectionPoolSize = url.MaxConnectionPoolSize;
            clientSettings.MinConnectionPoolSize = url.MinConnectionPoolSize;
            clientSettings.ReadConcern           = new ReadConcern(url.ReadConcernLevel);
            clientSettings.ReadEncoding          = null; // ReadEncoding must be provided in code
            clientSettings.ReadPreference        = (url.ReadPreference == null) ? ReadPreference.Primary : url.ReadPreference;
            clientSettings.ReplicaSetName        = url.ReplicaSetName;
            clientSettings.RetryReads            = url.RetryReads.GetValueOrDefault(true);
            clientSettings.RetryWrites           = url.RetryWrites.GetValueOrDefault(true);
            clientSettings.LocalThreshold        = url.LocalThreshold;
            clientSettings.Scheme  = url.Scheme;
            clientSettings.Servers = new List <MongoServerAddress>(url.Servers);
            clientSettings.ServerSelectionTimeout = url.ServerSelectionTimeout;
            clientSettings.SocketTimeout          = url.SocketTimeout;
            clientSettings.SslSettings            = null;
            if (url.TlsDisableCertificateRevocationCheck)
            {
                clientSettings.SslSettings = new SslSettings {
                    CheckCertificateRevocation = false
                };
            }
            clientSettings.UseTls = url.UseTls;
#pragma warning disable 618
            clientSettings.WaitQueueSize = url.ComputedWaitQueueSize;
#pragma warning restore 618
            clientSettings.WaitQueueTimeout = url.WaitQueueTimeout;
            clientSettings.WriteConcern     = url.GetWriteConcern(true); // WriteConcern is enabled by default for MongoClient
            clientSettings.WriteEncoding    = null;                      // WriteEncoding must be provided in code
            return(clientSettings);
        }
 public static MongoServer Create(MongoUrl url)
 {
     return(Create(MongoServerSettings.FromUrl(url)));
 }
        public static MongoServer Create(Uri uri)
        {
            var url = MongoUrl.Create(uri.ToString());

            return(Create(url));
        }
 public static MongoDatabase Create(Uri uri)
 {
     return(Create(MongoUrl.Create(uri.ToString())));
 }
        public static MongoDatabase Create(string connectionString)
        {
            MongoUrl url = MongoUrl.Create(connectionString);

            return(Create(url));
        }
Example #40
0
 /// <summary>
 /// Initializes a new instance of the MongoClient class.
 /// </summary>
 /// <param name="url">The URL.</param>
 public MongoClient(MongoUrl url)
     : this(MongoClientSettings.FromUrl(url))
 {
 }
Example #41
0
        public static MongoServer Create(string connectionString)
        {
            var url = MongoUrl.Create(connectionString);

            return(Create(url));
        }
Example #42
0
 /// <summary>
 /// Creates a new instance or returns an existing instance of MongoServer. Only one instance
 /// is created for each combination of server settings.
 /// </summary>
 /// <param name="url">Server settings in the form of a MongoUrl.</param>
 /// <returns>
 /// A new or existing instance of MongoServer.
 /// </returns>
 public static MongoServer Create(
     MongoUrl url
     )
 {
     return(Create(url.ToServerSettings()));
 }
 /// <summary>
 /// Creates a new instance of MongoUrl based on the settings in this MongoUrlBuilder.
 /// </summary>
 /// <returns>A new instance of MongoUrl.</returns>
 public MongoUrl ToMongoUrl()
 {
     return(MongoUrl.Create(ToString()));
 }