public void JustReading(int marker) { OutsiderSees(); using (var session = client.StartSession(new ClientSessionOptions { CausalConsistency = true })) { session.StartTransaction(new TransactionOptions( readConcern: ReadConcern.Snapshot, writeConcern: WriteConcern.WMajority)); try { PersonCollection.UpdateOne( session, TargetPersonFilter, Builders <Person> .Update.Set(p => p.ToolCount, marker)); Console.WriteLine($"Session set ToolCound to {marker}"); OutsiderSees(); } catch (Exception exception) { Console.WriteLine($"Caught exception during transaction, aborting: {exception.Message}."); session.AbortTransaction(); throw; } session.CommitWithRetry(); OutsiderSees(); } }
/// <summary> /// Commits data transaction to data source if applicable /// </summary> public void Commit() { if (!AutoCommit) { _transSession.CommitTransaction(); _transSession = _client.StartSession(); } }
public void CheckOut(int toolId, int personId) { System.Console.WriteLine($"Check Out tool [{toolId}] to person [{personId}]"); using (var session = client.StartSession(new ClientSessionOptions { CausalConsistency = true })) { session.StartTransaction(new TransactionOptions( readConcern: ReadConcern.Snapshot, writeConcern: WriteConcern.WMajority)); try { var holdTool = ToolCollection.UpdateOne(session, Builders <Tool> .Filter.Eq(t => t.Id, toolId) & Builders <Tool> .Filter.Eq(t => t.HeldBy, null), Builders <Tool> .Update.Set(t => t.HeldBy, personId)); if (holdTool.ModifiedCount != 1) { throw new InvalidOperationException($"Failed updating hold on tool {toolId}. It might be held or non-existent"); } LendLedgerCollection.InsertOne(session, new LendingLedger { ToolId = toolId, PersonId = personId, CheckOutTime = DateTime.UtcNow }); var toolCount = PersonCollection.UpdateOne( session, Builders <Person> .Filter.Eq(p => p.Id, personId), Builders <Person> .Update.Inc(p => p.ToolCount, 1) ); if (toolCount.ModifiedCount != 1) { throw new InvalidOperationException($"Failed increasing tool count on person {personId}"); } } catch (Exception exception) { Console.WriteLine($"Caught exception during transaction, aborting: {exception.Message}."); session.AbortTransaction(); throw; } session.CommitWithRetry(); } }
public UnitOfWorkTest() { transactionOptions = new TransactionOptions(readPreference: ReadPreference.Primary, readConcern: ReadConcern.Local, writeConcern: WriteConcern.WMajority); cancellationToken = CancellationToken.None; clientSessionHandle = Substitute.For <IClientSessionHandle>(); clientSessionHandle .WithTransactionAsync( Arg.Any <Func <IClientSessionHandle, CancellationToken, Task <bool> > >(), Arg.Any <TransactionOptions>(), Arg.Any <CancellationToken>()) .Returns(true); clientSessionHandle .WithTransaction( Arg.Any <Func <IClientSessionHandle, CancellationToken, bool> >(), Arg.Any <TransactionOptions>(), Arg.Any <CancellationToken>()) .Returns(true); mongoClient = Substitute.For <IMongoClient>(); mongoClient.StartSessionAsync().Returns(clientSessionHandle); mongoClient.StartSession().Returns(clientSessionHandle); unitOfWork = new UnitOfWorkMongo.UnitOfWork(mongoClient, transactionOptions); }
public MongoDbBaseRepository(IMongoClient client) { _clientSessionHandle = client.StartSession(); var database = client.GetDatabase(DATABASE); _Collection = database.GetCollection <T>(typeof(T).Name.ToLower()); }
public MongoDbWriteModelUnitOfWorkTests() { fixture = new Fixture(); //Setup mongo configuration configuration = fixture.Create <MongoDbConfiguration>(); //Setup client factory client = Substitute.For <IMongoClient>(); sessionHandle = Substitute.For <IClientSessionHandle>(); database = Substitute.For <IMongoDatabase>(); clientFactory = Substitute.For <IMongoClientFactory>(); client.StartSession().Returns(sessionHandle); client.GetDatabase(Arg.Any <string>()).Returns(database); clientFactory.CreateClient(Arg.Any <MongoDbConfiguration>()).Returns(client); //Setup user factory cryptService = Substitute.For <ICryptService>(); cryptService.Crypt(Arg.Any <string>()).Returns(args => args[0]); userFactory = new WriteModelUserFactory(cryptService); //Create unit of work unitOfWork = new MongoDbWriteModelUnitOfWork(configuration, clientFactory, userFactory); }
public MongoDBStorageTransaction(IMongoClient client, MongoDBOptions options) { _options = options; _database = client.GetDatabase(options.DatabaseName); _session = client.StartSession(); _session.StartTransaction(); }
/// <summary> /// Instantiates and begins a transaction. /// </summary> /// <param name="database">The name of the database to use for this transaction</param> /// <param name="options">Client session options for this transaction</param> public Transaction(string database = null, ClientSessionOptions options = null) { db = database; client = DB.GetClient(db); Session = client.StartSession(options); Session.StartTransaction(); }
public MongoDbContext(IMongoDatabase database) { _database = database; _client = database.Client; _session = _client.StartSession(); MigrationsAssembly = GetType().Assembly; }
/// <summary> /// Start the CAP transaction /// </summary> /// <param name="client">The <see cref="IMongoClient" />.</param> /// <param name="publisher">The <see cref="ICapPublisher" />.</param> /// <param name="autoCommit">Whether the transaction is automatically committed when the message is published</param> /// <returns>The <see cref="IClientSessionHandle" /> of MongoDB transaction session object.</returns> public static IClientSessionHandle StartTransaction(this IMongoClient client, ICapPublisher publisher, bool autoCommit = false) { var clientSessionHandle = client.StartSession(); var capTrans = publisher.Transaction.Begin(clientSessionHandle, autoCommit); return(new CapMongoDbClientSessionHandle(capTrans)); }
private IClientSessionHandle StartSession(IMongoClient client, BsonDocument test, string sessionKey) { Logger.Debug("Starting session"); var options = ParseSessionOptions(test, sessionKey); return(client.StartSession(options)); }
public MongoDBEventStore(IServiceProvider serviceProvider, MongoDBOptions options) { client = serviceProvider.GetRequiredService <IMongoClient>(); database = client.GetDatabase(options.DatabaseName); session = client.StartSession(); session.StartTransaction(); collectionName = options.EventCollectionName; collection = database.GetCollection <EventStream>(collectionName); }
/// <summary> /// Start the CAP transaction /// </summary> /// <param name="client">The <see cref="IMongoClient" />.</param> /// <param name="publisher">The <see cref="ICapPublisher" />.</param> /// <param name="autoCommit">Whether the transaction is automatically committed when the message is published</param> /// <returns>The <see cref="IClientSessionHandle" /> of MongoDB transaction session object.</returns> public static IClientSessionHandle StartTransaction(this IMongoClient client, ICapPublisher publisher, bool autoCommit = false) { var clientSessionHandle = client.StartSession(); publisher.Transaction.Value = ActivatorUtilities.CreateInstance <MongoDBCapTransaction>(publisher.ServiceProvider); var capTrans = publisher.Transaction.Value.Begin(clientSessionHandle, autoCommit); return(new CapMongoDbClientSessionHandle(capTrans)); }
/// <summary> /// Start the CAP transaction /// </summary> /// <param name="client">The <see cref="IMongoClient" />.</param> /// <param name="publisher">The <see cref="ICapPublisher" />.</param> /// <param name="autoCommit">Whether the transaction is automatically committed when the message is published</param> /// <returns>The <see cref="IClientSessionHandle" /> of MongoDB transaction session object.</returns> public static IClientSessionHandle StartTransaction(this IMongoClient client, ICapPublisher publisher, bool autoCommit = false) { var clientSessionHandle = client.StartSession(); publisher.Transaction.Value = publisher.ServiceProvider.GetService <CapTransactionBase>(); var capTrans = publisher.Transaction.Value.Begin(clientSessionHandle, autoCommit); return(new CapMongoDbClientSessionHandle(capTrans)); }
public bool Start() { _session = _client.StartSession(); if (_session == null) { return(false); } _session.StartTransaction(); return(true); }
/// <summary> /// Connects data provider to its source addressed by supplied connection string /// </summary> /// <param name="str">Connection string</param> public virtual void Connect(string str) { if (_client == null) { _connectionString = str; _client = new MongoClient(_connectionString); if (!AutoCommit) { _transSession = _client.StartSession(); } } }
/// <summary> /// Conecta com o banco de dados. /// </summary> public ServiceMongo() { try { nomeDaColecao = PegarNomeColecao(); sessao = server.StartSession(); db = sessao.Client.GetDatabase(MongoUrl.Create(StrConexao).DatabaseName); } catch (Exception ex) { throw ex; } }
public void BeginTransaction() { if (transaction != null) { return; } transaction = conn.StartSession(); transaction.StartTransaction(new TransactionOptions( readConcern: ReadConcern.Snapshot, writeConcern: WriteConcern.WMajority)); transactionStack.Push(transaction); }
//public MongoContext(IMongoClient client) //{ // string dbName = ConfigGetter.GetSectionFromJson("MongoSettings:DbName"); // _client = client; // _database = _client.GetDatabase(dbName); //} public void StartTransaction() { if (_session != null && _session.IsInTransaction) { throw new Exception("Session has been started and using in a transaction."); } if (_session == null) { _session = _client.StartSession(); } _session.StartTransaction(); }
private IEnumerable <IEvent> SaveEvents(IMongoClient mongoClient, IAggregate aggregate) { if (!aggregate.UncommitedEvents().Any()) { return(new List <IEvent>()); } var evtsToSave = aggregate.UncommitedEvents().ToList(); var expected = CalculateExpectedVersion(aggregate, evtsToSave); var database = mongoClient.GetDatabase(_mongoEventStoreConfiguration.DatabaseName); var eventsCollection = database.GetCollection <MongoEntity>(_mongoEventStoreConfiguration.EventsCollectionName); using (var session = mongoClient.StartSession()) { try { var current = eventsCollection .AsQueryable() .Count(x => x.Id == aggregate.Id) - 1; if (expected != current) { throw new AggregateConflictException(aggregate.Id, expected, current); } var mongoEventsToSave = evtsToSave.Select(e => new MongoEntity { Id = e.AggregateId, Version = e.Version, Payload = _serializer.Serialize(e) }); eventsCollection .InsertMany(session, mongoEventsToSave); session.CommitTransaction(); } catch (Exception) { session.AbortTransaction(); throw; } } return(aggregate.UncommitedEvents()); }
public void UpdateEmployeeInfoWithTransactionRetry(IMongoClient client) { // start a session using (var session = client.StartSession()) { try { RunTransactionWithRetry(UpdateEmployeeInfo, client, session); } catch (Exception exception) { // do something with error Console.WriteLine($"Non transient exception caught during transaction: ${exception.Message}."); } } }
public MongoDBProvider(string database, string replicaSetName, string host, int port, string clientApplicationName = null) { var settings = new MongoClientSettings { ReplicaSetName = replicaSetName, Server = new MongoServerAddress(host, port), ApplicationName = clientApplicationName, UseTls = false, Compressors = new List <CompressorConfiguration>() { new CompressorConfiguration(CompressorType.Snappy) } }; client = new MongoClient(settings); db = client.GetDatabase(database); sessionHandle = client.StartSession(); }
public static void EnsureReplicationSetReady(this IMongoClient mongoClient) { var delay = InitialDelay; var database = mongoClient.GetDatabase("__dummy-db"); try { while (true) { try { _ = database.GetCollection <DummyEntry>("__dummy"); database.DropCollection("__dummy"); var session = mongoClient.StartSession(); try { session.StartTransaction(); session.AbortTransaction(); } finally { session.Dispose(); } break; } catch (NotSupportedException) { } Thread.Sleep(delay); delay = Min(Double(delay), MaxDelay); } } finally { mongoClient.DropDatabase("__dummy-db"); } }
public Task <ITransaction> StartTransactionAsync(CancellationToken cancellationToken = default) { var transactionOptions = new TransactionOptions(ReadConcern.Majority, ReadPreference.Primary, WriteConcern.WMajority); ITransaction transaction; try { //TODO: the async overload might freeze if transactions are not supported var session = _client.StartSession(); session.StartTransaction(transactionOptions); transaction = new MongoTransaction(session); } catch (NotSupportedException ex) { _logger.LogWarning($"unable to start MongoDB transaction : {ex.Message}"); transaction = new NullTransaction(); } return(Task.FromResult(transaction)); }
private IClientSessionHandle CreateSession(IMongoClient client) { var stopwatch = Logger.StartStopwatch(); Logger.LogInformation($"Start CreateSession"); var session = client.StartSession(); if (_dbContextOptions.Timeout.HasValue) { session.AdvanceOperationTime(new BsonTimestamp(_dbContextOptions.Timeout.Value)); } session.StartTransaction(); stopwatch?.Stop(); Logger.LogInformation("End CreateSession, elapsed time: {elapsedTime}", Logger.GetElapsedTime(stopwatch)); stopwatch = null; return(session); }
public MongoDBProvider(string database, string replicaSetName, string host, int port, string username, string password, string clientApplicationName = null) { string mongoDbAuthMechanism = "SCRAM-SHA-1"; MongoInternalIdentity internalIdentity = new MongoInternalIdentity(database, username); PasswordEvidence passwordEvidence = new PasswordEvidence(password); MongoCredential mongoCredential = new MongoCredential(mongoDbAuthMechanism, internalIdentity, passwordEvidence); var settings = new MongoClientSettings { ReplicaSetName = replicaSetName, Server = new MongoServerAddress(host, port), ApplicationName = clientApplicationName, Credential = mongoCredential, UseTls = false, Compressors = new List <CompressorConfiguration>() { new CompressorConfiguration(CompressorType.Snappy) } }; client = new MongoClient(settings); db = client.GetDatabase(database); sessionHandle = client.StartSession(); }
/// <summary> /// Instantiates and begins a transaction. /// </summary> /// <param name="database">The name of the database to use for this transaction. default db is used if not specified</param> /// <param name="options">Client session options for this transaction</param> public Transaction(string database = default, ClientSessionOptions options = null) { client = DB.Database(database).Client; Session = client.StartSession(options); Session.StartTransaction(); }
public void OpenConnection(string connString, string dbName = "") { this._client = new MongoClient(connString); this._database = _client.GetDatabase(dbName); this._session = _client.StartSession(); }
public IClientSessionHandle StartSession(ClientSessionOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(wrapped.StartSession(options, cancellationToken)); }
private IClientSessionHandle CreateSession(BsonDocument entity, Dictionary <string, DisposableMongoClient> clients) { IMongoClient client = null; ClientSessionOptions options = null; foreach (var element in entity) { switch (element.Name) { case "id": // handled on higher level break; case "client": var clientId = element.Value.AsString; client = clients[clientId]; break; case "sessionOptions": options = new ClientSessionOptions(); foreach (var option in element.Value.AsBsonDocument) { switch (option.Name) { case "snapshot": options.Snapshot = option.Value.ToBoolean(); break; case "causalConsistency": options.CausalConsistency = option.Value.ToBoolean(); break; case "defaultTransactionOptions": ReadConcern readConcern = null; ReadPreference readPreference = null; WriteConcern writeConcern = null; foreach (var transactionOption in option.Value.AsBsonDocument) { switch (transactionOption.Name) { case "readConcern": readConcern = ReadConcern.FromBsonDocument(transactionOption.Value.AsBsonDocument); break; case "readPreference": readPreference = ReadPreference.FromBsonDocument(transactionOption.Value.AsBsonDocument); break; case "writeConcern": writeConcern = WriteConcern.FromBsonDocument(transactionOption.Value.AsBsonDocument); break; default: throw new FormatException($"Invalid session transaction option: '{transactionOption.Name}'."); } } options.DefaultTransactionOptions = new TransactionOptions(readConcern, readPreference, writeConcern); break; default: throw new FormatException($"Invalid session option argument name: '{option.Name}'."); } } break; default: throw new FormatException($"Invalid session argument name: '{element.Name}'."); } } var session = client.StartSession(options); return(session); }