public void Commit() { if (_transactionCounter == 1) { try { Transaction.Commit(); _mongoSession.CommitTransaction(); } catch { Transaction.Rollback(); _mongoSession.AbortTransaction(); throw; } finally { _connection.Close(); Transaction.Dispose(); _mongoSession.Dispose(); } } _transactionCounter--; }
public Result BookingSeat(int totalSeats, string seatIds, string jsonBooked, IMessage msg) { Result result; using (IDataAdapter da = DataManager.Build(this.DbConfig)) { IClientSessionHandle Session = null; try { string tickets = ""; string seatUnavailable = @" { _id: {'$in': <ids>}, 'bookingStatus._id': {'$ne': 'bs01'} } ".Replace("<ids>", seatIds); Session = da.Open() .CreateTransaction(); Session.StartTransaction(); da.Get(seatUnavailable, out tickets); if (tickets != "[]") { Session.AbortTransaction(); throw new System.InvalidOperationException("Unavailable ticket:" + tickets); } string bookSeats = @" { '_id': {'$in': <ids>} } ".Replace("<ids>", seatIds); long total = 0; da.EditMany(bookSeats, jsonBooked, out total); if (totalSeats != total) { Session.AbortTransaction(); throw new System.InvalidOperationException("Unavailable book all ticktes!"); } Session.CommitTransaction(); result = Result.GetResult(BusinessStatus.Completed, 210, msg, "Booking is successfully."); } catch (Exception err) { if (Session != null) { Session.AbortTransaction(); } result = Result.GetResult(BusinessStatus.Completed, 500, msg, err.Message); } } return(result); }
public void InDoubt(Enlistment enlistment) { try { _sessionHandle.AbortTransaction(); enlistment.Done(); } finally { _unregister(); } }
/// <summary> /// Busca o registro identico ao objeto informado. /// </summary> /// <param name="registro">Informe o objeto.</param> /// <returns>Retorna o primeiro registro encontrado.</returns> public virtual T Buscar(T registro) { try { return(Colecao.Find(sessao, CriarFiltro(registro)).FirstOrDefault()); } catch (Exception) { sessao.AbortTransaction(); throw; } }
private void RemoveUserActivationCode(string userName) { try { DBSession.StartTransaction(); UserCollection.DeleteOne(user => user.UserName.Equals(user.UserName)); DBSession.CommitTransaction(); } catch (System.Exception) { DBSession.AbortTransaction(); throw; } }
/// <summary> /// Insert entity /// </summary> /// <param name="entity">Entity</param> public virtual T Insert(T entity) { StartTransaction(); try { _collection.InsertOne(entity); _session.CommitTransaction(); return(entity); } catch (Exception) { _session.AbortTransaction(); throw; } }
// updates two collections in a transaction public void UpdateEmployeeInfo(IMongoClient client, IClientSessionHandle session) { var employeesCollection = client.GetDatabase("hr").GetCollection <BsonDocument>("employees"); var eventsCollection = client.GetDatabase("reporting").GetCollection <BsonDocument>("events"); session.StartTransaction(new TransactionOptions( readConcern: ReadConcern.Snapshot, writeConcern: WriteConcern.WMajority)); try { employeesCollection.UpdateOne( session, Builders <BsonDocument> .Filter.Eq("employee", 3), Builders <BsonDocument> .Update.Set("status", "Inactive")); eventsCollection.InsertOne( session, new BsonDocument { { "employee", 3 }, { "status", new BsonDocument { { "new", "Inactive" }, { "old", "Active" } } } }); } catch (Exception exception) { Console.WriteLine($"Caught exception during transaction, aborting: {exception.Message}."); session.AbortTransaction(); throw; } CommitWithRetry(session); }
public override void Rollback() { base.Rollback(); _clientSessionHandle.AbortTransaction(); _clientSessionHandle.Dispose(); _clientSessionHandle = null; }
internal void AbortTransaction() { if (IsInRunningState()) { _transactionSession.AbortTransaction(); } }
/// <summary> /// Reverts uncommitted data transactions if applicable /// </summary> public void RollBack() { if (!AutoCommit) { _transSession.AbortTransaction(); _transSession = _client.StartSession(); } }
public void AbortTransaction(CancellationToken cancellationToken = default(CancellationToken)) { if (DotUseTransaction) { return; } session.AbortTransaction(cancellationToken); }
public void Rollback() { if (_session != null) { _session.AbortTransaction(); } _session = null; }
public override void Dispose() { if (_session?.IsInTransaction == true) { _session.AbortTransaction(); } _session?.Dispose(); base.Dispose(); }
public void RollBack() { if (_session == null) { throw new Exception("Session has been gone somehow!"); } _session.AbortTransaction(); }
public void AbortTransaction() { if (_session == null) { throw new InvalidOperationException("Transaction already closed"); } _session.AbortTransaction(); }
// Start Transaction Intro Example 1 public void UpdateEmployeeInfo(IMongoClient client, IClientSessionHandle session) { var employeesCollection = client.GetDatabase("hr").GetCollection <BsonDocument>("employees"); var eventsCollection = client.GetDatabase("reporting").GetCollection <BsonDocument>("events"); session.StartTransaction(new TransactionOptions( readConcern: ReadConcern.Snapshot, writeConcern: WriteConcern.WMajority)); try { employeesCollection.UpdateOne( session, Builders <BsonDocument> .Filter.Eq("employee", 3), Builders <BsonDocument> .Update.Set("status", "Inactive")); eventsCollection.InsertOne( session, new BsonDocument { { "employee", 3 }, { "status", new BsonDocument { { "new", "Inactive" }, { "old", "Active" } } } }); } catch (Exception exception) { Console.WriteLine($"Caught exception during transaction, aborting: {exception.Message}."); session.AbortTransaction(); throw; } while (true) { try { session.CommitTransaction(); // uses write concern set at transaction start Console.WriteLine("Transaction committed."); break; } catch (MongoException exception) { // can retry commit if (exception.HasErrorLabel("UnknownTransactionCommitResult")) { Console.WriteLine("UnknownTransactionCommitResult, retrying commit operation."); continue; } else { Console.WriteLine("Error during commit."); throw; } } } }
public IDataAdapter StopTransaction() { if (_session != null) { if (_session.IsInTransaction) { _session.AbortTransaction(); } } return(this); }
public OperationResult Execute(CancellationToken cancellationToken) { try { _session.AbortTransaction(cancellationToken); return(OperationResult.Empty()); } catch (Exception ex) { return(OperationResult.FromException(ex)); } }
public async Task <Maybe <string> > Handle(CreateTechSpecificationByVehicleIdCommand request, CancellationToken cancellationToken) { var vehicleIdFilter = Builders <Vehicle> .Filter.Eq(v => v.Id, new ObjectId(request.VehicleId)); var techSpecificationFilter = Builders <Vehicle> .Filter.ElemMatch( v => v.VehicleTechSpecifications, request.VehicleTechSpecificationDTO.ToBsonDocument()); var filter = Builders <Vehicle> .Filter.And(vehicleIdFilter, techSpecificationFilter); var vehicles = await sparePartsDbContext.Vehicles.FindAsync(filter); var vehicle = await vehicles.FirstOrDefaultAsync(); if (vehicle == null) { return(Maybe <string> .None); } var vehicleTechSpecifictaion = MapDtoToVehicleTechSpecification(request.VehicleTechSpecificationDTO); var vehicleTechSpecificationUpdateDefinition = Builders <Vehicle> .Update.Push(v => v.VehicleTechSpecifications, vehicleTechSpecifictaion); var askForSparePartsEvent = new AskForSparePartsPricesIntegrationEvent( new VehicleDTO { Id = vehicle.Id.ToString(), ManufacturerName = vehicle.ManufacturerName, Model = vehicle.Model, Generation = vehicle.Generation, EndProductionYear = vehicle.EndProductionYear, StartProductionYear = vehicle.StartProductionYear, VehicleTechSpecification = request.VehicleTechSpecificationDTO }); clientSessionHandle.StartTransaction(); try { await sparePartsDbContext.Vehicles.UpdateOneAsync(filter, vehicleTechSpecificationUpdateDefinition); await sparePartsIntegrationEventService.PublishThroughEventBusAsync(askForSparePartsEvent); await clientSessionHandle.CommitTransactionAsync(); } catch (Exception ex) { logger.Information($"Can`t create vehicle tech specification : {vehicleTechSpecifictaion.ToJson()}. Exception: {ex.Message}"); clientSessionHandle.AbortTransaction(); return(Maybe <string> .None); } return(vehicleTechSpecifictaion.Id.ToString()); }
public void Dispose() { if (null != session) { if (session.IsInTransaction) { session.AbortTransaction(); } session.Dispose(); } }
public int SalvarAlteracoes() { try { _session.CommitTransaction(); return(1); } catch { _session.AbortTransaction(); return(0); } }
/// <summary> /// CloseTransaction /// </summary> public void CloseTransaction() { if (conn == null) { throw new Exception("Connection has not initialize."); } if (session == null) { throw new Exception("StartTransaction has not initialize."); } session.AbortTransaction(); session = null; }
protected override void MarkJobFailedImpl(Guid jobId, Exception cause) { //TODO Docs using (IClientSessionHandle session = _client.StartSession()) { session.StartTransaction(); try { if (!TryGetMongoExtractJobDoc(jobId, out MongoExtractJobDoc toFail)) { throw new ApplicationException($"Could not find job {jobId} in the job store"); } if (toFail.JobStatus == ExtractJobStatus.Failed || toFail.FailedJobInfoDoc != null) { throw new ApplicationException($"Job {jobId} is already marked as failed"); } toFail.JobStatus = ExtractJobStatus.Failed; toFail.FailedJobInfoDoc = new MongoFailedJobInfoDoc(cause, _dateTimeProvider); ReplaceOneResult res = _inProgressJobCollection.ReplaceOne(GetFilterForSpecificJob <MongoExtractJobDoc>(jobId), toFail); if (!res.IsAcknowledged || res.ModifiedCount != 1) { throw new ApplicationException($"Received invalid ReplaceOneResult: {res}"); } } catch (Exception) { Logger.Debug("Caught exception from transaction. Aborting before re-throwing"); session.AbortTransaction(); throw; } // TODO(rkm 2020-03-03) Can potentially add a retry here session.CommitTransaction(); } }
private static CallbackOutcome <TResult> ExecuteCallback <TResult>(IClientSessionHandle clientSession, Func <IClientSessionHandle, CancellationToken, TResult> callback, DateTime startTime, IClock clock, CancellationToken cancellationToken) { try { var result = callback(clientSession, cancellationToken); return(new CallbackOutcome <TResult> .WithResult(result)); } catch (Exception ex) { if (IsTransactionInStartingOrInProgressState(clientSession)) { clientSession.AbortTransaction(cancellationToken); } if (HasErrorLabel(ex, TransientTransactionErrorLabel) && !HasTimedOut(startTime, clock.UtcNow)) { return(new CallbackOutcome <TResult> .WithShouldRetryTransaction()); } throw; } }
public void Rollback(Enlistment enlistment) { _session.AbortTransaction(); enlistment.Done(); }
public void Abort() { Session.AbortTransaction(); }
//public List<User> GetUsers() //{ // //Create the collection object that represents the "users" collection // var users = session.Client.GetDatabase("MyPerformance").GetCollection<User>("users"); // return users; //} public async Task <List <User> > InitUsers(List <User> existingUsers) { var users = session.Client.GetDatabase("MyPerformance").GetCollection <User>("users"); //Clean up the collection if there is data in there // users.Database.DropCollection("users"); PrincipalContext ctx = new PrincipalContext(ContextType.Machine, Environment.MachineName); UserPrincipal user = new UserPrincipal(ctx); user.Name = "*"; PrincipalSearcher ps = new PrincipalSearcher(); ps.QueryFilter = user; PrincipalSearchResult <Principal> result = ps.FindAll(); var machineId = Machine.GetMachineId(); try { Console.WriteLine("User Accounts\n"); foreach (Principal p in result) { using (UserPrincipal mo = (UserPrincipal)p) { Console.WriteLine("Account : " + mo.Name); //Begin transaction Console.WriteLine("Local, checking if already exists"); // check if the user already exists if (existingUsers.Any(_ => _.Name == mo.Name.ToString())) { continue; } Console.WriteLine("Adding : " + mo.Name); session.StartTransaction(); try { var newUser = new User { Name = mo.Name, MachineId = machineId, SamAccountName = mo.SamAccountName, DisplayName = mo.DisplayName, SID = mo.Sid.ToString(), UserPrincipalName = mo.UserPrincipalName, Description = mo.Description }; await users.InsertOneAsync(newUser); session.CommitTransaction(); existingUsers.Add(newUser); } catch (Exception e) { session.AbortTransaction(); Console.WriteLine("Error writing to MongoDB: " + e.Message); } } } return(existingUsers); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(existingUsers); } }
protected override void CompleteJobImpl(Guid jobId) { //TODO Docs using (IClientSessionHandle session = _client.StartSession()) { session.StartTransaction(); string expectedCollNameForJob = ExpectedFilesCollectionName(jobId); string statusCollNameForJob = StatusCollectionName(jobId); try { if (!TryGetMongoExtractJobDoc(jobId, out MongoExtractJobDoc toComplete)) { throw new ApplicationException($"Could not find job {jobId} in the job store"); } if (toComplete.JobStatus == ExtractJobStatus.Failed) { throw new ApplicationException($"Job {jobId} is marked as failed"); } var completedJob = new MongoCompletedExtractJobDoc(toComplete, _dateTimeProvider.UtcNow()); _completedJobCollection.InsertOne(completedJob); DeleteResult res = _inProgressJobCollection.DeleteOne(GetFilterForSpecificJob <MongoExtractJobDoc>(jobId)); if (!res.IsAcknowledged) { throw new ApplicationException("Job data was archived but could not delete original from job store"); } // Move the associated docs from each collection to the archives IMongoCollection <MongoExpectedFilesDoc> expectedTempCollection = _database.GetCollection <MongoExpectedFilesDoc>(expectedCollNameForJob); if (expectedTempCollection.CountDocuments(FilterDefinition <MongoExpectedFilesDoc> .Empty) == 0) { throw new ApplicationException($"Collection of MongoExpectedFilesDoc for job {jobId} was missing or empty"); } using (IAsyncCursor <MongoExpectedFilesDoc> cursor = expectedTempCollection.FindSync(FilterDefinition <MongoExpectedFilesDoc> .Empty)) { while (cursor.MoveNext()) { _completedExpectedFilesCollection.InsertMany(cursor.Current); } } IMongoCollection <MongoFileStatusDoc> statusTemp = _database.GetCollection <MongoFileStatusDoc>(statusCollNameForJob); if (statusTemp.CountDocuments(FilterDefinition <MongoFileStatusDoc> .Empty) == 0) { throw new ApplicationException($"Collection of MongoFileStatusDoc for job {jobId} was missing or empty"); } using (IAsyncCursor <MongoFileStatusDoc> cursor = statusTemp.FindSync(FilterDefinition <MongoFileStatusDoc> .Empty)) { while (cursor.MoveNext()) { _completedStatusCollection.InsertMany(cursor.Current); } } } catch (Exception) { Logger.Debug("Caught exception from transaction. Aborting before re-throwing"); session.AbortTransaction(); throw; } // TODO(rkm 2020-03-03) Can potentially add a retry here session.CommitTransaction(); // NOTE(rkm 2020-03-09) "Operations that affect the database catalog, such as creating or dropping a collection or an index, are not allowed in transactions" _database.DropCollection(expectedCollNameForJob); _database.DropCollection(statusCollNameForJob); } }
public void RollbackTransaction() { session?.AbortTransaction(); }
// protected methods protected override void CallMethod(IClientSessionHandle session, CancellationToken cancellationToken) { session.AbortTransaction(cancellationToken); }