示例#1
0
        public async Task <int> SaveGift(Gift gift)
        {
            var giftDocument = new BsonDocument
            {
                { "name", BsonValue.Create(gift.Name) }
            };

            var settings = MongoDB.Driver.MongoClientSettings.FromUrl(
                new MongoDB.Driver.MongoUrl(ConnectionString)
                );

            settings.SslSettings =
                new MongoDB.Driver.SslSettings()
            {
                EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
            };
            var mongoClient = new MongoDB.Driver.MongoClient(settings);

            var mongoDb = mongoClient.GetDatabase(DatabaseName);

            var collection = mongoDb.GetCollection <BsonDocument>(CollectionName);

            return(await Task.Run(() =>
            {
                var result = collection.InsertOneAsync(giftDocument);

                return result.Id;
            }
                                  ));
        }
示例#2
0
        public IActionResult Index()
        {
            var connectionString = Startup.ConnectionString;
            var client           = new MongoDB.Driver.MongoClient(connectionString);
            var db         = client.GetDatabase("foo");
            var collection = db.GetCollection <BsonDocument>("bar");

            return(View());
        }
示例#3
0
        public SharedController(IFilesService filesService, IConfiguration config)
        {
            this.config       = config;
            this.filesService = filesService;
            var mongoClient = new MongoDB.Driver.MongoClient(config.GetConnectionString("MongoDbConnection"));
            var database    = mongoClient.GetDatabase(nameof(WitDrive));

            this.fsc = new FileSystemClient(database, chunkSize: 32768);
        }
        public static ILoggerFactory AddMongodb(this ILoggerFactory factory, string connetionString = "mongodb://127.0.0.1:27017/logging")
        {
            var mongoUrl = new MongoDB.Driver.MongoUrl(connetionString);
            var client   = new MongoDB.Driver.MongoClient(mongoUrl);

            factory.AddProvider(new MongodbProvider(client.GetDatabase(mongoUrl.DatabaseName)));

            return(factory);
        }
示例#5
0
        private async Task AddToMongoCollection()
        {
            var mongoClient = new MongoDB.Driver.MongoClient("mongodb://localhost:27017");
            var db          = mongoClient.GetDatabase("IntegrationTest");
            var col         = db.GetCollection <TestClass>("TestClass");
            await col.InsertOneAsync(new TestClass { Test = 1 });

            helper.WriteLine("Mongodb document inserted");
        }
        public AccountController(IEmailSender emailSender, UserManager <User> userManager, IConfiguration config)
        {
            this.emailSender = emailSender;
            this.userManager = userManager;
            var mongoClient = new MongoDB.Driver.MongoClient(config.GetConnectionString("MongoDbConnection"));
            var database    = mongoClient.GetDatabase(nameof(WitDrive));

            this.space = long.Parse(config.GetSection("DiskSpace").GetSection("Space").Value);
            this.fsc   = new FileSystemClient(database, chunkSize: 32768);
        }
示例#7
0
        protected override void ConfigureEventStore()
        {
            var mongoDbConnectionString = Configuration.GetConnectionString("Merp-Accountancy-EventStore");
            var mongoDbDatabaseName     = MongoDB.Driver.MongoUrl.Create(mongoDbConnectionString).DatabaseName;
            var mongoClient             = new MongoDB.Driver.MongoClient(mongoDbConnectionString);

            Services.AddSingleton(mongoClient.GetDatabase(mongoDbDatabaseName));
            Services.AddTransient <IEventStore, MementoFX.Persistence.MongoDB.MongoDbEventStore>();
            Services.AddTransient <IRepository, MementoFX.Persistence.Repository>();
        }
示例#8
0
        public DirController(IDirService dirService, IConfiguration config)
        {
            this.config     = config;
            this.dirService = dirService;
            var mongoClient = new MongoDB.Driver.MongoClient(config.GetConnectionString("MongoDbConnection"));
            var database    = mongoClient.GetDatabase(nameof(WitDrive));

            this.fsc   = new FileSystemClient(database, chunkSize: 32768);
            this.space = long.Parse(config.GetSection("DiskSpace").GetSection("Space").Value);
        }
示例#9
0
        public void ConfigureEventStore()
        {
            var mongoDbConnectionString = Configuration.GetConnectionString("OnTime-TaskManagement-EventStore");
            var mongoDbDatabaseName     = MongoDB.Driver.MongoUrl.Create(mongoDbConnectionString).DatabaseName;
            var mongoClient             = new MongoDB.Driver.MongoClient(mongoDbConnectionString);

            Services.AddSingleton(mongoClient.GetDatabase(mongoDbDatabaseName));

            Services.AddTransient <IEventStore, Memento.Persistence.MongoDB.MongoDbEventStore>();

            Services.AddTransient <IRepository, Memento.Persistence.Repository>();
        }
示例#10
0
        public AuthController(IConfiguration config, IMapper mapper, IAuthService service,
                              UserManager <User> userManager, SignInManager <User> signInManager)
        {
            this.config        = config;
            this.mapper        = mapper;
            this.service       = service;
            this.userManager   = userManager;
            this.signInManager = signInManager;
            var mongoClient = new MongoDB.Driver.MongoClient(config.GetConnectionString("MongoDbConnection"));
            var database    = mongoClient.GetDatabase(nameof(WitDrive));

            this.fsc = new FileSystemClient(database, chunkSize: 32768);
        }
示例#11
0
        public AlertingRepository(string connection)
        {
            if (string.IsNullOrWhiteSpace(connection))
            {
                connection = "mongodb://localhost:27017";
            }

            _client = new MongoDB.Driver.MongoClient(connection);
            _database = _client.GetDatabase("local",  null);
            _alertTypes = _database.GetCollection<AlertType>("alerttypes");

            var filter = new MongoDB.Bson.BsonDocument();
            long count = _alertTypes.Count(filter);

            // AddTestData();
        }
        public IActionResult Add()
        {
            var collection = _mongoDbClient.GetDatabase("admin").GetCollection <Aluno>("aluno");

            collection.InsertMany(new[] {
                new Aluno {
                    Nome = "Roberto Ramos", Idade = 38
                },
                new Aluno {
                    Nome = "Zoe Ramos", Idade = 3
                },
                new Aluno {
                    Nome = "Chloe Ramos", Idade = 1
                }
            });
            return(Ok("3 alunos foram adicionados"));
        }
示例#13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var rmqConfig     = ConfigurationReader.ReadConfiguration <RabbitMqConfiguration>();
            var fileConfig    = ConfigurationReader.ReadConfiguration <FileConfiguration>();
            var mysqlConfig   = ConfigurationReader.ReadConfiguration <MySqlConfiguration>();
            var mongoDbConfig = ConfigurationReader.ReadConfiguration <MongoDbConfiguration>();
            var serviceConfig = ConfigurationReader.ReadConfiguration <ServiceConfiguration>();

            if (string.IsNullOrWhiteSpace(serviceConfig?.Secret))
            {
                throw new Exception($"Please set {nameof(ServiceConfiguration.Secret)} in the {nameof(ServiceConfiguration)}!");
            }

            services.AddSingleton(serviceConfig);

            if (mongoDbConfig != null)
            {
                string connectionString;

                if (mongoDbConfig.UseDnsSrv)
                {
                    connectionString = $"mongodb+srv://{mongoDbConfig.User}:{mongoDbConfig.Password}" +
                                       $"@{mongoDbConfig.Host}/{mongoDbConfig.Database}";
                }
                else
                {
                    connectionString = $"mongodb://{mongoDbConfig.User}:{mongoDbConfig.Password}" +
                                       $"@{mongoDbConfig.Host}:{mongoDbConfig.Port}/{mongoDbConfig.Database}";
                }

                var client = new MongoDB.Driver.MongoClient(connectionString);
                var db     = client.GetDatabase(mongoDbConfig.Database);

                services.AddSingleton(db);
                services.AddScoped <ISnippetRepository, MongoDbSnippetRepository>();
                services.AddScoped <IUserRepository, MongoDbUserRepository>();
                services.AddScoped <ISnippetQuery, MongoDbSnippetQuery>();
                services.AddScoped <IUserQuery, MongoDbUserQuery>();
            }
            else if (mysqlConfig != null)
            {
                services.AddSingleton(mysqlConfig);
                services.AddScoped <ISnippetRepository, MySqlSnippetRepository>();
                services.AddScoped <IUserRepository, MySqlUserRepository>();
                services.AddScoped <ISnippetQuery, MySqlSnippetQuery>();
                services.AddScoped <IUserQuery, MySqlUserQuery>();
                services.AddScoped <MySqlDbContext>();
            }
            else
            {
                if (fileConfig == null)
                {
                    fileConfig = new FileConfiguration();
                }

                services.AddSingleton(fileConfig);
                services.AddScoped <ISnippetRepository, FileSnippetRepository>();
                services.AddScoped <IUserRepository, FileUserRepository>();
                services.AddScoped <ISnippetQuery, FileSnippetQuery>();
                services.AddScoped <IUserQuery, FileUserQuery>();
            }

            if (rmqConfig != null)
            {
                rmqConfig.QueueName = "SnippetStudio.Service";
                services.AddCoseiRabbitMq(rmqConfig);
            }

            services.AddCosei();

            services.AddScoped <SnippetService>();
            services.AddScoped <UserService>();
            services.AddScoped <TokenService>();
            services.AddSignalR();

            var validationParameters = TokenService.GetValidationParameters(serviceConfig.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.TokenValidationParameters = validationParameters;
            });

            services.AddControllers();
        }
示例#14
0
        static async Task Main(string[] args)
        {
            var        LightBulbIdentifier = new Guid("11223344-5566-7788-99AA-BBCCDDEEFF00");
            QueryModel LightBulbQueryModel;

            var CancellationTokenSource = new CancellationTokenSource();

            var MongoClient     = new MongoDB.Driver.MongoClient("mongodb://mongo:27017");
            var MongoSmartHome  = MongoClient.GetDatabase("smart_home");
            var MongoLightBulbs = MongoSmartHome.GetCollection <QueryModel>("light_bulbs");
            var MongoFilter     = MongoDB.Driver.Builders <QueryModel> .Filter.Eq(
                nameof(QueryModel.Identifier),
                LightBulbIdentifier
                );

            var MongoLightBulbsIt = await MongoLightBulbs.FindAsync <QueryModel>(MongoFilter);

            if (await MongoLightBulbsIt.MoveNextAsync() && null != MongoLightBulbsIt.Current && 0 < MongoLightBulbsIt.Current.Count())
            {
                LightBulbQueryModel = MongoLightBulbsIt.Current.First();
            }
            else
            {
                LightBulbQueryModel = new QueryModel()
                {
                    Identifier = LightBulbIdentifier
                };
                await MongoLightBulbs.InsertOneAsync(LightBulbQueryModel);
            }
            LightBulbQueryModel.PropertyChanged += (object sender, PropertyChangedEventArgs e) =>
            {
                var QueryModel = sender as QueryModel;
                switch (e.PropertyName)
                {
                case null:
                    CancellationTokenSource.Cancel();
                    break;

                default:
                    Console.WriteLine(
                        "The bulb is now the color {0} with brightness {1} based on {2}",
                        QueryModel.Color,
                        QueryModel.Brightness,
                        QueryModel.EventNumber
                        );
                    break;
                }
            };
            LightBulbQueryModel.NotifyPropertyChanged("Everything");
            System.AppDomain.CurrentDomain.ProcessExit += (object sender, EventArgs e) =>
            {
                Console.Write("Snapshoting event number {0}...", LightBulbQueryModel.EventNumber);
                MongoLightBulbs.FindOneAndReplace <QueryModel>(
                    MongoFilter,
                    LightBulbQueryModel
                    );
                Console.WriteLine(" Success!");
            };

            using (var connection = EventStoreConnection.Create(
                       ConnectionSettings.Create().UseConsoleLogger().FailOnNoServerResponse(),
                       new Uri("tcp://eventstore:1113")
                       ))
            {
                await connection.ConnectAsync();

                LightBulbQueryModel.LinkTo(connection, LightBulbIdentifier);

                while (true)
                {
                    ;
                }
            }
        }
示例#15
0
 static PostToDB()
 {
     HttpClient    = new HttpClient();
     MongoClient   = new MongoDB.Driver.MongoClient("mongodb://127.0.0.1:27017");
     MongoDatabase = MongoClient.GetDatabase("spider");
 }
示例#16
0
        public void FileToDatabase(object obj)
        {
            MongoDB.Driver.MongoClient    client   = new MongoDB.Driver.MongoClient("mongodb://localhost");
            MongoDB.Driver.IMongoDatabase dataBase = client.GetDatabase("UserCenter");
            MongoDB.Driver.IMongoCollection <UserInfo> userInfoDb = dataBase.GetCollection <UserInfo>("UserInfo");
            int successNumber = 0;
            int repeatNumber  = 0;
            int totaleNumber  = 0;

            for (int ver = 136; ver < 256; ver++)
            {
                WriterFile(obj.ToString() + "线程开始同步");
                string versionName  = string.Format("{0}_登录成功(1)_.txt", ver.ToString("D3"));
                string fileFullPath = txtFilePath.Text + "\\" + versionName;
                if (File.Exists(fileFullPath))
                {
                    fileFullPath = txtFilePath.Text + "\\" + versionName;
                    WriterFile(obj.ToString() + "线程开始同步" + versionName);
                    StreamReader sr = new StreamReader(fileFullPath, Encoding.Default);
                    String       line;
                    DateTime     currentTime = DateTime.Now;
                    line = sr.ReadToEnd();
                    sr.Close();

                    string[] lineArray = Regex.Split(line, "\r\n");
                    for (int i = 0; i < lineArray.Length; i++)
                    {
                        MatchCollection collection = Regex.Matches(lineArray[i], "^(.*)----(.*)$");
                        if (collection.Count > 0)
                        {
                            UserInfo userInfo = new UserInfo {
                                UserName = collection[0].Groups[1].Value, Password = collection[0].Groups[2].Value
                            };
                            totaleNumber++;
                            //MongoDB.Driver.Builders<UserInfo>.Filter filter=
                            //MongoDB.Driver.Builders<UserInfo>.Filter;
                            MongoDB.Driver.FilterDefinitionBuilder <UserInfo> filerBuilder = new MongoDB.Driver.FilterDefinitionBuilder <UserInfo>();
                            MongoDB.Driver.FilterDefinition <UserInfo>        filter       = filerBuilder.Where(c => c.UserName == userInfo.UserName && c.Password == userInfo.Password);
                            if (userInfoDb.Count(filter) == 0)
                            {
                                userInfoDb.InsertOne(userInfo);
                                successNumber++;
                            }
                            else
                            {
                                repeatNumber++;
                            }
                            if (totaleNumber % 100000 == 0)
                            {
                                WriterFile(string.Format(obj.ToString() + "线程:共{0},成功{1},失败{2},用时{3},当前时间:{4}",
                                                         totaleNumber, successNumber, repeatNumber, DateTime.Now - currentTime, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                                currentTime = DateTime.Now;
                            }
                        }
                    }

                    lineArray = null;
                    GC.Collect();
                }
            }
            WriterFile(obj + "线程结束同步");
        }