Esempio 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;
     }
 }
Esempio n. 2
0
 internal void CommitTransaction()
 {
     if (IsInRunningState())
     {
         _transactionSession.CommitTransaction();
     }
 }
Esempio n. 3
0
 public override void Commit()
 {
     base.Commit();
     _clientSessionHandle.CommitTransaction();
     _clientSessionHandle.Dispose();
     _clientSessionHandle = null;
 }
Esempio 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;
                    }
                }
            }
        }
Esempio 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--;
        }
Esempio 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;
                }
            }
        }
Esempio n. 7
0
 public void Commit()
 {
     if (_clientSession.IsInTransaction)
     {
         _clientSession.CommitTransaction();
     }
 }
Esempio 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;
             }
         }
     }
 }
Esempio n. 9
0
 public void Commit()
 {
     if (_session != null)
     {
         _session.CommitTransaction();
     }
     _session = null;
 }
Esempio n. 10
0
 public void CommitTransaction()
 {
     if (_session == null)
     {
         throw new InvalidOperationException("Transaction already closed");
     }
     _session.CommitTransaction();
 }
Esempio n. 11
0
 /// <summary>
 /// Commits data transaction to data source if applicable
 /// </summary>
 public void Commit()
 {
     if (!AutoCommit)
     {
         _transSession.CommitTransaction();
         _transSession = _client.StartSession();
     }
 }
Esempio n. 12
0
 public void CommitTransaction()
 {
     if (session == null)
     {
         throw new CjExpInvalidOperationException("Transaction session not started");
     }
     session.CommitTransaction();
     session = null;
 }
Esempio 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;
                    }
                }
            }
        }
Esempio 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);
        }
Esempio n. 15
0
        public void Commit()
        {
            if (_session == null)
            {
                throw new Exception("Session has been gone somehow!");
            }

            _session.CommitTransaction();
            _session.Dispose();
        }
Esempio 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));
     }
 }
Esempio n. 18
0
 public void Commit(Enlistment enlistment)
 {
     try
     {
         _sessionHandle.CommitTransaction();
         enlistment.Done();
     }
     finally
     {
         _unregister();
     }
 }
Esempio n. 19
0
 public int SalvarAlteracoes()
 {
     try
     {
         _session.CommitTransaction();
         return(1);
     }
     catch
     {
         _session.AbortTransaction();
         return(0);
     }
 }
Esempio 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();
        }
Esempio 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);
     });
 }
Esempio 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();
        }
Esempio 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;
     }
 }
Esempio 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();
 }
Esempio n. 26
0
 public void CommitTransaction()
 {
     mongoSession.CommitTransaction();
 }
Esempio n. 27
0
 public void Commit(Enlistment enlistment)
 {
     Retryer.Retry(() => _session.CommitTransaction(), _maxRetries);
     enlistment.Done();
 }
Esempio 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);
            }
        }
Esempio n. 29
0
 public IDataAdapter CommitTransaction()
 {
     _session.CommitTransaction();
     return(this);
 }
 public void Execute()
 {
     _session.CommitTransaction();
 }