public ConnectionProviderTests()
        {
            db1 = A.Fake <MongoDbConnection>();
            db2 = A.Fake <MongoDbConnection>();

            provider = new ConnectionProvider();
        }
        public static IEnumerable AutoAssertion(String DataSetName)
        {
            MongoDbConnection           mongoDbConnection = new MongoDbConnection();
            Dictionary <String, Object> reqNames          = mongoDbConnection.getRequestData(DataSetName, "Request");
            Dictionary <String, Object> respNames         = mongoDbConnection.getRequestData(DataSetName, "Response");

            int dataSets  = 0;
            int arguments = 0;

            dataSets = CalculateDataSetParams(reqNames, ref arguments);

            for (int i = 1; i < dataSets + 1; i++)
            {
                //TODO create testcases objects using reflection
                if (arguments == 1)
                {
                    yield return(new TestCaseData(reqNames["Request" + i + "1"]).Returns(respNames["Response" + i]));
                }
                else if (arguments == 2)
                {
                    yield return(new TestCaseData(reqNames["Request" + i + "1"], reqNames["Request" + i + "2"]).Returns(respNames["Response" + i]));
                }
                else if (arguments == 3)
                {
                    yield return(new TestCaseData(reqNames["Request" + i + "1"], reqNames["Request" + i + "2"], reqNames["Request" + i + "3"]).Returns(respNames["Response" + i]));
                }
            }
        }
Example #3
0
        public static void StartDatabaseConnection()
        {
            const string ConnectionString = "mongodb://*****:*****@test-shard-00-00-imtir.mongodb.net:27017,test-shard-00-01-imtir.mongodb.net:27017,test-shard-00-02-imtir.mongodb.net:27017/test?ssl=true&replicaSet=test-shard-0&authSource=admin&retryWrites=true";

            MongoDbConnection.InitializeAndStartConnection(ConnectionString, databaseName: "MilitaryTCG");
            CrudFaction = new Crud <Faction>();
        }
        public static IEnumerable AutoAutoAssertion1(String MultipleDataSetName)
        {
            String[] DataSetNames = MultipleDataSetName.Split(',');
            for (int j = 0; j < DataSetNames.Length - 1; j++)
            {
                String                      DataSetName       = DataSetNames[j + 1];
                MongoDbConnection           mongoDbConnection = new MongoDbConnection();
                ClassDetails                classDetails      = mongoDbConnection.getClassDetails(DataSetName);
                Dictionary <String, Object> reqNames          = mongoDbConnection.getRequestData(DataSetName, "Request");
                Dictionary <String, Object> respNames         = mongoDbConnection.getRequestData(DataSetName, "Response");

                int dataSets  = 0;
                int arguments = 0;
                dataSets = CalculateDataSetParams(reqNames, ref arguments);

                for (int i = 1; i < dataSets + 1; i++)
                {
                    //TODO create testcases objects using reflection
                    if (arguments == 1)
                    {
                        yield return(new TestCaseData(classDetails, reqNames["Request" + i + "1"]).Returns(respNames["Response" + i]));
                    }
                    else if (arguments == 2)
                    {
                        yield return(new TestCaseData(classDetails, reqNames["Request" + i + "1"], reqNames["Request" + i + "2"]).Returns(respNames["Response" + i]));
                    }
                    else if (arguments == 3)
                    {
                        yield return(new TestCaseData(classDetails, reqNames["Request" + i + "1"], reqNames["Request" + i + "2"], reqNames["Request" + i + "3"]).Returns(respNames["Response" + i]));
                    }
                }
            }
        }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connection = new MongoDbConnection(new ConnectionConfiguration()
            {
                ////This connection string should be used when we run service using Docker as it need proxy communication to local machine
                //ConnectionString = "mongodb://host.docker.internal:27017",

                ////This connection string should be used when we run service from local machine
                ConnectionString = "mongodb://localhost:27017",
                Database         = "TodoApplicationDatabase"
            });

            services.TryAddSingleton <IMongoDbConnection>(connection);
            services.TryAddSingleton <IToDoRepository, ToDoRepository>();


            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "ToDo Application API", Version = "v1"
                });
            });
        }
Example #6
0
        public MaintenanceTools()
        {
            var conStr = ConfigurationManager.ConnectionStrings["mongoServer"].ToString();
            var dbName = ConfigurationManager.ConnectionStrings["dbName"].ToString();

            _connection = new MongoDbConnection(conStr, dbName);
            _database   = new Database(new TicketAutUser(string.Empty, string.Empty), _connection);
        }
Example #7
0
        public Keywords()
        {
            InitializeComponent();
            const string CONNECTIONSTRING = "mongodb://*****:*****@test-shard-00-00-imtir.mongodb.net:27017,test-shard-00-01-imtir.mongodb.net:27017,test-shard-00-02-imtir.mongodb.net:27017/test?ssl=true&replicaSet=test-shard-0&authSource=admin&retryWrites=true";

            MongoDbConnection.InitializeAndStartConnection(CONNECTIONSTRING, databaseName: "MilitaryTCG");
            _crudKeyword = new Crud <Keyword>();
        }
        public void Get_collection_calls_mongo_database_get_collection()
        {
            IMongoDbConnection mongoDbConnection = new MongoDbConnection(_mockMongoClient.Object, _model);

            Assert.Equal(_mockSimpleRecords.Object, mongoDbConnection.GetCollection <SimpleRecord>());
            _mockMongoDatabase
            .Verify(mongoDatabase => mongoDatabase.GetCollection <SimpleRecord>("simpleRecords", It.IsAny <MongoCollectionSettings>()), Times.Once);
        }
Example #9
0
        public MaintenanceTools()
        {
            var conStr = ConfigurationManager.ConnectionStrings["mongoServer"].ToString();
            var dbName = ConfigurationManager.ConnectionStrings["dbName"].ToString();

            _connection = new MongoDbConnection(conStr, dbName);
            _database = new Database(new TicketAutUser(string.Empty, string.Empty), _connection);
        }
        public async Task Drop_database_async_calls_mongo_client_drop_database_async()
        {
            IMongoDbConnection mongoDbConnection = new MongoDbConnection(_mockMongoClient.Object, _model);
            await mongoDbConnection.DropDatabaseAsync();

            _mockMongoClient
            .Verify(mongoClient => mongoClient.DropDatabaseAsync("testdb", It.IsAny <CancellationToken>()), Times.Once);
        }
        public async Task Get_database_async_calls_mongo_client_get_database()
        {
            IMongoDbConnection mongoDbConnection = new MongoDbConnection(_mockMongoClient.Object, _model);

            Assert.Equal(_mockMongoDatabase.Object, await mongoDbConnection.GetDatabaseAsync());
            _mockMongoClient
            .Verify(mongoClient => mongoClient.GetDatabase("testdb", It.IsAny <MongoDatabaseSettings>()), Times.Once);
        }
Example #12
0
 public void Add(string name, MongoDbConnection connection, bool useAsDefault)
 {
     connections.Add(name.ToLowerInvariant(), connection);
     if (useAsDefault)
     {
         connections.Add("UseAsDefault".ToLowerInvariant(), connection);
     }
 }
        public void Drop_database_calls_mongo_client_drop_database()
        {
            IMongoDbConnection mongoDbConnection = new MongoDbConnection(_mockMongoClient.Object, _model);

            mongoDbConnection.DropDatabase();
            _mockMongoClient
            .Verify(mongoClient => mongoClient.DropDatabase("testdb", It.IsAny <CancellationToken>()), Times.Once);
        }
Example #14
0
        public async void RunMigration()
        {
            EnsureEmptyCollection <MigrationDocument>();
            EnsureEmptyCollection <KewlEntity>();

            var db = new MongoDbConnection(GetDb());

            var services = new ServiceCollection();

            var runner = new YoloMigrationRunner(
                services.BuildServiceProvider(),
                "staging",
                ConnectionString,
                GetDbName(),
                A.Fake <IDistributedAppLockProvider>(),
                typeof(YoloMigrationRunnerTests).GetAssembly()
                );

            var storage = new MongoMigrationStorage();

            var connectionProvider = new ConnectionProvider();

            connectionProvider.Add("x", db, true);

            // setup some state
            var five = new KewlEntity {
                Reference = 5
            };
            await db.InsertAsync <KewlEntity>(five);

            var seven = new KewlEntity {
                Reference = 7
            };
            await db.InsertAsync <KewlEntity>(seven);

            // let's say that migration01 has already been completed
            await storage.MarkAsCompleteAsync(new MongoMigrationContext { ConnectionProvider = connectionProvider }, new Migration01(), 123);

            await runner.UpgradeAsync();

            // are all the migrations marked as completed?
            var allDocs = GetAll <MigrationDocument>();

            Assert.Contains(allDocs, x => x.Name == nameof(Migration01) && x.MigrationCompleted);
            Assert.Contains(allDocs, x => x.Name == nameof(Migration02) && x.MigrationCompleted);
            Assert.Contains(allDocs, x => x.Name == nameof(Migration03) && x.MigrationCompleted);

            // check the state of the db
            var fiveUp = await db.FirstOrDefaultAsync <KewlEntityUpdated>(x => x.Id == five.Id);

            Assert.Equal("5", fiveUp.Reference);
            Assert.Equal("Ulla Henriksen", fiveUp.Mucho);

            var sevenUp = await db.FirstOrDefaultAsync <KewlEntityUpdated>(x => x.Id == seven.Id);

            Assert.Equal("7", sevenUp.Reference);
            Assert.Equal("Bubbly", sevenUp.Mucho);
        }
        public static IMongoDbConnection GetConnection()
        {
            var urlBuilder = new MongoUrlBuilder(ConnectionString)
            {
                DatabaseName = GetDatabaseName()
            };

            return(MongoDbConnection.FromUrl(urlBuilder.ToMongoUrl()));
        }
        private static ConnectionProvider ConnectionProviderFromString(string mongoConnectionString, string mongoDbName)
        {
            var provider = new ConnectionProvider();
            var client   = new MongoClient(mongoConnectionString);
            var db       = client.GetDatabase(mongoDbName);
            var conn     = new MongoDbConnection(db);

            provider.Add("yolo", conn, true);

            return(provider);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            MongoDbConnection.InitializeAndStartConnection(databaseName: "pkmndb");
            BsonRegister();
            services.AddSingleton <Crud <MonsterCardEntity> >();
            services.AddSingleton <Crud <CardImageEntity> >();
            services.AddSwaggerGen();
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddSignalR();
        }
Example #18
0
        private void InterfaceOrientedProgrammingExample()
        {
            var mongoDb   = new MongoDbConnection();
            var sqlServer = new SqlServerConnection();
            var db        = new Database(mongoDb);

            db.OpenConnection();
            db.CloseConnection();
            db = new Database(sqlServer);
            db.OpenConnection();
            db.CloseConnection();
        }
        public override TestResult Execute(TestExecutionContext context)
        {
            TestResult testResults = null;

            try
            {
                command.Execute(context);
            }
            catch (Exception ex)
            {
                String msg = ex.Message;
            }
            testResults = context.CurrentResult;
            if (context.CurrentResult.FailCount > 0)
            {
                context.CurrentResult.SetResult(ResultState.Failure);
            }
            else
            {
                context.CurrentResult.SetResult(ResultState.Success);
            }

            TestMethodDataEntity testMethodDataEntity = new TestMethodDataEntity();

            testMethodDataEntity.TestMethodName    = context.CurrentTest.MethodName;
            testMethodDataEntity.TestClassName     = context.CurrentTest.ClassName;
            testMethodDataEntity.TestDataReference = JsonConvert.SerializeObject(context.CurrentTest.Arguments);
            testMethodDataEntity.Result            = (context.CurrentResult.ResultState == ResultState.Success) ? true : false;
            String message = "";

            if (!testMethodDataEntity.Result)
            {
                for (int i = 0; i < context.CurrentResult.AssertionResults.Count; i++)
                {
                    message += context.CurrentResult.AssertionResults[i].Message;
                }
                testMethodDataEntity.Message = message;
                // TODO: Buidling custom error messages
                // Classname, methodname and argument list is available.
                // Based on the argument list get the expected response object
                // Get the actual response object --------------------------------- NEED TO CHECK THIS
                // Get all the properties via reflection
                // Compare and build a custom error message
            }

            MongoDbConnection mongoDbConnection = new MongoDbConnection();

            mongoDbConnection.upsertTestResultsData(testMethodDataEntity);

            return(testResults);
        }
        public static IServiceCollection AddSecurityLayer(this IServiceCollection services, IConfiguration configuration)
        {
            ContextFactory.RegisterObject(new SecurityContext(services, configuration));
            var connection = MongoDbConnection.FromConnectionString(configuration["ConnectionString"]);

            services.AddTransient <IDataContext, SecurityDataContext>((s)
                                                                      => new SecurityDataContext(connection));

            var mapper = new AcubecMapper(new SecurityMapper());

            services.AddSingleton(typeof(IMapper), mapper);
            services.AddUtilities();
            return(services);
        }
Example #21
0
        public CardEditor()
        {
            InitializeComponent();


            const string ConnectionString = "mongodb://*****:*****@test-shard-00-00-imtir.mongodb.net:27017,test-shard-00-01-imtir.mongodb.net:27017,test-shard-00-02-imtir.mongodb.net:27017/test?ssl=true&replicaSet=test-shard-0&authSource=admin&retryWrites=true";

            MongoDbConnection.InitializeAndStartConnection(ConnectionString, databaseName: "MilitaryTCG");

            _keywordCrud = new Crud <Keyword>();
            _cardCrud    = new Crud <Card>();
            _crudFaction = new Crud <Faction>();

            _cardInfoPage = new CardInfoPage(FillFactionComboBox());

            FillRarityComboBox();
            FillCombobox();
            FillListBox();
        }
Example #22
0
        private static void handleBatch <T>(MongoDbConnection dbConnection, NotificationHandler notificationHandler) where T : IGUIDable, INotifiable
        {
            ConsoleWrite($">> Checking for {typeof(T)}...");
            MongoRepository <T> repo = new MongoRepository <T>(dbConnection);

            // Find new objects
            List <T> foundForms = repo.Find(x => x.NotificationSent == false).ToList();

            foreach (T form in foundForms)
            {
                ConsoleWrite($">> Enqueuing notifications for {form.Id} ({form.GetType().Name})");
                notificationHandler.AddNotification(form);
            }

            // Send all notifications that we queued
            notificationHandler.Flush();

            // Mark objects that suceeded as complete
            foreach (T form in foundForms.Where(f => f.NotificationSent == true))
            {
                ConsoleWrite($">> Marking {form.Id} as notified ({form.GetType().Name})");
                repo.Update(form);
            }
        }
Example #23
0
 public RoomsXmlMongoImporter()
 {
     this.mongoContext = new MongoDbConnection();
     this.rooms        = new List <MongoModels.Room>();
 }
 public RemoveDataCommiter(MongoDbConnection mongoDbConnection, IEntitiesForRemovingProvider <TKey, TEntity> entitiesProvider)
 {
     this.mongoDbConnection = mongoDbConnection ?? throw new ArgumentNullException($"{nameof(mongoDbConnection)} should not be null");
     this.entitiesProvider  = entitiesProvider ?? throw new ArgumentNullException($"{nameof(entitiesProvider)} should not be null");
 }
Example #25
0
        public ServiceResult Migrate(MogoMigrateView view)
        {
            if (!HttpWeb.UserName.Equal("admin"))
            {
                return(ServiceResult.Failure("当前操作用户名非admin,不能进行该操作"));
            }

            if (view.MongoTableName.IsNullOrEmpty())
            {
                return(ServiceResult.Failure("Mongodb数据库不能为空"));
            }

            if (view.MongoConnectionString.IsNullOrEmpty())
            {
                return(ServiceResult.Failure("Mongodb链接字符串不能为空"));
            }

            var user = Resolve <IUserService>().GetSingle(HttpWeb.UserId);

            if (user.Status != Status.Normal)
            {
                return(ServiceResult.Failure("用户状态不正常,不能进行该操作"));
            }

            if (!user.UserName.Equal("admin"))
            {
                return(ServiceResult.Failure("当前操作用户名非admin,不能进行该操作"));
            }

            if (!view.UserTable.Equals("User_User"))
            {
                return(ServiceResult.Failure("用户数据表填写出错,不能进行该操作"));
            }

            //if (!view.ProjectId.Equals(HttpWeb.Token.ProjectId.ToString())) {
            //    return ServiceResult.Failure("项目Id填写错误,不能进行该操作");
            //}

            if (!view.Key.Equals(RuntimeContext.Current.WebsiteConfig.OpenApiSetting.Key))
            {
                return(ServiceResult.Failure("秘钥填写错误,不能进行该操作"));
            }

            var connection = new MongoDbConnection {
                ConnectionString = view.MongoConnectionString,
                Database         = view.MongoTableName
            };
            var types = GetMongoEntityTypes();

            foreach (var type in types)
            {
                //// 使用Mongodb的上下文链接字符串
                //MongoRepositoryConnection.MongoDbConnectionContext = connection;
                //// 读取需要迁移数据库中所有的数据
                //var sourceResult = DynamicService.ResolveMethod(type.Name, "GetList");
                //if (!sourceResult.Item1.Succeeded) {
                //    return ServiceResult.Failure($"表{type.Name}数据获取失败:" + sourceResult.Item2.ToString());
                //}

                //// 切换数据库,当前配置数据库
                //MongoRepositoryConnection.MongoDbConnectionContext = null;
                //// 批量插入数据库中
                //var addResult = DynamicService.ResolveMethod(type.Name, "AddMany", sourceResult.Item2);
                //if (!addResult.Item1.Succeeded) {
                //    return ServiceResult.Failure($"表{type.Name}数据添加失败:" + sourceResult.Item2.ToString());
                //}
            }

            Resolve <ITableService>().Log("数据迁移成功");
            Resolve <ISmsService>().SendRaw(Resolve <ISmsService>().OpenMobile(), "您的数据已迁移成功,请悉知。");
            return(ServiceResult.Success);
        }
 public void NullUrlThrowsException()
 {
     MongoDbConnection.FromUrl(null);
 }
 public MongoDbConnection_GetCollection_Tests()
 {
     connection = new MongoDbConnection(GetDb());
 }
Example #28
0
 public InsertDataCommiter(MongoDbConnection entitiesProvider, IEntitiesForInsertingProvider <TEntity> usersProvider)
 {
     this.entitiesProvider = entitiesProvider ?? throw new ArgumentNullException($"{nameof(entitiesProvider)} should not be null");
     this.usersProvider    = usersProvider ?? throw new ArgumentNullException($"{nameof(usersProvider)} should not be null");
 }
        public void InvalidConfigForConnection()
        {
            var connection = MongoDbConnection.FromConfig("ThisConfigNameDoesntExist");

            Assert.IsNull(connection);
        }
        public void ConnectionFromConnectionString()
        {
            var connection = MongoDbConnection.FromConnectionString("mongodb://localhost:27017/MongoFrameworkTests");

            Assert.IsNotNull(connection);
        }
 public MongoDbConnection_Insert_Tests()
 {
     connection = new MongoDbConnection(GetDb());
 }
 public RoomsXmlMongoImporter()
 {
     this.mongoContext = new MongoDbConnection();
        this.rooms = new List<MongoModels.Room>();
 }