// static constructor
        static DriverTestConfiguration()
        {
            var connectionString = CoreTestConfiguration.ConnectionString.ToString();

            var mongoUrl = new MongoUrl(connectionString);
            var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
            if (!clientSettings.WriteConcern.IsAcknowledged)
            {
                clientSettings.WriteConcern = WriteConcern.Acknowledged; // ensure WriteConcern is enabled regardless of what the URL says
            }

            var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");
            if (serverSelectionTimeoutString == null)
            {
                serverSelectionTimeoutString = "10000";
            }
            clientSettings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString));
            clientSettings.ClusterConfigurator = cb =>
            {
                var traceSource = new TraceSource("mongodb-tests", SourceLevels.Information);
                traceSource.Listeners.Clear(); // remove the default listener
                var listener = new ConsoleTraceListener();
                traceSource.Listeners.Add(listener);
                cb.TraceWith(traceSource);
            };

            __client = new MongoClient(clientSettings);
            __databaseNamespace = mongoUrl.DatabaseName == null ? CoreTestConfiguration.DatabaseNamespace : new DatabaseNamespace(mongoUrl.DatabaseName);
            __collectionNamespace = new CollectionNamespace(__databaseNamespace, "testcollection");
        }
Example #2
0
        public async Task RunAsync(int numConcurrentWorkers, Action<ClusterBuilder> configurator)
        {
            var settings = new MongoClientSettings();
            settings.ClusterConfigurator = configurator;

            var client = new MongoClient(settings);

            var db = client.GetDatabase("foo");
            var collection = db.GetCollection<BsonDocument>("bar");

            Console.WriteLine("Press Enter to begin");
            Console.ReadLine();

            Console.WriteLine("Clearing Data");
            await ClearData(collection);
            Console.WriteLine("Inserting Seed Data");
            await InsertData(collection);

            Console.WriteLine("Running CRUD (errors will show up as + (query error) or * (insert/update error))");
            var tasks = new List<Task>();
            for (int i = 0; i < numConcurrentWorkers; i++)
            {
                tasks.Add(DoWork(collection));
            }

            Console.WriteLine("Press Enter to shutdown");
            Console.ReadLine();

            _cancellationTokenSource.Cancel();
            Task.WaitAll(tasks.ToArray());
        }
Example #3
0
        public void Run(int numConcurrentWorkers, Action<ClusterBuilder> configurator)
        {
            var settings = new MongoClientSettings();
            settings.ClusterConfigurator = configurator;

            var client = new MongoClient(settings);
#pragma warning disable 618
            var server = client.GetServer();
#pragma warning restore 618

            var db = server.GetDatabase("foo");
            var collection = db.GetCollection<BsonDocument>("bar");

            Console.WriteLine("Press Enter to begin");
            Console.ReadLine();

            Console.WriteLine("Clearing Data");
            ClearData(collection);
            Console.WriteLine("Inserting Seed Data");
            InsertData(collection);

            Console.WriteLine("Running CRUD (errors will show up as + (query error) or * (insert/update error))");
            for (int i = 0; i < numConcurrentWorkers; i++)
            {
                ThreadPool.QueueUserWorkItem(_ => DoWork(collection));
            }

            Console.WriteLine("Press Enter to shutdown");
            Console.ReadLine();

            _cancellationTokenSource.Cancel();

            Console.WriteLine("Press Enter to exit");
            Console.ReadLine();
        }
        public void MongoClientAccessorConstror(MongoClient mongoClient, string databaseName)
        {
            var clientAccessor = new MongoClientAccessor(mongoClient, databaseName);

            clientAccessor.MongoClient.Should().Be(mongoClient);
            clientAccessor.DatabaseName.Should().Be(databaseName);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MongoClientAccessor"/> class.
        /// </summary>
        /// <param name="mongoClient">
        /// The mongo client.
        /// </param>
        /// <param name="databaseName">
        /// The database name.
        /// </param>
        public MongoClientAccessor(MongoClient mongoClient, string databaseName)
        {
            Contract.Requires<ArgumentNullException>(mongoClient != null, "mongoClient != null");
            Contract.Requires<ArgumentNullException>(
                !string.IsNullOrWhiteSpace(databaseName),
                "!string.IsNullOrWhiteSpace(databaseName)");

            this.MongoClient = mongoClient;
            this.DatabaseName = databaseName;
        }
        public void UsesSameMongoServerForIdenticalSettings()
        {
            var client1 = new MongoClient("mongodb://localhost");
            var server1 = client1.GetServer();

            var client2 = new MongoClient("mongodb://localhost");
            var server2 = client2.GetServer();

            Assert.AreSame(server1, server2);
        }
        public void UsesSameMongoServerWhenReadPreferenceTagsAreTheSame()
        {
            var client1 = new MongoClient("mongodb://localhost/?readPreferenceTags=dc:ny");
            var server1 = client1.GetServer();

            var client2 = new MongoClient("mongodb://localhost/?readPreferenceTags=dc:ny");
            var server2 = client2.GetServer();

            Assert.AreSame(server1, server2);
        }
        public async Task ListDatabaseNames()
        {
            var operationExecutor = new MockOperationExecutor();
            var client = new MongoClient(operationExecutor);
            var names = await client.GetDatabaseNamesAsync();

            var call = operationExecutor.GetReadCall<IReadOnlyList<string>>();

            call.Operation.Should().BeOfType<ListDatabaseNamesOperation>();
        }
        public void TestSuccessfulAuthentication()
        {
            var client = new MongoClient(_settings);

            var result = client
                .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                .GetCollection<BsonDocument>(__collectionName)
                .FindSync(new BsonDocument())
                .ToList();

            Assert.IsNotNull(result);
        }
        public void TestSuccessfulAuthentication()
        {
            RequireEnvironment.Check().EnvironmentVariable("EXPLICIT");
            var client = new MongoClient(_settings);

            var result = client
                .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                .GetCollection<BsonDocument>(__collectionName)
                .FindSync(new BsonDocument())
                .ToList();

            Assert.NotNull(result);
        }
Example #11
0
        public void TestNoCredentials()
        {
            _settings.Credentials = Enumerable.Empty<MongoCredential>();
            var client = new MongoClient(_settings);

            Assert.Throws<MongoCommandException>(() =>
            {
                client
                    .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                    .GetCollection<BsonDocument>(__collectionName)
                    .Count(new BsonDocument());
            });
        }
        private static MongoClientAccessor InternalMongoClientAccessorFactory(
            string connectionString, 
            string databaseName)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(connectionString));
            Contract.Requires(!string.IsNullOrWhiteSpace(databaseName));
            Contract.Ensures(Contract.Result<MongoClientAccessor>() != null);

            var client = new MongoClient(connectionString);
            var clientAccessor = new MongoClientAccessor(client, databaseName);

            return clientAccessor;
        }
Example #13
0
        public void UsesSameMongoServerForIdenticalSettings()
        {
            var client1 = new MongoClient("mongodb://localhost");
#pragma warning disable 618
            var server1 = client1.GetServer();
#pragma warning restore

            var client2 = new MongoClient("mongodb://localhost");
#pragma warning disable 618
            var server2 = client2.GetServer();
#pragma warning restore

            Assert.AreSame(server1, server2);
        }
Example #14
0
        public void UsesSameMongoServerWhenReadPreferenceTagsAreTheSame()
        {
            var client1 = new MongoClient("mongodb://localhost/?readPreference=secondary;readPreferenceTags=dc:ny");
#pragma warning disable 618
            var server1 = client1.GetServer();
#pragma warning restore

            var client2 = new MongoClient("mongodb://localhost/?readPreference=secondary;readPreferenceTags=dc:ny");
#pragma warning disable 618
            var server2 = client2.GetServer();
#pragma warning restore

            Assert.AreSame(server1, server2);
        }
Example #15
0
		private MongoCollection<BsonDocument> AquireMessageCollection()
		{
			string connectionString;
			MongoClient client;
			MongoServer server;
			MongoDatabase database;
			MongoCollection<BsonDocument> collection;

			connectionString = AppConfigFascade.Instance.GetConnectionString("_2ndAsset.MessagingEngine.Core.StorageModel::ConnectionString#MongoDbMessageStore");
			client = new MongoClient(connectionString);
			server = client.GetServer();
			database = server.GetDatabase("2ndAsset");
			collection = database.GetCollection("message_box");

			return collection;
		}
        public void TestNoCredentials()
        {
            _settings.Credentials = Enumerable.Empty<MongoCredential>();
            var client = new MongoClient(_settings);

            Assert.Throws<MongoQueryException>(() =>
            {
                client
                    .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                    .GetCollection<BsonDocument>(__collectionName)
                    .Find(new BsonDocument())
                    .ToListAsync()
                    .GetAwaiter()
                    .GetResult();
            });
        }
        // static constructor
        static DriverTestConfiguration()
        {
            var connectionString = CoreTestConfiguration.ConnectionString.ToString();

            var mongoUrl = new MongoUrl(connectionString);
            var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
            if (!clientSettings.WriteConcern.IsAcknowledged)
            {
                clientSettings.WriteConcern = WriteConcern.Acknowledged; // ensure WriteConcern is enabled regardless of what the URL says
            }

            clientSettings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(500);

            __client = new MongoClient(clientSettings);
            __databaseNamespace = mongoUrl.DatabaseName == null ? CoreTestConfiguration.DatabaseNamespace : new DatabaseNamespace(mongoUrl.DatabaseName);
            __collectionNamespace = new CollectionNamespace(__databaseNamespace, "testcollection");
        }
        public void Customize(IFixture fixture)
        {
            var client = new MongoClient(MongoPersistenceConstants.DefaultConnectionString);
            var clientAccessor = new MongoClientAccessor(client, "UnitTest");
            var databaseFactory = new MongoDatabaseFactory(clientAccessor);

            fixture.Register(() => client);
            fixture.Register(() => clientAccessor);
            fixture.Register(() => databaseFactory);

            fixture.Customize<TimeoutData>(
                c => c.With(t => t.OwningTimeoutManager, "UnitTests").With(t => t.Time, DateTime.UtcNow));

            fixture.Customize<MongoTimeoutPersister>(c => c.With(t => t.EndpointName, "UnitTests"));

            fixture.Customize(new SupportMutableValueTypesCustomization());

            TimeoutClassMaps.ConfigureClassMaps();
        }
        public void TestBadPassword()
        {
            var currentCredentialUsername = _settings.Credentials.Single().Username;
            _settings.Credentials = new[]
            {
                MongoCredential.CreateGssapiCredential(currentCredentialUsername, "wrongPassword")
            };

            var client = new MongoClient(_settings);

            Assert.Throws<TimeoutException>(() =>
            {
                client
                    .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName)
                    .GetCollection<BsonDocument>(__collectionName)
                    .FindSync(new BsonDocument())
                    .ToList();
            });
        }
Example #20
0
        public void TestFixtureSetUp()
        {
            __capturedEvents = new EventCapturer()
                .Capture<CommandStartedEvent>()
                .Capture<CommandSucceededEvent>()
                .Capture<CommandFailedEvent>();

            var settings = new MongoClientSettings
            {
                ClusterConfigurator = cb =>
                {
                    cb.Subscribe(__capturedEvents);

                    // never heartbeat...
                    cb.ConfigureServer(ss => ss.With(heartbeatInterval: Timeout.InfiniteTimeSpan));
                }
            };

            __client = new MongoClient(settings);
        }
Example #21
0
        public static async Task TestAsync()
        {
            var client = new MongoClient();
            var db = client.GetDatabase("test");
            var col = db.GetCollection<Person>("people");
            await col.DeleteManyAsync(x => true);

            //warm up
            for (int i = 0; i < 1000; i++)
            {
                await Builder(col);
                await ExpressionMethod(col);
                await Linq(col);
            }

            // measure
            await Measure("Builder", col, Builder);
            await Measure("Expression Method", col, ExpressionMethod);
            await Measure("Linq", col, Linq);
            Console.ReadKey();
        }
 public void TestFixtureSetUp()
 {
     _client = new MongoClient();
     _server = _client.GetServer();
 }
Example #23
0
        public MainWindow()
        {
            InitializeComponent();

            dtGrid_dataOutput.CellEditEnding += dtGrid_dataOutput_CellEditEnding;
            //if (File.Exists("BD.json"))
            //{
            //    JsonSerializerSettings settings = new JsonSerializerSettings
            //    {
            //        TypeNameHandling = TypeNameHandling.Auto
            //    };
            //    LoadedOborud = JsonConvert.DeserializeObject<List<Oborudovanie>>(File.ReadAllText("BD.json"), settings);
            //}
            string connectionString = "mongodb://localhost";
            var    client           = new MongoClient(connectionString);
            var    database         = client.GetDatabase("BN");
            var    collection       = database.GetCollection <Oborudovanie>("BNCol");
            var    filter           = new BsonDocument();

            LoadedOborud = collection.Find(filter).ToList();
            UpdateOborList();

            oborudovanies.AddRange(new List <Oborudovanie>()
            {
                new KPT(),
                new ElectroEngine(),
                new Kotel(),
                new Nasos(),
                new HeatExchanger(),
                new PowerTransformator(),
                new SNK_ControlStation()
            });

            oborudovanies_editor.AddRange(new List <Oborudovanie>()
            {
                new KPT(),
                new ElectroEngine(),
                new Kotel(),
                new Nasos(),
                new HeatExchanger(),
                new PowerTransformator(),
                new SNK_ControlStation(),
                new Oborudovanie()
            });

            Dictionary <int, string> namesList  = new Dictionary <int, string>();
            Dictionary <int, string> namesList2 = new Dictionary <int, string>();

            for (int i = 0; i < oborudovanies.Count; i++)
            {
                namesList.Add((i + 1), oborudovanies[i].Name_OsnovnSredstva.Value);
            }

            for (int i = 0; i < oborudovanies_editor.Count; i++)
            {
                namesList2.Add((i + 1), oborudovanies_editor[i].Name_OsnovnSredstva.Value);
            }
            //var listOfFields1 = kpt2.GetType().GetProperties().ToList();
            //IList<IAttribute> attList = new List<IAttribute>();
            //foreach (var a in listOfFields1)
            //{
            //    var propvalue = a.GetValue(kpt2, null) as IAttribute;
            //    attList.Add(propvalue);
            //}

            ListGrid0.ItemsSource  = namesList;
            ListGrid01.ItemsSource = namesList2;
        }
Example #24
0
        public BDatabaseServiceMongoDB(
            string _MongoClientConfigJson,
            string _MongoPassword,
            string _MongoDatabase,
            Action <string> _ErrorMessageAction = null)
        {
            try
            {
                var _ClientConfigString = _MongoClientConfigJson;
                // Parse the Client Config Json if it's a base64 encoded (for running on local environment with launchSettings.json)
                Span <byte> buffer = new Span <byte>(new byte[_ClientConfigString.Length]);
                if (Convert.TryFromBase64String(_ClientConfigString, buffer, out int bytesParsed))
                {
                    if (bytesParsed > 0)
                    {
                        _ClientConfigString = Encoding.UTF8.GetString(buffer);
                    }
                }

                var _ClientConfigJObject = JObject.Parse(_ClientConfigString);

                var _HostTokens = _ClientConfigJObject.SelectTokens("$...hostname");
                var _Hosts      = new List <string>();
                foreach (var item in _HostTokens)
                {
                    _Hosts.Add(item.ToObject <string>());
                }

                var _PortTokens = _ClientConfigJObject.SelectTokens("$....port");
                var _Ports      = new List <int>();
                foreach (var item in _PortTokens)
                {
                    _Ports.Add(item.ToObject <int>());
                }

                var _ReplicaSetName = _ClientConfigJObject.SelectToken("replicaSets[0]._id").ToObject <string>();
                var _DatabaseName   = _ClientConfigJObject.SelectToken("auth.usersWanted[0].db").ToObject <string>();
                var _UserName       = _ClientConfigJObject.SelectToken("auth.usersWanted[0].user").ToObject <string>();
                var _AuthMechnasim  = _ClientConfigJObject.SelectToken("auth.autoAuthMechanism").ToObject <string>();
                int _MongoDBPort    = 27017;

                var _ServerList = new List <MongoServerAddress>();
                for (int i = 0; i < _Hosts.Count; i++)
                {
                    if (i < _Ports.Count)
                    {
                        _MongoDBPort = _Ports[i];
                    }

                    _ServerList.Add(new MongoServerAddress(_Hosts[i], _MongoDBPort));
                }

                MongoInternalIdentity _InternalIdentity = new MongoInternalIdentity(_DatabaseName, _UserName);
                PasswordEvidence      _PasswordEvidence = new PasswordEvidence(_MongoPassword);
                MongoCredential       _MongoCredential  = new MongoCredential(_AuthMechnasim, _InternalIdentity, _PasswordEvidence);
                //MongoCredential _MongoCredential = MongoCredential.CreateCredential(_DatabaseName, _UserName, _MongoPassword);

                var _ClientSettings = new MongoClientSettings();
                _ClientSettings.Servers        = _ServerList.ToArray();
                _ClientSettings.ConnectionMode = ConnectionMode.ReplicaSet;
                _ClientSettings.ReplicaSetName = _ReplicaSetName;
                _ClientSettings.Credential     = _MongoCredential;
                var Client = new MongoClient(_ClientSettings);
                MongoDB = Client.GetDatabase(_MongoDatabase);
                bInitializationSucceed = MongoDB != null;
            }
            catch (Exception e)
            {
                _ErrorMessageAction?.Invoke($"BDatabaseServiceMongoDB->Constructor: {e.Message} \n Trace: {e.StackTrace}");
                bInitializationSucceed = false;
            }
        }
Example #25
0
 public TransactionRepository()
 {
     mongoClient = new MongoClient(ConnectionString);
     database    = mongoClient.GetDatabase(Database);
 }
 /// <summary>
 /// MongoDb插入数据
 /// </summary>
 /// <param name="collenction">集合名称</param>
 /// <param name="bd">所插入的数据</param>
 /// <returns>插入数据返回的结果</returns>
 public static WriteConcernResult InsertMongoCollection(string collenction, BsonDocument bd)
 {
     var connectionString = "mongodb://localhost";
     var client = new MongoClient(connectionString);
     var server = client.GetServer();
     var database = server.GetDatabase("test"); // WriteConcern defaulted to Acknowledged
     MongoCollection col = database.GetCollection(collenction);
     //insert
     WriteConcernResult wcr = null;
     try
     {
         wcr = col.Insert(bd);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
     return wcr;
 }
 /// <summary>
 /// 查询MongoDB
 /// </summary>
 /// <param name="collenction">集合名称</param>
 /// <param name="qd">QueryCocument条件</param>
 /// <returns>返回结果</returns>
 public static MongoCursor QueryMongoCollection(string collenction, QueryDocument qd)
 {
     MongoCursor<BsonDocument> result = null;
     var connectionString = "mongodb://localhost";
     var client = new MongoClient(connectionString);
     var server = client.GetServer();
     var database = server.GetDatabase("test"); // WriteConcern defaulted to Acknowledged
     MongoCollection col = database.GetCollection(collenction);
     try
     {
         //查找全部
         //result = col.FindAllAs<BsonDocument>();
         //条件查找
         result = col.FindOneAs<MongoCursor<BsonDocument>>(qd);
     }
     catch (Exception ex)
     {
         CommonFunction.WriteErrorLog(ex.ToString());
     }
     return result;
 }
Example #28
0
 public void Init()
 {
     client   = new MongoClient();
     database = client.GetDatabase("TestMosaicDatabase");
 }
        internal static void ShowUncontactableMongoWarning(MongoClient mongoClient, Exception exception)
        {
            Contract.Requires(mongoClient != null);
            Contract.Requires(exception != null);

            var serverSettings = string.Join(", ", GetMongoServers(mongoClient));

            var sb = new StringBuilder();
            sb.AppendFormat("Mongo could not be contacted using: {0}.", serverSettings);
            sb.AppendLine();
            sb.AppendFormat("If you are using a Replica Set, please ensure that all the Mongo instance(s) {0} are available.", serverSettings);
            sb.AppendLine();
            sb.AppendLine(
                @"To configure NServiceBus to use a different connection string add a connection string named ""NServiceBus/Persistence"" in your config file.");
            sb.AppendLine("Reason: " + exception);

            Logger.Warn(sb.ToString());
        }
 // static constructor
 static DriverTestConfiguration()
 {
     __client = new MongoClient(CoreTestConfiguration.Cluster);
     __databaseNamespace = CoreTestConfiguration.DatabaseNamespace;
     __collectionNamespace = new CollectionNamespace(__databaseNamespace, "testcollection");
 }
Example #31
0
 public JobMongoService()
 {
     this.client = new MongoClient(ConnectionString);
 }
Example #32
0
 public DataAccess()
 {
     _client = new MongoClient("mongodb://<sageuser>:<sageuser123>@ds253922.mlab.com:53922/sage50");
     _server = MongoClientExtensions.GetServer(this._client);
     _db     = _server.GetDatabase("sage50");
 }
 public MongoDataContext(string connectionString, string mongoDbName)
 {
     _mongoDbName = mongoDbName;
     _client      = new MongoClient(connectionString);
 }
        public HomeController()
        {
            var client = new MongoClient(Properties.Resources.ResourceManager.GetString("mongoDBConnectionString"));

            Expenses = client.GetDatabase("expenses").GetCollection <ExpenseModel>("expenses");
        }
Example #35
0
        private void BtnDodajIgraca_Click(object sender, EventArgs e)
        {
            // ---- Provera ispravnosti licnih podataka ----
            if (String.IsNullOrWhiteSpace(TbPunoIme.Text))
            {
                MessageBox.Show("Unesite puno ime igraca!");
                return;
            }
            else if (String.IsNullOrWhiteSpace(TbMestoRodjenja.Text))
            {
                MessageBox.Show("Unesite mesto rodjenja igraca!");
                return;
            }
            else if (String.IsNullOrWhiteSpace(TbTrenutniKlub.Text))
            {
                MessageBox.Show("Unesite trenutni (ili poslednji) klub igraca!");
                return;
            }
            else if (String.IsNullOrWhiteSpace(TbVisina.Text) || TbVisina.Text.Length != 4)
            {
                MessageBox.Show("Unesite ispravno vrednost visine igraca! Na primer '1.92' ");
                return; /*AKO JE OBAVEZNO POLJE*/
            }
            else if (LvPozicijeIgraca.Items.Count == 0)
            {
                MessageBox.Show("Ubacite poziciju/je na kojoj igrac igra!");
                return;
            }

            // ---- Izvlacimo pozicije igraca ----
            string pozicije = "";

            foreach (ListViewItem lvi in LvPozicijeIgraca.Items)
            {
                pozicije += lvi.Text + ", ";
            }
            pozicije = pozicije.TrimEnd(',');

            // ---- Ubacujemo podatke u objekat ----
            Igrac noviIgrac = new Igrac();

            // ---- Licni podaci ----
            noviIgrac.PunoIme       = StringCleaner.checkString(TbPunoIme.Text);
            noviIgrac.MestoRodjenja = StringCleaner.checkString(TbMestoRodjenja.Text);
            noviIgrac.DatumRodjenja = DpDatumRodjenja.Text; /*Treba se ispravi*/
            noviIgrac.Visina        = StringCleaner.checkString(TbVisina.Text);
            noviIgrac.TrenutniKlub  = StringCleaner.checkString(TbTrenutniKlub.Text);
            noviIgrac.Pozicija      = StringCleaner.checkString(pozicije);
            // ---- Ostali podaci ----
            noviIgrac.SportskaBiografija      = StringCleaner.checkString(RtbSportksaBiografija.Text);
            noviIgrac.ReprezentativnaKarijera = StringCleaner.checkString(RtbReprezentativnaKarijera.Text);
            noviIgrac.Statistika = StringCleaner.checkString(RtbStatistika.Text);
            noviIgrac.Trofeji    = StringCleaner.checkString(RtbTrofeji.Text);

            // ------------------ID------------------------


            //noviIgrac.Id = new BsonObjectId("");

            //----------------------------------------------

            // ---- Rad sa bazom ----
            try
            {
                var _client   = new MongoClient();
                var _database = _client.GetDatabase("test");

                var collection = _database.GetCollection <BsonDocument>("igraci");
                var filter     = new BsonDocument();
                var document   = noviIgrac.ToBsonDocument();
                collection.InsertOne(document);
                MessageBox.Show("Uspesno dodat novi igrac!");

                // ---- Zatvaranje forme ----
                this.Dispose();
            }
            catch (Exception ec)
            {
                MessageBox.Show(ec.ToString());
            }
        }
        private static IEnumerable<MongoServerAddress> GetMongoServers(MongoClient mongoClient)
        {
            Contract.Requires<ArgumentNullException>(mongoClient != null);
            Contract.Ensures(Contract.Result<IEnumerable<MongoServerAddress>>() != null);

            if (mongoClient.Settings.Servers != null && mongoClient.Settings.Servers.Any())
            {
                return mongoClient.Settings.Servers;
            }

            return new[] { mongoClient.Settings.Server };
        }
Example #37
0
        public void OneTimeSetUp()
        {
            __capturedEvents = new EventCapturer()
                .Capture<CommandStartedEvent>(e => __commandsToCapture.Contains(e.CommandName))
                .Capture<CommandSucceededEvent>(e => __commandsToCapture.Contains(e.CommandName))
                .Capture<CommandFailedEvent>(e => __commandsToCapture.Contains(e.CommandName));

            var settings = new MongoClientSettings
            {
                ClusterConfigurator = cb =>
                {
                    cb = CoreTestConfiguration.ConfigureCluster(cb);
                    cb.Subscribe(__capturedEvents);

                    // never heartbeat...
                    cb.ConfigureServer(ss => ss.With(heartbeatInterval: Timeout.InfiniteTimeSpan));
                }
            };

            __client = new MongoClient(settings);
        }
        public void TestSocketConfigurator()
        {
            var settings = DriverTestConfiguration.Client.Settings.Clone();
            var socketConfiguratorWasCalled = false;
            Action<Socket> socketConfigurator = s => { socketConfiguratorWasCalled = true; };
            settings.ClusterConfigurator = cb => cb.ConfigureTcp(tcp => tcp.With(socketConfigurator: socketConfigurator));
            var subject = new MongoClient(settings);

            SpinWait.SpinUntil(() => subject.Cluster.Description.State == ClusterState.Connected, TimeSpan.FromSeconds(4));

            Assert.That(socketConfiguratorWasCalled, Is.True);
        }
        private async Task RunAsync(CancellationToken cancellationToken)
        {
            // TODO: Replace the following with your own logic.
            initQueue();        //call the queue initialization method
            while (!cancellationToken.IsCancellationRequested)
            {
                // Async dequeue (read) the message
                inMessage = await inqueue.GetMessageAsync();    //not an optimal way to retrieve a message from a queue, but works

                payMessage = await payqueue.GetMessageAsync();

                transactionMessage = await transactionqueue.GetMessageAsync();

                if (inMessage != null)
                {
                    //create json object
                    JObject jObject = JObject.Parse(inMessage.AsString);
                    string  bigs    = calculatePrice(jObject);
                    await inqueue.DeleteMessageAsync(inMessage);

                    // Create a message and add it to the queue.
                    outMessage = new CloudQueueMessage(bigs);
                    outqueue.AddMessage(outMessage);
                }

                //Mongo insertion with queues

                if (payMessage != null)
                {
                    JObject      payInfo = JObject.Parse(payMessage.AsString);
                    BsonDocument doc     = BsonDocument.Parse(payInfo.ToString());

                    //MONGO insertion
                    MongoClient dbClient = new MongoClient(connection);
                    var         database = dbClient.GetDatabase("PaymentService");
                    var         getPaymentInformation = database.GetCollection <BsonDocument>("PaymentInformation");
                    //insert
                    await getPaymentInformation.InsertOneAsync(doc);

                    payqueue.DeleteMessage(payMessage);
                }

                if (transactionMessage != null)
                {
                    JObject      transInfo = JObject.Parse(transactionMessage.AsString);
                    BsonDocument docu      = BsonDocument.Parse(transInfo.ToString());

                    //MONGO insertion
                    MongoClient dbClient = new MongoClient(connection);
                    var         database = dbClient.GetDatabase("PaymentService");
                    var         getPaymentInformation = database.GetCollection <BsonDocument>("Transactions");
                    //insert
                    await getPaymentInformation.InsertOneAsync(docu);

                    transactionqueue.DeleteMessage(transactionMessage);
                }


                Trace.TraceInformation("Working");
                await Task.Delay(1000);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="collenction"></param>
        /// <param name="bd"></param>
        public static void UpdateMongoCollection(string collenction, BsonDocument bd)
        {
            var connectionString = "mongodb://localhost";
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            var database = server.GetDatabase("test"); // WriteConcern defaulted to Acknowledged
            MongoCollection col = database.GetCollection(collenction);
            //update
            //col.Update(collenction, (x => x.ID == collenction.ID));

        }
//	    public virtual string GetInsertCommitScript()
//	    {
//	        return @"function (commit) {
//    var result;
//    while (1) {
//        var cursor = db.Commits.find( {}, { _id: 1 } ).sort( { _id: -1 } ).limit(1);

//        var seq = cursor.hasNext() ? cursor.next()._id + 1 : 1;

//        commit._id = NumberLong(seq);

//        db.Commits.insert(commit);
        
//        var err = db.getLastErrorObj();

//        if( err && err.code ) {
//            if( err.code == 11000 /* dup key */  && 
//                err.err.indexOf('$_id_') != -1  /* dup checkpoint id */){
//                continue;
//            }
//            else{
//                result = err ;
//                break;
//            }
//        }

//        result = {id: commit._id};
//        break;
//    }
//    return result;
//}";
//	    }

	    /// <summary>
		/// Connects to NEvenstore Mongo database
		/// </summary>
		/// <param name="connectionString">Connection string</param>
		/// <returns>nevenstore mongodatabase store</returns>
		public virtual IMongoDatabase ConnectToDatabase(string connectionString)
		{
			var builder = new MongoUrlBuilder(connectionString);
            var client = new MongoClient(connectionString);

            var database = client.GetDatabase(builder.DatabaseName);
			return database;
		}
Example #42
0
        /// <summary>
        /// Creates and returns a MongoDatabase from the specified url.
        /// </summary>
        /// <param name="url">The url to use to get the database from.</param>
        /// <returns>Returns a MongoDatabase from the specified url.</returns>
        private static IMongoDatabase GetDatabaseFromUrl(MongoUrl url)
        {
            var client = new MongoClient(url);

            return(client.GetDatabase(url.DatabaseName)); // WriteConcern defaulted to Acknowledged
        }
 public SearchRepository(IPortfolioManagerConnection portfolioManagerConnection)
 {
     _portfolioManagerConnection = portfolioManagerConnection;
     _mongoClient = new MongoClient(_portfolioManagerConnection.ConnectionString);
 }