Ejemplo n.º 1
0
 private void RemoveUserActivationCode(string userName)
 {
     try
     {
         DBSession.StartTransaction();
         UserCollection.DeleteOne(user => user.UserName.Equals(user.UserName));
         DBSession.CommitTransaction();
     }
     catch (System.Exception)
     {
         DBSession.AbortTransaction();
         throw;
     }
 }
Ejemplo n.º 2
0
 internal void CommitTransaction()
 {
     if (IsInRunningState())
     {
         _transactionSession.CommitTransaction();
     }
 }
Ejemplo n.º 3
0
 public override void Commit()
 {
     base.Commit();
     _clientSessionHandle.CommitTransaction();
     _clientSessionHandle.Dispose();
     _clientSessionHandle = null;
 }
Ejemplo n.º 4
0
        public static void CommitWithRetry(this IClientSessionHandle session)
        {
            while (true)
            {
                try
                {
                    session.CommitTransaction();
                    Console.WriteLine("Transaction committed.");
                    break;
                }
                catch (MongoException exception)
                {
                    // can retry commit
                    // Driver already attempts a retry ONCE if there's a network class error.

                    // In face of "write concern timeout" exception, driver retries once, but you may see "UnknownTransactionCommitResult" if that failed.
                    if (exception.HasErrorLabel("UnknownTransactionCommitResult"))
                    {
                        Console.WriteLine("UnknownTransactionCommitResult, retrying commit operation");
                        continue;
                    }
                    else
                    {
                        Console.WriteLine($"Error during commit: {exception.Message}.");
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 5
0
        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--;
        }
Ejemplo n.º 6
0
        private static bool CommitWithRetries(IClientSessionHandle clientSession, DateTime startTime, IClock clock, CancellationToken cancellationToken)
        {
            while (true)
            {
                try
                {
                    clientSession.CommitTransaction(cancellationToken);
                    return(true);
                }
                catch (Exception ex)
                {
                    var now = clock.UtcNow; // call UtcNow once since we need to facilitate predictable mocking
                    if (ShouldRetryCommit(ex, startTime, now))
                    {
                        continue;
                    }

                    if (HasErrorLabel(ex, TransientTransactionErrorLabel) && !HasTimedOut(startTime, now))
                    {
                        return(false); // the transaction will be retried
                    }

                    throw;
                }
            }
        }
Ejemplo n.º 7
0
 public void Commit()
 {
     if (_clientSession.IsInTransaction)
     {
         _clientSession.CommitTransaction();
     }
 }
Ejemplo n.º 8
0
 // Start Transactions Retry Example 2
 public void CommitWithRetry(IClientSessionHandle session)
 {
     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($"Excpetion during commit: {exception.Message}.");
                 throw;
             }
         }
     }
 }
Ejemplo n.º 9
0
 public void Commit()
 {
     if (_session != null)
     {
         _session.CommitTransaction();
     }
     _session = null;
 }
Ejemplo n.º 10
0
 public void CommitTransaction()
 {
     if (_session == null)
     {
         throw new InvalidOperationException("Transaction already closed");
     }
     _session.CommitTransaction();
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Commits data transaction to data source if applicable
 /// </summary>
 public void Commit()
 {
     if (!AutoCommit)
     {
         _transSession.CommitTransaction();
         _transSession = _client.StartSession();
     }
 }
Ejemplo n.º 12
0
 public void CommitTransaction()
 {
     if (session == null)
     {
         throw new CjExpInvalidOperationException("Transaction session not started");
     }
     session.CommitTransaction();
     session = null;
 }
Ejemplo n.º 13
0
        // 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;
                    }
                }
            }
        }
Ejemplo n.º 14
0
        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);
        }
Ejemplo n.º 15
0
        public void Commit()
        {
            if (_session == null)
            {
                throw new Exception("Session has been gone somehow!");
            }

            _session.CommitTransaction();
            _session.Dispose();
        }
Ejemplo n.º 16
0
 public void Commit()
 {
     try
     {
         _transactionSession.CommitTransaction();
     }
     finally
     {
         _transactionSession.Dispose();
     }
 }
 public OperationResult Execute(CancellationToken cancellationToken)
 {
     try
     {
         _session.CommitTransaction(cancellationToken);
         return(OperationResult.Empty());
     }
     catch (Exception ex)
     {
         return(OperationResult.FromException(ex));
     }
 }
Ejemplo n.º 18
0
 public void Commit(Enlistment enlistment)
 {
     try
     {
         _sessionHandle.CommitTransaction();
         enlistment.Done();
     }
     finally
     {
         _unregister();
     }
 }
Ejemplo n.º 19
0
 public int SalvarAlteracoes()
 {
     try
     {
         _session.CommitTransaction();
         return(1);
     }
     catch
     {
         _session.AbortTransaction();
         return(0);
     }
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Commit Transaction
        /// </summary>
        public void CommitTransaction()
        {
            if (conn == null)
            {
                throw new Exception("Connection has not initialize.");
            }

            if (session == null)
            {
                throw new Exception("StartTransaction has not initialize.");
            }

            session.CommitTransaction();
        }
Ejemplo n.º 21
0
 public void CommitTransaction(CancellationToken cancellationToken = default(CancellationToken))
 {
     if (DotUseTransaction)
     {
         return;
     }
     Policy.Handle <MongoConnectionException>(i => i.InnerException.GetType() == typeof(IOException) || i.InnerException.GetType() == typeof(SocketException))
     .Or <MongoException>(i => i.HasErrorLabel("UnknownTransactionCommitResult") || i.HasErrorLabel("TransientTransactionError"))     //TransientTransactionError
     .Retry(3, (exception, retryCount) => { Console.WriteLine("Retry." + retryCount); })
     .Execute(() =>
     {
         session.CommitTransaction(cancellationToken);
     });
 }
Ejemplo n.º 22
0
        public void CommitTransaction_NoError()
        {
            //Act
            Action action = () =>
            {
                using (IClientSessionHandle session = _mongoRsResource.Client.StartSession())
                {
                    IMongoCollection <BsonDocument> collection = _mongoRsResource.CreateCollection <BsonDocument>("bar");
                    session.StartTransaction();
                    collection.InsertOne(session, new BsonDocument("name", "test"));
                    session.CommitTransaction();
                }
            };

            //Assert
            action.Should().NotThrow();
        }
Ejemplo n.º 23
0
 /// <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;
     }
 }
Ejemplo n.º 24
0
        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();
            }
        }
 protected override void CommitTransaction()
 {
     _session.CommitTransaction();
 }
Ejemplo n.º 26
0
 public void CommitTransaction()
 {
     mongoSession.CommitTransaction();
 }
Ejemplo n.º 27
0
 public void Commit(Enlistment enlistment)
 {
     Retryer.Retry(() => _session.CommitTransaction(), _maxRetries);
     enlistment.Done();
 }
Ejemplo n.º 28
0
        //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);
            }
        }
Ejemplo n.º 29
0
 public IDataAdapter CommitTransaction()
 {
     _session.CommitTransaction();
     return(this);
 }
 public void Execute()
 {
     _session.CommitTransaction();
 }