public IMongoCollection <T> GetCollection <T>()
        {
            string               collectionName = $"{typeof(T).Name}s";
            var                  mongoClient    = new MongoClient(mongoUrlBuilder.ToMongoUrl());
            IMongoDatabase       mongoDatabase  = mongoClient.GetDatabase(mongoUrlBuilder.DatabaseName);
            IMongoCollection <T> collection     = mongoDatabase.GetCollection <T>(collectionName);

            return(collection);
        }
Esempio n. 2
0
        public MongoDbContext(string mongoUrlString)
        {
            Check.ArgumentNotNullOrEmpty(mongoUrlString);

            var builder = new MongoUrlBuilder(mongoUrlString);

            Client   = new MongoClient(builder.ToMongoUrl());
            Database = Client.GetDatabase(builder.ToMongoUrl().DatabaseName);
        }
Esempio n. 3
0
        public MongoJobLogger(string connectionString, string tablePrefix)
        {
            if (!BsonClassMap.IsClassMapRegistered(typeof(JobLogEntry)))
            {
                BsonClassMap.RegisterClassMap <JobLogEntry>(cm =>
                {
                    cm.AutoMap();
                    cm.MapField(x => x.Timestamp);
                    cm.MapField(x => x.Name);
                    cm.MapField(x => x.Kind);
                    cm.MapField(x => x.Group);
                    cm.MapField(x => x.NextFireTimeUtc);
                    cm.MapField(x => x.PreviousFireTimeUtc);
                    cm.MapField(x => x.JobRunTime);
                    cm.MapField(x => x.ExceptionMessage);
                    cm.MapField(x => x.ExceptionStackTrace);
                });
            }

            this.tablePrefix = tablePrefix;

            var urlBuilder = new MongoUrlBuilder(connectionString);
            var client     = new MongoClient(urlBuilder.ToMongoUrl());

            this.tablePrefix = tablePrefix;
            this.database    = client.GetServer().GetDatabase(urlBuilder.DatabaseName);
        }
Esempio n. 4
0
        private void InitiateDatabase()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["Mongo.ConnectionString"].ConnectionString;
            var mongoUrlBuilder  = new MongoUrlBuilder(connectionString);

            mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());

            var TaskCatDBName = ConfigurationManager.AppSettings["TaskCat.DbName"];

            Database = mongoClient.GetDatabase(string.IsNullOrWhiteSpace(TaskCatDBName) ? DatabaseNames.TASKCAT_DB : TaskCatDBName);

            var shadowCatConnectionString = ConfigurationManager.ConnectionStrings["ShadowCat.ConnectionString"].ConnectionString;

            if (string.Equals(connectionString, shadowCatConnectionString))
            {
                ShadowCatDatabase = Database;
            }
            else
            {
                var shadowCatUrlBuilder = new MongoUrlBuilder(shadowCatConnectionString);
                shadowCatMongoClient = new MongoClient(shadowCatUrlBuilder.ToMongoUrl());
                if (shadowCatUrlBuilder.DatabaseName == "admin" || string.IsNullOrWhiteSpace(shadowCatUrlBuilder.DatabaseName))
                {
                    //Load default shadowcat database name
                    ShadowCatDatabase = shadowCatMongoClient.GetDatabase(DatabaseNames.SHADOWCAT_DEFAULT_DB);
                }
                else
                {
                    ShadowCatDatabase = shadowCatMongoClient.GetDatabase(shadowCatUrlBuilder.DatabaseName);
                }
            }
        }
        public void TestFromUrl()
        {
            // set everything to non default values to test that all settings are converted
            var connectionString =
                "mongodb://*****:*****@somehost/?appname=app1;authSource=db;authMechanismProperties=CANONICALIZE_HOST_NAME:true;" +
                "compressors=zlib,snappy;zlibCompressionLevel=9;connect=direct;connectTimeout=123;uuidRepresentation=pythonLegacy;ipv6=true;heartbeatInterval=1m;heartbeatTimeout=2m;localThreshold=128;" +
                "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;readConcernLevel=majority;" +
                "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;retryReads=false;retryWrites=true;socketTimeout=129;" +
                "serverSelectionTimeout=20s;tls=true;tlsInsecure=true;waitqueuesize=130;waitQueueTimeout=131;" +
                "w=1;fsync=true;journal=true;w=2;wtimeout=131;gssapiServiceName=other";
            var builder = new MongoUrlBuilder(connectionString);
            var url     = builder.ToMongoUrl();

            var settings = MongoClientSettings.FromUrl(url);

            Assert.Equal(url.AllowInsecureTls, settings.AllowInsecureTls);
            Assert.Equal(url.ApplicationName, settings.ApplicationName);
            Assert.Equal(url.Compressors, settings.Compressors);
            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(url.Password), settings.Credential.Evidence);
            Assert.Equal(url.GuidRepresentation, settings.GuidRepresentation);
            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.ReadConcernLevel, settings.ReadConcern.Level);
            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);
#pragma warning restore 618
            Assert.Equal(url.UseTls, settings.UseTls);
#pragma warning disable 618
            Assert.Equal(url.VerifySslCertificate, settings.VerifySslCertificate);
#pragma warning restore 618

            Assert.Equal(url.ComputedWaitQueueSize, settings.WaitQueueSize);
            Assert.Equal(url.WaitQueueTimeout, settings.WaitQueueTimeout);
            Assert.Equal(url.GetWriteConcern(true), settings.WriteConcern);
        }
Esempio n. 6
0
        public bool Connect(Database db)
        {
            LogTitle = $"{db.Server}:{db.Port}/{db.DB}";
            try
            {
                MongoUrlBuilder mub = new MongoUrlBuilder()
                {
                    Server   = new MongoServerAddress(db.Server, (int)db.Port),
                    Username = string.IsNullOrEmpty(db.User) ? null : db.User,
                    Password = string.IsNullOrEmpty(db.Pwd) ? null : db.Pwd,
                    UseTls   = db.Encrypt,
                    MaxConnectionPoolSize = 1,
                    SocketTimeout         = TimeSpan.FromSeconds(db.Timeout)
                };
                MongoClient mc = new MongoClient(mub.ToMongoUrl());

                mdb = mc.GetDatabase(db.DB);

                return(mdb != null);
            }
            catch (Exception ex)
            {
                LastError = ex.Message;
                Logger.WriteLogExcept(LogTitle, ex);

                return(false);
            }
        }
        public static IMongoDatabase GetDatabase(string connectionString)
        {
            var conn = connectionString ?? throw new ArgumentNullException(nameof(connectionString));

            lock (Lock)
            {
                Databases.TryGetValue(conn, out var database);

                if (database != null)
                {
                    return(database);
                }

                var urlBuilder = new MongoUrlBuilder(conn);

                var databaseName = urlBuilder.DatabaseName;

                if (databaseName == null)
                {
                    databaseName = GetDatabaseNameDefault();
                }

                var client = new MongoClient(urlBuilder.ToMongoUrl());
                database = client.GetDatabase(databaseName);

                Register();

                Databases[conn] = database;

                return(database);
            }
        }
Esempio n. 8
0
        public static TMongoContext GetMongoContext <TMongoContext>()
            where TMongoContext : BaseMongoContext
        {
            MockHelper.DisposeMongoDbRunner();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                _runner = MongoDbRunner.Start(MongoTestPath, "*/tools/mongodb-linux*/bin", Environment.GetEnvironmentVariable("HOME") + "/.nuget/packages/mongo2go");
            }
            else
            {
                _runner = MongoDbRunner.Start(MongoTestPath);
            }

            var mongoUrlBuilder = new MongoUrlBuilder(_runner.ConnectionString);

            mongoUrlBuilder.DatabaseName = Guid.NewGuid().ToString();

            var client   = new MongoClient(mongoUrlBuilder.ToMongoUrl());
            var database = client.GetDatabase(mongoUrlBuilder.DatabaseName);

            var db = (TMongoContext)Activator.CreateInstance(typeof(TMongoContext), database);

            return(db);
        }
Esempio n. 9
0
        public static IMongoDatabase GetDatabase(string connectionString)
        {
            var conn = connectionString ?? throw new ArgumentNullException(nameof(connectionString));

            lock (Lock)
            {
                Databases.TryGetValue(conn, out var database);

                if (database != null)
                {
                    return(database);
                }

                var url = new MongoUrlBuilder(conn);

                if (url.DatabaseName == null)
                {
                    url.DatabaseName = $"{Configuration.Stage.Get().GetName().ToUpper()}_{Configuration.AppName.Get().ToUpper()}";
                }

                var client = new MongoClient(MongoClientSettings.FromUrl(url.ToMongoUrl()));
                database = client.GetDatabase(url.DatabaseName);

                Register();

                Databases[conn] = database;

                return(database);
            }
        }
Esempio n. 10
0
        private static IMongoDatabase GetPeopleDb()
        {
            var mongoUrl = new MongoUrlBuilder("mongodb://localhost");
            var dbClient = new MongoClient(mongoUrl.ToMongoUrl());

            return(dbClient.GetDatabase("People"));
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            try
            {
                var mongoUrl   = new MongoUrlBuilder("mongodb://localhost");
                var dbClient   = new MongoClient(mongoUrl.ToMongoUrl());
                var dataBase   = dbClient.GetDatabase("People");
                var collection = dataBase.GetCollection <BsonDocument>("Persons");

                //GetFirstDocAsync(collection);
                //Console.WriteLine();
                //GetFirstDocByAgeAsync(collection, 50);
                //Console.WriteLine();
                //GetAllDocsAsync(collection);
                //Console.WriteLine();
                //GetGTEFilteredResultsAsync(collection, 50);
                //Console.WriteLine();
                //LinqFilterExampleAsync(dataBase, 50);
                //Console.WriteLine();
                //ToCursorExampleAsync(collection, 50);
                //Console.WriteLine();
                SortDemoAsync(collection, 50);
                Console.ReadLine();
            }
            catch (Exception e)
            {
            }
        }
Esempio n. 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="conn"></param>
        public MongoDbService(string conn)
        {
            var connsetting = new MongoUrlBuilder(conn);
            var client      = new MongoClient(connsetting.ToMongoUrl());

            Database = client.GetDatabase(connsetting.DatabaseName);
        }
Esempio n. 13
0
        protected MongoUrl BuildMongoUrl()
        {
            var urlBuilder = new MongoUrlBuilder
            {
                ConnectionMode        = ConnectionMode.Automatic,
                ConnectTimeout        = TimeSpan.FromSeconds(Timeout),
                MaxConnectionPoolSize = PoolSize,
                ReadPreference        = ReadPreference.PrimaryPreferred,
                WaitQueueMultiple     = WaitQueueMultiplier
            };

            if (Servers.Count == 1)
            {
                urlBuilder.Server = Servers.First();
            }
            else
            {
                urlBuilder.Servers = Servers;
            }

            // Set username & password only if username is specified.
            if (!String.IsNullOrWhiteSpace(Username))
            {
                urlBuilder.Username = Username;
                urlBuilder.Password = Password;
            }

            return(urlBuilder.ToMongoUrl());
        }
Esempio n. 14
0
        public IWorkflowStore GetWorkflowStore(ConnectionModel connectionModel)
        {
            IWorkflowStore workflowStore;

            if (connectionModel.WorkflowStoreType == WorkflowStoreType.MongoDb)
            {
                MongoUrlBuilder urlBuilder = new MongoUrlBuilder();
                urlBuilder.Server = new MongoServerAddress(connectionModel.Host, connectionModel.Port.Value);
                if (!String.IsNullOrWhiteSpace(connectionModel.User))
                {
                    urlBuilder.Username = connectionModel.User;
                }
                //if (!String.IsNullOrWhiteSpace(pwd)) urlBuilder.Password = pwd;

                var url    = urlBuilder.ToMongoUrl();
                var client = new MongoClient(url);
                var db     = client.GetDatabase(connectionModel.Database);

                workflowStore = new MongoDbWorkflowStore(db, connectionModel.ActiveCollection, connectionModel.CompletedCollection);
            }
            else
            {
                throw new NotImplementedException();
            }

            return(workflowStore);
        }
Esempio n. 15
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     // Add framework services.
     services.AddHangfire(config =>
     {
         var connectionString = "put-your-connectionsString-here";
         var mongoUrlBuilder  = new MongoUrlBuilder(connectionString)
         {
             DatabaseName = "jobs"
         };
         var mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
         var opt         = new CosmosStorageOptions
         {
             MigrationOptions = new MongoMigrationOptions
             {
                 BackupStrategy    = new NoneMongoBackupStrategy(),
                 MigrationStrategy = new DropMongoMigrationStrategy(),
             }
         };
         //config.UseLogProvider(new FileLogProvider());
         config.UseColouredConsoleLogProvider(LogLevel.Info);
         config.UseCosmosStorage(mongoClient, mongoUrlBuilder.DatabaseName, opt);
     });
     services.AddMvc(c => c.EnableEndpointRouting = false);
 }
Esempio n. 16
0
        public KoiJaboMongoDataContext()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["KoijaboMongo.ConnectionString"].ConnectionString;
            var mongoUrlBuilder  = new MongoUrlBuilder(connectionString);
            var mongoClient      = new MongoClient(mongoUrlBuilder.ToMongoUrl());

            Database = mongoClient.GetDatabase(mongoUrlBuilder.DatabaseName);

            _restaurants         = Database.GetCollection <RestaurantEntity>(MongoCollectionNames.RestaurantsCollectionName);
            _reviews             = Database.GetCollection <ReviewEntity>(MongoCollectionNames.ReviewsCollectionName);
            _users               = Database.GetCollection <UserEntity>(MongoCollectionNames.UsersCollectionName);
            _optionsForDashBoard = Database.GetCollection <OptionsForDashBoardEntity>(MongoCollectionNames.OptionsForDashboardCollectionName);

            CreateIndexOptions GeoSphereindexOptions = new CreateIndexOptions();

            GeoSphereindexOptions.SphereIndexVersion = 2;
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Geo2DSphere(x => x.GeoPoint), GeoSphereindexOptions);

            CreateIndexOptions TextindexOptions = new CreateIndexOptions();

            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.Name), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.Area), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.Address), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.PhoneNumber), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.CreditCards), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.GoodFor), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.Cuisines), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.EstablishmentType), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.Parking), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.Attire), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.NoiseLevel), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.TagsTrue), TextindexOptions);
            _restaurants.Indexes.CreateOneAsync(Builders <RestaurantEntity> .IndexKeys.Text(x => x.TagsFalse), TextindexOptions);
        }
Esempio n. 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            string databaseUrl = System.Environment.GetEnvironmentVariable("URL_DATABASE");

            var mongoUrlBuilder = new MongoUrlBuilder(databaseUrl);
            var mongoClient     = new MongoClient(mongoUrlBuilder.ToMongoUrl());

            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseMongoStorage(mongoClient, mongoUrlBuilder.DatabaseName, new MongoStorageOptions
            {
                MigrationOptions = new MongoMigrationOptions
                {
                    MigrationStrategy = new MigrateMongoMigrationStrategy(),
                    BackupStrategy    = new CollectionMongoBackupStrategy()
                },
                Prefix          = "hangfire.mongo",
                CheckConnection = true
            })
                                 );

            services.AddHangfireServer(options =>
            {
                options.ServerName = "Hangfire Tasks";
            });



            services.AddScoped <IHandlerJob, HandlerJob>();
        }
Esempio n. 18
0
        public IWorkflowStore GetWorkflowStore(ConnectionModel connectionModel)
        {
            IWorkflowStore workflowStore;

            if (connectionModel.WorkflowStoreType == WorkflowStoreType.MongoDb)
            {
                MongoUrlBuilder urlBuilder = new MongoUrlBuilder();
                urlBuilder.Server = new MongoServerAddress(connectionModel.Host, connectionModel.Port.Value);
                if (!String.IsNullOrWhiteSpace(connectionModel.User))
                {
                    urlBuilder.Username = connectionModel.User;
                }
                if (!String.IsNullOrWhiteSpace(connectionModel.Password) && !String.IsNullOrEmpty(connectionModel.Key))
                {
                    byte[] key = Convert.FromBase64String(connectionModel.Key);
                    string pwd = _encryptionProvider.SimpleDecrypt(connectionModel.Password, key);
                    urlBuilder.Password = pwd;
                }

                var url    = urlBuilder.ToMongoUrl();
                var client = new MongoClient(url);
                var db     = client.GetDatabase(connectionModel.Database);

                workflowStore = new MongoDbWorkflowStore(db, connectionModel.ActiveCollection, connectionModel.CompletedCollection);
            }
            else
            {
                throw new NotImplementedException();
            }

            return(workflowStore);
        }
Esempio n. 19
0
        private DatabaseClient()
        {
            if (ConnectionInfo == null)
            {
                var colorWas = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("! default mongo connection is used !");
                Console.ForegroundColor = colorWas;
                this.client             = new MongoClient();
            }
            else
            {
                //var settings = new MongoClientSettings();
                //settings.Server = MongoServerAddress.Parse(ConnectionInfo.Server);
                //settings.
                var mongourlBuilder = new MongoUrlBuilder();
                mongourlBuilder.Server   = MongoServerAddress.Parse(ConnectionInfo.Server);
                mongourlBuilder.Username = ConnectionInfo.Username;
                mongourlBuilder.Password = ConnectionInfo.Password;
                this.client = new MongoClient(mongourlBuilder.ToMongoUrl());
            }
            //TODO: implement connection

            //this.client = new MongoClient();
        }
Esempio n. 20
0
        public DriverConnection(string connectionString)
        {
            //TODO: see additional parameters
            var builder = new MongoUrlBuilder(connectionString);

            Url = builder.ToMongoUrl();
        }
Esempio n. 21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="options"></param>
        public MongoDbService(IOptionsMonitor <MongoDBOptions> options)
        {
            var connsetting = new MongoUrlBuilder(options.CurrentValue.ConnectionString);

            Client   = new MongoClient(connsetting.ToMongoUrl());
            Database = Client.GetDatabase(connsetting.DatabaseName);
        }
        private MongoDbContextOptions BuildOptions(IServiceProvider provider)
        {
            if (ConnectionString == null)
            {
                throw new InvalidOperationException($"Not set {nameof(ConnectionString)} value.");
            }

            if (DatabaseName == null)
            {
                throw new InvalidOperationException($"Not set {nameof(DatabaseName)} value.");
            }

            var mongoUrlBuilder = new MongoUrlBuilder(ConnectionString)
            {
                DatabaseName = DatabaseName
            };

            var mongoUrl      = mongoUrlBuilder.ToMongoUrl();
            var clientFactory = provider.GetService <IMongoDbClientFactory>();

            if (clientFactory == null)
            {
                clientFactory = MongoDbClientFactory.Instance;
            }

            var options = new MongoDbContextOptions
            {
                Url           = mongoUrl,
                ClientFactory = clientFactory
            };

            options.Collections.AddRange(collections);

            return(options);
        }
Esempio n. 23
0
        //public BookService BookService { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration["BookstoreDatabaseSettings:ConnectionString"];
            var mongoUrlBuilder  = new MongoUrlBuilder(connectionString);
            var mongoClient      = new MongoClient(mongoUrlBuilder.ToMongoUrl());
            var storageOptions   = new MongoStorageOptions
            {
                MigrationOptions = new MongoMigrationOptions
                {
                    Strategy       = MongoMigrationStrategy.Migrate,
                    BackupStrategy = MongoBackupStrategy.Collections
                }
            };

            services.AddHangfire(config =>
                                 config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseDefaultTypeSerializer()
                                 .UseMongoStorage(mongoClient, "HangfireDB", storageOptions));
            //.UseMemoryStorage());


            services.AddHangfireServer();
            services.AddControllers();
            services.AddTransient <IBookService, BookService>();
        }
Esempio n. 24
0
        public void TestClone()
        {
            // set everything to non default values to test that all settings are cloned
            var connectionString =
                "mongodb://*****:*****@somehost/?appname=app;" +
                "connect=direct;connectTimeout=123;ipv6=true;heartbeatInterval=1m;heartbeatTimeout=2m;localThreshold=128;" +
                "maxIdleTime=124;maxLifeTime=125;maxPoolSize=126;minPoolSize=127;readConcernLevel=majority;" +
                "readPreference=secondary;readPreferenceTags=a:1,b:2;readPreferenceTags=c:3,d:4;socketTimeout=129;" +
                "serverSelectionTimeout=20s;ssl=true;sslVerifyCertificate=false;waitqueuesize=130;waitQueueTimeout=131;" +
                "w=1;fsync=true;journal=true;w=2;wtimeout=131;gssapiServiceName=other";

#pragma warning disable 618
            if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
            {
                connectionString += ";uuidRepresentation=pythonLegacy";
            }
#pragma warning restore 618
            var builder  = new MongoUrlBuilder(connectionString);
            var url      = builder.ToMongoUrl();
            var settings = MongoClientSettings.FromUrl(url);
            // a few settings can only be made in code
#pragma warning disable 618
            settings.Credential = MongoCredential.CreateMongoCRCredential("database", "username", "password").WithMechanismProperty("SERVICE_NAME", "other");
#pragma warning restore 618
            settings.SslSettings = new SslSettings {
                CheckCertificateRevocation = false
            };
            settings.SdamLogFilename = "stdout";

            var clone = settings.Clone();

            Assert.Equal(settings, clone);
        }
Esempio n. 25
0
        //=========================================================================
        //
        //  AJAX ACTIONS
        //
        //=========================================================================

        /// <summary>
        /// Fetches the instance log by connecting to its mongod server.
        /// This is fast and cheap, but won't work if the instance is down.
        /// </summary>
        public JsonResult GetServerLog(int id)
        {
            var server     = ServerStatus.Get(id);
            var urlBuilder = new MongoUrlBuilder();

            urlBuilder.ConnectTimeout = new TimeSpan(0, 0, 3);
            urlBuilder.Server         = MongoServerAddress.Parse(server.Name);
            urlBuilder.ReadPreference = ReadPreference.SecondaryPreferred;
            var client = new MongoClient(urlBuilder.ToMongoUrl());
            var conn   = client.GetServer();

            try
            {
                var command = new CommandDocument
                {
                    { "getLog", "global" }
                };
                var result = conn.GetDatabase("admin").RunCommand(command);
                return(Json(new { log = HtmlizeFromLogArray(result.
                                                            Response["log"].AsBsonArray) },
                            JsonRequestBehavior.AllowGet));
            }
            catch (MongoException e)
            {
                return(Json(new { error = e.Message },
                            JsonRequestBehavior.AllowGet));
            }
        }
        public DbContext(string connectionString)
        {
            var mongoUrl = new MongoUrlBuilder(connectionString);
            var client   = new MongoClient(mongoUrl.ToMongoUrl());

            _db = client.GetDatabase(mongoUrl.DatabaseName);
        }
Esempio n. 27
0
        public void MongoUriConstructor()
        {
            var uriBuilder = new MongoUrlBuilder("mongodb://*****:*****@localhost/myDatabase");
            IMongoDatabaseFactory mongoDbFactory = new SimpleMongoDatabaseFactory(uriBuilder.ToMongoUrl());

            Assert.That(ReflectionUtils.GetInstanceFieldValue(mongoDbFactory, "_credentials"), Is.EqualTo(new MongoCredentials("myUsername", "myPassword")));
            Assert.That(ReflectionUtils.GetInstanceFieldValue(mongoDbFactory, "_databaseName").ToString(), Is.EqualTo("myDatabase"));
        }
Esempio n. 28
0
        // private methods
        private IEnumerable <MongoUrl> EnumerateBuiltAndParsedUrls(
            MongoUrlBuilder built,
            string connectionString)
        {
            yield return(built.ToMongoUrl());

            yield return(new MongoUrl(connectionString));
        }
Esempio n. 29
0
        private void InitiateDatabase()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["Mongo.ConnectionString"].ConnectionString;
            var mongoUrlBuilder  = new MongoUrlBuilder(connectionString);

            mongoClient = new MongoClient(mongoUrlBuilder.ToMongoUrl());
            Database    = mongoClient.GetDatabase(mongoUrlBuilder.DatabaseName);
        }
        public IMongoDatabase Create()
        {
            var    mongoUrlBuilder = new MongoUrlBuilder(_connectionString);
            var    client          = new MongoClient(mongoUrlBuilder.ToMongoUrl());
            string databaseName    = mongoUrlBuilder.DatabaseName;

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

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

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

            var settings = MongoClientSettings.FromUrl(url);
            Assert.AreEqual(url.ConnectionMode, settings.ConnectionMode);
            Assert.AreEqual(url.ConnectTimeout, settings.ConnectTimeout);
            Assert.AreEqual(1, settings.Credentials.Count());
            Assert.AreEqual(url.Username, settings.Credentials.Single().Username);
            Assert.AreEqual(url.AuthenticationMechanism, settings.Credentials.Single().Mechanism);
            Assert.AreEqual("other", settings.Credentials.Single().GetMechanismProperty<string>("SERVICE_NAME", "mongodb"));
            Assert.AreEqual(true, settings.Credentials.Single().GetMechanismProperty<bool>("CANONICALIZE_HOST_NAME", false));
            Assert.AreEqual(url.AuthenticationSource, settings.Credentials.Single().Source);
            Assert.AreEqual(new PasswordEvidence(url.Password), settings.Credentials.Single().Evidence);
            Assert.AreEqual(url.GuidRepresentation, settings.GuidRepresentation);
            Assert.AreEqual(url.IPv6, settings.IPv6);
            Assert.AreEqual(url.MaxConnectionIdleTime, settings.MaxConnectionIdleTime);
            Assert.AreEqual(url.MaxConnectionLifeTime, settings.MaxConnectionLifeTime);
            Assert.AreEqual(url.MaxConnectionPoolSize, settings.MaxConnectionPoolSize);
            Assert.AreEqual(url.MinConnectionPoolSize, settings.MinConnectionPoolSize);
            Assert.AreEqual(url.ReadPreference, settings.ReadPreference);
            Assert.AreEqual(url.ReplicaSetName, settings.ReplicaSetName);
            Assert.AreEqual(url.LocalThreshold, settings.LocalThreshold);
            Assert.IsTrue(url.Servers.SequenceEqual(settings.Servers));
            Assert.AreEqual(url.ServerSelectionTimeout, settings.ServerSelectionTimeout);
            Assert.AreEqual(url.SocketTimeout, settings.SocketTimeout);
            Assert.AreEqual(null, settings.SslSettings);
            Assert.AreEqual(url.UseSsl, settings.UseSsl);
            Assert.AreEqual(url.VerifySslCertificate, settings.VerifySslCertificate);
            Assert.AreEqual(url.ComputedWaitQueueSize, settings.WaitQueueSize);
            Assert.AreEqual(url.WaitQueueTimeout, settings.WaitQueueTimeout);
            Assert.AreEqual(url.GetWriteConcern(true), settings.WriteConcern);
        }