Ejemplo n.º 1
0
        public MongoDbService(MongoDBConfig dBConfig)
        {
            _dBConfig = dBConfig;
            _client   = new MongoClient(new MongoClientSettings()
            {
                Server     = MongoServerAddress.Parse(_dBConfig.Host),
                Credential = string.IsNullOrEmpty(_dBConfig.AuthMechanism)
                    ? null
                    : MongoCredential.CreateCredential(
                    _dBConfig.AuthSource,
                    _dBConfig.Username,
                    _dBConfig.Password
                    )
            });
            _dB = _client.GetDatabase(_dBConfig.Database);

            _data   = _dB.GetCollection <CcData>(_dBConfig.CollectionData);
            _events = _dB.GetCollection <CcEvent>(_dBConfig.CollectionEvents);
            _groups = _dB.GetCollection <CcGroup>(_dBConfig.CollectionGroups);


            Data   = new MongoCollection <CcData>(_data);
            Events = new MongoCollection <CcEvent>(_events);
            Groups = new MongoCollection <CcGroup>(_groups);
        }
Ejemplo n.º 2
0
        public DatabaseContext(MongoDBConfig config)
        {
            //var client = new MongoClient(config.ConnectionString);
            //_db = client.GetDatabase(config.Database);
            //string username = config.User;
            //string password = config.Password;

            string mongoDbAuthMechanism            = "SCRAM-SHA-1";
            MongoInternalIdentity internalIdentity =
                new MongoInternalIdentity("admin", config.User);
            PasswordEvidence passwordEvidence = new PasswordEvidence(config.Password);
            MongoCredential  mongoCredential  =
                new MongoCredential(mongoDbAuthMechanism,
                                    internalIdentity, passwordEvidence);
            List <MongoCredential> credentials =
                new List <MongoCredential>()
            {
                mongoCredential
            };


            MongoClientSettings settings = new MongoClientSettings();
            // comment this line below if your mongo doesn't run on secured mode
            //settings.Credentials = credentials;
            String             mongoHost = config.Host;
            MongoServerAddress address   = new MongoServerAddress(mongoHost);

            settings.Server = address;

            MongoClient client = new MongoClient(settings);

            _db = client.GetDatabase(config.Database);
        }
Ejemplo n.º 3
0
        //[SetUp]
        public MongoDatabaseManager()
        {
            _config = new MongoDBConfig();
            _connect();

            _initData();
        }
Ejemplo n.º 4
0
 public void GetDatabaseQueryTimeout()
 {
     #region GetQueryTimeout
     int databaseTimeout = MongoDBConfig.GetQueryTimeout();
     #endregion
     Assert.AreEqual(30, databaseTimeout);
 }
Ejemplo n.º 5
0
 public void GetDatabaseStringTest()
 {
     #region GetDatabaseString
     string databaseString = MongoDBConfig.GetDatabaseString();
     #endregion
     Assert.AreEqual("MongoDatabaseTest", databaseString);
 }
Ejemplo n.º 6
0
        private static async Task MainAsync()
        {
            MongoDBConfig.RegisterClassMaps();

            var builder = new ContainerBuilder();

            builder.RegisterModule(new Common.AutofacModule());
            builder.RegisterModule(new AutofacModule());

            var container = builder.Build();

            while (true)
            {
                var jobs = container.Resolve <IEnumerable <IJob> >();
                foreach (var job in jobs)
                {
                    Console.WriteLine($"Starting {job.GetType().Name} job.");
                    var sw = Stopwatch.StartNew();

                    await job.ExecuteJob();

                    sw.Stop();
                    Console.WriteLine($"Took {TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds):dd\\.hh\\:mm\\:ss\\.fff} to execute {job.GetType().Name} job.");
                    Console.WriteLine();
                }

                Thread.Sleep(TimeSpan.FromDays(7));
            }
        }
Ejemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var config = new MongoDBConfig();

            Configuration.Bind(config);

            #region Statistics
            var statisticsContext    = new StatisticsContext(config);
            var statisticsRepository = new StatisticsRepository(statisticsContext);
            services.AddSingleton <StatisticsRepository>(statisticsRepository);
            #endregion

            var statistics = statisticsRepository.GetAll().GetAwaiter().GetResult();
            if (statistics.Count() == 0)
            {
                this.seedDefaultStatisticsObject(statisticsRepository);
            }

            services.AddControllers();
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:4200")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
        }
Ejemplo n.º 8
0
 public MongoDatabase(MongoDBConfig config)
 {
     this.config          = config;
     this.client          = new MongoClient("mongodb://" + config.hostName + ":" + config.port);
     this.database        = client.GetDatabase(config.database);
     this.notesCollection = database.GetCollection <Note>("notes");
 }
Ejemplo n.º 9
0
        public StoredFileContext(MongoDBConfig config)
        {
            var client = new MongoClient(config.ConnectionString);

            _db    = client.GetDatabase(config.Database);
            bucket = new GridFSBucket(_db);
        }
Ejemplo n.º 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services
            .AddOptions()
            .AddCors(options => {
                var policy = new Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicy();
                policy.Origins.Add("*");
                policy.Headers.Add("*");
                policy.Methods.Add("*");
                policy.SupportsCredentials = true;

                options.AddPolicy("CorsPolicy", policy);
            })
            .AddMvc()
            .AddJsonOptions(options =>
            {
                var settings = options.SerializerSettings;

                settings.ContractResolver  = new CamelCasePropertyNamesContractResolver();
                settings.NullValueHandling = NullValueHandling.Ignore;
                settings.Formatting        = Formatting.Indented;
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("LocalOnly", policy => policy.Requirements.Add(new LocalAuthorizationOnlyRequirement()));
                options.AddPolicy("Admin", policy => policy.Requirements.Add(new GroupAuthorizationRequirement("Admin")));
            });

            services.Configure <MongoDBOptions>(Configuration.GetSection("mongodb"));
            MongoDBConfig.RegisterClassMaps();

            return(IocConfig.RegisterComponents(services));
        }
Ejemplo n.º 11
0
 public void GetDatabaseConnectionStringTest()
 {
     #region GetConnection
     string connection = MongoDBConfig.GetConnectionString();
     #endregion
     Assert.AreEqual("mongodb://localhost:27017", connection);
 }
Ejemplo n.º 12
0
        public IActionResult DeleteByFieldValue()
        {
            ViewData["Message"] = "Your application description page.";

            MongoDBConfig config = new MongoDBConfig(
                _configuration[MongoDBConfig.KeyNameConnectionString],
                _configuration[MongoDBConfig.KeyNameDatabaseName]
                );

            ObjectId someObjectIdValue = new ObjectId("5c6e82d721654c50981bddec");

            Test test = new Test()
            {
                AliveAndKicking   = true,
                DateOfBirth       = new DateTime(1976, 4, 19),
                Name              = "Ozan Kutlu",
                Surname           = "Bayram",
                _DateUtcCreated   = DateTime.Now,
                _DateUtcModified  = DateTime.Now,
                _IsActive         = true,
                SomeObjectIdValue = someObjectIdValue
            };

            MongoDBHelper helper = new MongoDBHelper(config, typeof(Parameter));

            helper.Insert(test);

            long deletedCount = 0;
            bool deleteResult = helper.DeleteByFieldValue <Test>("SomeObjectIdValue", someObjectIdValue, out deletedCount);

            ViewData["DeletedCount"] = deletedCount.ToString();
            ViewData["DeleteResult"] = deleteResult.ToString();

            return(View());
        }
Ejemplo n.º 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            var config = new MongoDBConfig();

            Configuration.Bind(config);

            #region ZIFile
            var appUsersContext = new ZIFileContext(config);
            var repo            = new ZIFileRepository(appUsersContext);
            services.AddSingleton <ZIFileRepository>(repo);
            #endregion

            services.AddControllers();

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:4200")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
        }
Ejemplo n.º 14
0
        public void LoadConfiguration_Tests()
        {
            IConfigurationProvider provider = IocManager.Instance.IocContainer.Resolve <IConfigurationProvider>();
            MongoDBConfig          config   = provider.GetConfiguration <MongoDBConfig>();

            int i = 0;
        }
Ejemplo n.º 15
0
        private static async Task MainAsync()
        {
            MongoDBConfig.RegisterClassMaps();

            var builder = new ContainerBuilder();

            builder.RegisterModule(new Common.AutofacModule());
            builder.RegisterModule(new AutofacModule());

            var container = builder.Build();

            while (true)
            {
                var sw = Stopwatch.StartNew();

                var updatePricesJob = container.Resolve <UpdatePricesJob>();
                await updatePricesJob.UpdatePrices();

                sw.Stop();
                Console.WriteLine("Took " + TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds).ToString(@"dd\.hh\:mm\:ss\.fff") + " to process prices.");
                Console.WriteLine();
                sw.Restart();

                using (var alertUsersJob = container.Resolve <AlertUsersJob>())
                {
                    await alertUsersJob.SendAlerts();
                }

                sw.Stop();
                Console.WriteLine("Took " + TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds).ToString(@"dd\.hh\:mm\:ss\.fff") + " to process alerts.");
                Console.WriteLine();

                Thread.Sleep(TimeSpan.FromHours(16));
            }
        }
Ejemplo n.º 16
0
 public BaseRepository(IOptions <MongoDBConfig> mongoDBConfig)
 {
     _mongoDBConfig = mongoDBConfig.Value;
     //client = new MongoClient("mongodb://localhost:27017/RemoteVoters");
     client   = new MongoClient(_mongoDBConfig.getConnectionString());
     database = client.GetDatabase(_mongoDBConfig.Database);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// constructor
 /// </summary>
 public MongoDBWrapper()
 {
     Server         = MongoDBConfig.GetServer().Trim();
     Port           = MongoDBConfig.GetPort().Trim();
     DBName         = MongoDBConfig.GetDB().Trim();
     CollectionName = MongoDBConfig.GetCollectionName().Trim();
     mongoDB        = MongoHelper.InitializeMongo();
 }
Ejemplo n.º 18
0
        public RouletteDBContext(MongoDBConfig config)
        {
            var client = new MongoClient(config.ConnectionString);

            _db           = client.GetDatabase(config.Database);
            this._session = client.StartSession();
            this._session.StartTransaction();
        }
Ejemplo n.º 19
0
        public void RespectConnectionStingsOverrideInBase()
        {
            var collection = this.MongoDBDriver.Collection;

            this.OverrideConnectionDriver(MongoDBConfig.GetConnectionString(), MongoDBConfig.GetDatabaseString(), MongoDBConfig.GetCollectionString());

            Assert.AreNotEqual(collection, this.MongoDBDriver.Collection);
        }
Ejemplo n.º 20
0
        public void RespectNewDriverOverride()
        {
            var mongoDriver = new MongoDBDriver <BsonDocument>(MongoDBConfig.GetCollectionString());

            this.TestObject.OverrideMongoDBDriver(mongoDriver);

            Assert.AreEqual(mongoDriver.Collection, this.MongoDBDriver.Collection);
        }
Ejemplo n.º 21
0
        public void RespectDirectDriverOverride()
        {
            var mongoDriver = new MongoDBDriver <BsonDocument>(MongoDBConfig.GetCollectionString());

            this.MongoDBDriver = mongoDriver;

            Assert.AreEqual(mongoDriver.Collection, this.MongoDBDriver.Collection);
        }
Ejemplo n.º 22
0
        public StoreContext(MongoDBConfig config)
        {
            var client = new MongoClient(config.ConnectionString);

            _db = client.GetDatabase(config.Database);

            SetupIndexes();
        }
Ejemplo n.º 23
0
        public PersonContext(MongoDBConfig config)
        {
            var client = new MongoClient(config.ConnectionString);

            _db = client.GetDatabase(config.Database);

            Seed(config.IsDevelopment);
        }
Ejemplo n.º 24
0
        public void RespectDriverConnectionsOverride()
        {
            var mongoDriver = new MongoDBDriver <BsonDocument>(MongoDBConfig.GetConnectionString(), MongoDBConfig.GetDatabaseString(), MongoDBConfig.GetCollectionString());

            this.TestObject.MongoDBManager.OverrideDriver(mongoDriver);

            Assert.AreEqual(mongoDriver.Collection, this.MongoDBDriver.Collection);
        }
Ejemplo n.º 25
0
        public void MongoDBConfigTest2()
        {
            MongoDBConfig mdb = new MongoDBConfig("aaaaa", "2121", "bbbbb");

            Assert.AreEqual("aaaaa", mdb.hostName);
            Assert.AreEqual("2121", mdb.port);
            Assert.AreEqual("bbbbb", mdb.database);
        }
Ejemplo n.º 26
0
 public ConfigurationController(ILogger <ConfigurationController> logger, RepoInfoCache repoInfo, DbService dbService, GitInfoService gitInfo, MongoDBConfig dBConfig)
 {
     _repoInfo  = repoInfo;
     _dbService = dbService;
     _indexInfo = dbService.CachedColIndexInfo;
     _gitInfo   = gitInfo;
     _logger    = logger;
     _dBConfig  = dBConfig;
 }
Ejemplo n.º 27
0
        public void SaveConfiguration_Tests()
        {
            IConfigurationProvider provider = IocManager.Instance.IocContainer.Resolve <IConfigurationProvider>();
            MongoDBConfig          config   = provider.GetConfiguration <MongoDBConfig>();

            config.DatabaseName = "huang";
            provider.SaveConfiguration(config);
            int i = 0;
        }
Ejemplo n.º 28
0
        public void OverrideConnectionStrings()
        {
            var collection = this.MongoDBDriver.Collection;

            this.TestObject.OverrideMongoDBDriver(MongoDBConfig.GetConnectionString(), MongoDBConfig.GetDatabaseString(), MongoDBConfig.GetCollectionString());

            Assert.AreNotEqual(collection, this.MongoDBDriver.Collection);
            Assert.IsFalse(this.MongoDBDriver.IsCollectionEmpty());
        }
Ejemplo n.º 29
0
        public static async Task Main(string[] args)
        {
            IHost host = CreateHostBuilder(args).Build();

            // Try and fetch mongoDB and rabbitMQ configs
            var httpClient = new HttpClient();

            var rabbitMQConfigUrl = $"http://nextpipe-service.default.svc.cluster.local:5555/core/config/rabbitmq?loadBalancer=false";
            var mongoDBConfigUrl  = $"http://nextpipe-service.default.svc.cluster.local:5555/core/config/mongoDB";

            //var rabbitMQConfigUrl = $"http://localhost:5555/core/config/rabbitmq?loadBalancer=false";
            //var mongoDBConfigUrl = $"http://localhost:5555/core/config/mongoDB";

            // Fetch rabbitMQConfig
            try
            {
                var result = await httpClient.GetAsync(rabbitMQConfigUrl);

                if (!result.IsSuccessStatusCode)
                {
                    throw new SystemException($"Couldn't resolve rabbitMQ configuration from controlplane");
                }

                var content = await result.Content.ReadAsStringAsync();

                rabbitConfig = JsonConvert.DeserializeObject <RabbitMQConfig>(content);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }

            try
            {
                var result = await httpClient.GetAsync(mongoDBConfigUrl);

                if (!result.IsSuccessStatusCode)
                {
                    throw new SystemException($"Couldn't resolve mongoDB configuration from controlPlane");
                }

                var content = await result.Content.ReadAsStringAsync();

                mongoConfig = JsonConvert.DeserializeObject <MongoDBConfig>(content);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw ex;
            }

            host.Run();
        }
Ejemplo n.º 30
0
        public void CanUseMultipleWithFunc()
        {
            var newCollection = MongoFactory.GetCollection <BsonDocument>(MongoDBConfig.GetConnectionString(), MongoDBConfig.GetDatabaseString(), MongoDBConfig.GetCollectionString());

            MongoDriverManager <BsonDocument> newDriver = new MongoDriverManager <BsonDocument>(() => newCollection, this.TestObject);

            this.ManagerStore.Add("test", newDriver);

            Assert.AreNotEqual(this.TestObject.MongoDBDriver, (MongoDriverManager <BsonDocument>) this.ManagerStore["test"]);
            Assert.AreNotEqual(this.TestObject.MongoDBManager.Get(), ((MongoDriverManager <BsonDocument>) this.ManagerStore["test"]).Get());
            Assert.AreEqual(newCollection, ((MongoDriverManager <BsonDocument>) this.ManagerStore["test"]).GetMongoDriver().Collection);
        }