Beispiel #1
0
        public void transact(Func <ICommandBuilder, TransactionAction> statementBlockDelegate)
        {
            using (TConnection connection = new TConnection())
            {
                connection.ConnectionString = this.connectionString;
                connection.Open();

                using (IDbTransaction transaction = connection.BeginTransaction())
                {
                    ICommandBuilder commandBuilder = new PrvCommandBuilder(transaction);

                    TransactionAction action = statementBlockDelegate(commandBuilder);

                    if (action == TransactionAction.Commit)
                    {
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Rollback();
                    }
                }

                connection.Close();
            }
        }
 /// <summary>
 /// Includeds the by reload.
 /// </summary>
 /// <param name="action">The action.</param>
 /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
 private bool includedByReload(TransactionAction action)
 {
     return
         (action.Name == "ReloadAssembly" ||
          includedByComponentsInvalidation(action) ||
          includedByComponentsLoad(action));
 }
Beispiel #3
0
        public async Task ValidateAsync(Transaction entity, TransactionAction action)
        {
            switch (action)
            {
            case TransactionAction.Create:
                await ValidateCreateAsync(entity);

                break;

            case TransactionAction.Update:
                break;

            case TransactionAction.Delete:
                break;

            case TransactionAction.Submit:
                break;

            case TransactionAction.Approve:
                break;

            case TransactionAction.Reject:
                break;

            default:
                throw new NotImplementedException();
            }
        }
Beispiel #4
0
        private IEnumerator TransactionOut()
        {
            yield return(new WaitForEndOfFrame());

            while (true)
            {
                TransactionImage.color = new Color(TargetColor.r, TargetColor.g, TargetColor.b, TransactionImage.color.a + ColorStep);
                if (TransactionImage.color.a >= TargetColor.a - 0.1f && !_isTarget)
                {
                    _isTarget = true;
                    TransactionImage.color = TargetColor;
                    if (_isLoadingEnable)
                    {
                        LoadingContainer.gameObject.SetActive(true);
                    }
                    yield return(new WaitForEndOfFrame());
                }
                if (_isTarget)
                {
                    if (TranactionOutEnd != null)
                    {
                        TranactionOutEnd();
                        TranactionOutEnd = null;
                    }
                    yield break;
                }
                yield return(new WaitForEndOfFrame());
            }
        }
        private void OnTransactionClosed(DesignerHostTransaction raiser, TransactionAction action)
        {
            bool commit          = false;
            bool lastTransaction = false;

            if (_transactions.Peek() != raiser)
            {
                throw new InvalidOperationException("Current transaction differs from the one a commit was requested for.");
            }

            if (_transactions.Count == 1)
            {
                lastTransaction = true;
            }
            if (action == TransactionAction.Commit)
            {
                commit = true;
            }

            _transactions.Pop();

            if (TransactionClosed != null)
            {
                TransactionClosed(this, new DesignerTransactionCloseEventArgs(commit, lastTransaction));
            }
        }
        /// <summary>
        /// Add after action to current transaction.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <param name="name">The name.</param>
        /// <param name="predicate">The predicate.</param>
        /// <param name="keys">The keys.</param>
        private void addAfterAction(Action action, string name, IsIncludedPredicate predicate, params object[] keys)
        {
            var transactionAction = new TransactionAction(action, name, predicate, keys);

            //attach to current transaction or to root
            Transactions.AttachAfterAction(Transactions.CurrentTransaction, transactionAction);
        }
 /// <summary>
 /// Handles the transactional listener exception.
 /// </summary>
 /// <param name="e">The exception thrown while processing the message.</param>
 /// <param name="message">The message.</param>
 /// <param name="messageQueueTransaction">The message queue transaction.</param>
 /// <returns>The TransactionAction retruned by the TransactionalExceptionListener</returns>
 protected virtual TransactionAction HandleTransactionalListenerException(Exception e, Message message,
                                                                          MessageQueueTransaction
                                                                          messageQueueTransaction)
 {
     try
     {
         TransactionAction transactionAction =
             InvokeTransactionalExceptionListener(e, message, messageQueueTransaction);
         if (Active)
         {
             // Regular case: failed while active.
             // Log at error level.
             LOG.Error("Execution of message listener failed", e);
         }
         else
         {
             // Rare case: listener thread failed after container shutdown.
             // Log at debug level, to avoid spamming the shutdown log.
             LOG.Debug("Listener exception after container shutdown", e);
         }
         return(transactionAction);
     }
     catch (Exception ex)
     {
         LOG.Error("Exception invoking MessageTransactionExceptionHandler.  Rolling back transaction.", ex);
         return(TransactionAction.Rollback);
     }
 }
Beispiel #8
0
        public void receiveMessage(IFailedMessageHandler failedMessageHandler)
        {
            if (incomingQueue == null)
            {
                throw new NullReferenceException("La coda di ricezione non è stata specificata");
            }
            gotMessage = null;


            SetFormatter();


            MessageQueueTransaction transaction = new MessageQueueTransaction();

            transaction.Begin();
            // Message message = null;
            try
            {
                gotMessage = incomingQueue.Receive(TimeSpan.Zero, transaction);

                Log("Received message ID: " + gotMessage.Id);
                ProcessMessage();
                transaction.Commit();
                Log("Message processed OK");
            }
            catch (Exception e)
            {
                Log("Message failed");
                TransactionAction transactionAction = TransactionAction.ROLLBACK;

                if (gotMessage == null)
                {
                    Log("Message couldn't be received: " + e.Message);
                    Log("Message couldn't be received (stak: " + e.StackTrace);
                }
                else
                {
                    try
                    {
                        transactionAction = failedMessageHandler.HandleFailedMessage(gotMessage, transaction);
                    }
                    catch (Exception failureHandlerException)
                    {
                        Log("Error during failure handling: " + failureHandlerException.Message);
                    }
                }

                if (transactionAction == TransactionAction.ROLLBACK)
                {
                    transaction.Abort();
                    Log("Transaction rolled back");
                }
                else
                {
                    transaction.Commit();
                    Log("Transaction commited - message removed from queue");
                }
            }
        }
Beispiel #9
0
        private Payload CreateTransactionCommonPayload(Proposal ccodeProposal, ByteString propResponsePayload, List <Endorsement> endrsements)
        {
            ChaincodeEndorsedAction chaincodeEndorsedAction = new ChaincodeEndorsedAction {
                ProposalResponsePayload = propResponsePayload
            };

            chaincodeEndorsedAction.Endorsements.AddRange(endrsements);
            //ChaincodeActionPayload
            ChaincodeActionPayload chaincodeActionPayload = new ChaincodeActionPayload {
                Action = chaincodeEndorsedAction
            };

            //We need to remove any transient fields - they are not part of what the peer uses to calculate hash.
            ChaincodeProposalPayload p = ChaincodeProposalPayload.Parser.ParseFrom(ccodeProposal.Payload);
            ChaincodeProposalPayload chaincodeProposalPayloadNoTrans = new ChaincodeProposalPayload {
                Input = p.Input
            };

            chaincodeActionPayload.ChaincodeProposalPayload = chaincodeProposalPayloadNoTrans.ToByteString();


            TransactionAction transactionAction = new TransactionAction();

            Header header = Header.Parser.ParseFrom(ccodeProposal.Header);

            if (Config.Instance.ExtraLogLevel(10))
            {
                if (null != diagnosticFileDumper)
                {
                    StringBuilder sb = new StringBuilder(10000);
                    sb.Append("transaction header bytes:" + header.ToByteString().ToHexString());
                    sb.Append("\n");
                    sb.Append("transaction header sig bytes:" + header.SignatureHeader.ToHexString());
                    logger.Trace("transaction header:  " + diagnosticFileDumper.CreateDiagnosticFile(sb.ToString()));
                }
            }

            transactionAction.Header = header.SignatureHeader;

            if (Config.Instance.ExtraLogLevel(10))
            {
                if (null != diagnosticFileDumper)
                {
                    logger.Trace("transactionActionBuilder.setPayload: " + diagnosticFileDumper.CreateDiagnosticFile(chaincodeActionPayload.ToByteString().ToHexString()));
                }
            }

            transactionAction.Payload = chaincodeActionPayload.ToByteString();

            //Transaction
            Transaction transaction = new Transaction();

            transaction.Actions.Add(transactionAction);

            return(new Payload {
                Header = header, Data = transaction.ToByteString()
            });
        }
Beispiel #10
0
 /// <summary>
 /// Requires updating of composition point list.
 /// </summary>
 private void requireUpdate()
 {
     DispatchedAction(() =>
     {
         var action = new TransactionAction(() => FlushCompositionPointUpdates()
                                            , "UpdateCompositionPoints", (t) => t.Name == "UpdateCompositionPoints", this);
         Transactions.AttachAfterAction(null, action);
     });
 }
Beispiel #11
0
        public void InReadTransaction(TransactionAction transactionClosure)
        {
            const int voidReturn = 0;

            InReadTransaction(container =>
            {
                transactionClosure(container);
                return(voidReturn);
            });
        }
 private int Transaction(Shard s, TransactionAction action, int parameterA, int parameterB)
 {
     try
     {
         return action(parameterA, parameterB, s.random);
     }
     finally
     {
         s.spinLock.Unlock();
     }
 }
Beispiel #13
0
        private void DoTranAction(int climberID, string climberName, TransactionAction action, byte routeToClean)
        {
            long?activeTranID, nextTranID, toCheck;

            try
            {
                ResultListSpeed.GetSpeedTransactions(climberID, listID, out activeTranID, out nextTranID, cn);
                toCheck = (action == TransactionAction.ROLLBACK) ? activeTranID : nextTranID;
                string message = (action == TransactionAction.ROLLBACK) ? "��������" : "�������";
                if (toCheck == null || !toCheck.HasValue)
                {
                    MessageBox.Show(this, "���������� " + message + " ���������");
                    return;
                }
                if (MessageBox.Show(this, "�� �������, ��� ������ " + message + " ��������� �������� ��������� (" +
                                    climberName + ")?", message + " ���������?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                    == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
                SqlTransaction tran = cn.BeginTransaction();
                try
                {
                    bool res;
                    if (action == TransactionAction.ROLLBACK)
                    {
                        res = StaticClass.RollbackTransaction(toCheck.Value, cn, tran);
                    }
                    else
                    {
                        res = StaticClass.RestoreLogicTransaction(toCheck.Value, cn, tran);
                    }
                    if (res)
                    {
                        ResultListSpeed.RefreshTable(listID, baseIID, RefreshData, cn, CR, tran, false);
                        tran.Commit();
                        RefreshData();
                        ClearClimberOnRoute(routeToClean);
                    }
                    else
                    {
                        MessageBox.Show("���������� ������� ����������� ���������� ������� SQL Server");
                        tran.Rollback();
                    }
                }
                catch (Exception ex)
                {
                    try { tran.Rollback(); }
                    catch { }
                    throw ex;
                }
            }
            catch (Exception ex) { MessageBox.Show("������ ���������� �������:\r\n" + ex.Message); }
        }
Beispiel #14
0
            /// <summary>
            /// Commit all pending inventory actions in this transaction.
            /// </summary>
            public void Commit()
            {
                while (actions.Count > 0)
                {
                    TransactionAction action       = actions.Dequeue();
                    Container         srcContainer = owner.Inventory.GetContainer(action.Source);
                    Container         dstContainer = owner.Inventory.GetContainer(action.Destination);

                    Item srcItem = srcContainer.GetItem(action.SrcSlot);
                    if (srcItem == null && action.Source != ContainerType.None)
                    {
                        return;
                    }

                    Item dstItem = dstContainer?.GetItem(action.DstSlot);
                    if (dstItem == null && action.Destination != ContainerType.None)
                    {
                        return;
                    }

                    switch (action.InventoryAction)
                    {
                    case InventoryAction.Discard:
                        owner.Inventory.RemoveItem(srcItem, srcContainer);
                        break;

                        #if DEBUG
                    default:
                        Console.WriteLine($"Unhandled inventory transaction action {action.InventoryAction}!");
                        break;
                        #endif
                    }

                    owner.Session.Send(new ServerInventoryUpdate
                    {
                        Id               = id,
                        Action           = action.InventoryAction,
                        SrcActorId       = owner.Character.ActorId,
                        SrcContainerType = action.Source,
                        SrcSlot          = action.SrcSlot,
                        SrcStackSize     = srcItem?.StackSize ?? 0u,
                        DstActorId       = owner.Character.ActorId,
                        DstContainerType = action.Destination,
                        DstSlot          = action.DstSlot,
                        DstStackSize     = dstItem?.StackSize ?? 0u
                    });
                }

                owner.Session.Send(new ServerInventoryUpdateFinish
                {
                    Id = id
                });
            }
Beispiel #15
0
 //public static ResourcePayloadContainerLink FindLinkByPayloadPath(ResourcePayloadContainerLink[] links, string payloadPath)
 //{
 //    foreach(ResourcePayloadContainerLink link in links)
 //    {
 //        if (link.PayloadPath.Equals(payloadPath))
 //            return link;
 //    }
 //    return null;
 //}
 //public static List<ResourcePayloadContainerLink> ReducePayloadPath(List<ResourcePayloadContainerLink> links)
 //{
 //    List<ResourcePayloadContainerLink> result = new List<ResourcePayloadContainerLink>();
 //    foreach (ResourcePayloadContainerLink originalLink in links)
 //        result.Add(originalLink.Clone() as ResourcePayloadContainerLink);
 //    foreach(ResourcePayloadContainerLink link in result)
 //    {
 //        if (!String.IsNullOrEmpty(link.PayloadPath))
 //        {
 //            if (link.PayloadPath.Contains("/") && link.PayloadPath.Length> 1)
 //            {
 //                link.PayloadPath = link.PayloadPath.Substring(link.PayloadPath.IndexOf("/") + 1);
 //            }
 //                else
 //                link.PayloadPath = "";
 //        }
 //    }
 //    return result;
 //}
 //public static List<ResourcePayloadContainerLink> ExtendPayloadPath(List<ResourcePayloadContainerLink> links, string payload)
 //{
 //    List<ResourcePayloadContainerLink> result = new List<ResourcePayloadContainerLink>();
 //    foreach (ResourcePayloadContainerLink originalLink in links)
 //        result.Add(originalLink.Clone() as ResourcePayloadContainerLink);
 //    foreach (ResourcePayloadContainerLink link in result)
 //    {
 //        if (!String.IsNullOrEmpty(link.PayloadPath))
 //        {
 //                link.PayloadPath = payload + "/" + link.PayloadPath;
 //        }
 //    }
 //    return result;
 //}
 public static HttpMethod GetHttpMethod(TransactionAction transactionAction)
 {
     switch (transactionAction)
     {
         case TransactionAction.Created:
             return HttpMethod.POST;
         case TransactionAction.Updated:
             return HttpMethod.PUT;
         case TransactionAction.Deleted:
         default:
             return HttpMethod.DELETE;
     }
 }
Beispiel #16
0
        internal static string GetHttpMethod(TransactionAction transactionAction)
        {
            switch (transactionAction)
            {
            case TransactionAction.Created:
                return("POST");

            case TransactionAction.Updated:
                return("PUT");

            case TransactionAction.Deleted:
                return("DELETE");
            }
            return("");
        }
        //public static ResourcePayloadContainerLink FindLinkByPayloadPath(ResourcePayloadContainerLink[] links, string payloadPath)
        //{
        //    foreach(ResourcePayloadContainerLink link in links)
        //    {
        //        if (link.PayloadPath.Equals(payloadPath))
        //            return link;
        //    }

        //    return null;
        //}

        //public static List<ResourcePayloadContainerLink> ReducePayloadPath(List<ResourcePayloadContainerLink> links)
        //{
        //    List<ResourcePayloadContainerLink> result = new List<ResourcePayloadContainerLink>();
        //    foreach (ResourcePayloadContainerLink originalLink in links)
        //        result.Add(originalLink.Clone() as ResourcePayloadContainerLink);

        //    foreach(ResourcePayloadContainerLink link in result)
        //    {
        //        if (!String.IsNullOrEmpty(link.PayloadPath))
        //        {
        //            if (link.PayloadPath.Contains("/") && link.PayloadPath.Length> 1)
        //            {
        //                link.PayloadPath = link.PayloadPath.Substring(link.PayloadPath.IndexOf("/") + 1);
        //            }
        //                else
        //                link.PayloadPath = "";
        //        }
        //    }
        //    return result;
        //}

        //public static List<ResourcePayloadContainerLink> ExtendPayloadPath(List<ResourcePayloadContainerLink> links, string payload)
        //{
        //    List<ResourcePayloadContainerLink> result = new List<ResourcePayloadContainerLink>();
        //    foreach (ResourcePayloadContainerLink originalLink in links)
        //        result.Add(originalLink.Clone() as ResourcePayloadContainerLink);

        //    foreach (ResourcePayloadContainerLink link in result)
        //    {
        //        if (!String.IsNullOrEmpty(link.PayloadPath))
        //        {
        //                link.PayloadPath = payload + "/" + link.PayloadPath;
        //        }
        //    }
        //    return result;
        //}

        public static HttpMethod GetHttpMethod(TransactionAction transactionAction)
        {
            switch (transactionAction)
            {
            case TransactionAction.Created:
                return(HttpMethod.POST);

            case TransactionAction.Updated:
                return(HttpMethod.PUT);

            case TransactionAction.Deleted:
            default:
                return(HttpMethod.DELETE);
            }
        }
Beispiel #18
0
 public TransactionTrace(
     TransactionAction action,
     string blockHash,
     BigInteger blockNumber,
     string error,
     string transactionHash,
     string type)
 {
     Action          = action;
     BlockHash       = blockHash;
     BlockNumber     = blockNumber;
     Error           = error;
     TransactionHash = transactionHash;
     Type            = type;
 }
Beispiel #19
0
 public Transaction(ApplicationUser _customer, double _amount, TransactionAction action)
 {
     CreatedDate   = DateTime.Now;
     CurrentAmount = _customer.Balance;
     amount        = _amount;
     customer      = _customer;
     if (action == TransactionAction.Add)
     {
         customer.Balance += amount;
     }
     else if (action == TransactionAction.Extract)
     {
         customer.Balance -= amount;
         amount           *= -1;
     }
 }
Beispiel #20
0
 public static void ProcessTransaction(TransactionAction action)
 {
     using (ConnectionManager mrg = ConnectionManager.GetManager("TapMangoDatabase"))
     {
         try
         {
             var transaction = mrg.Connection.BeginTransaction();
             action((SqlTransaction)transaction);
             transaction.Commit();
         }
         catch
         {
             mrg.Connection.Close();
             throw;
         }
     }
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="transaction"></param>
 /// <param name="actionToTake"></param>
 public static void RollbackOrCommit(this IDbTransaction transaction, TransactionAction actionToTake)
 {
     if (transaction == null)
     {
         return;
     }
     using (transaction)
     {
         if (actionToTake == TransactionAction.Rollback)
         {
             transaction.Rollback();
         }
         else
         {
             transaction.Commit();
         }
     }
 }
Beispiel #22
0
        private void RotateThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            if (_imageControl == null)
            {
                return;
            }
            if (!_isRotate)
            {
                _transaction = _imageControl.ControlManager.ReviseRotateCenterSelected;
                _transaction.Execute();
                _isRotate = true;
            }

            var currentPoint = Mouse.GetPosition(null);
            var deltaVector  = Point.Subtract(currentPoint, _centerPoint);
            var angle        = Math.Round(Vector.AngleBetween(_startVector, deltaVector), 0);

            _imageControl.ControlManager.DragRotateSelected(angle - _angle, false);
            _angle = angle;
        }
Beispiel #23
0
        private void CanIOperate(TransactionAction transactionAction)
        {
            switch (TransactionState)
            {
            case TransactionState.InProgress:
                if (transactionAction == TransactionAction.Dispose)
                {
                    throw new TransactionInProgressException();
                }
                break;

            case TransactionState.Ended:
                if (transactionAction != TransactionAction.Dispose)
                {
                    throw new TransactionEndedException();
                }
                break;

            case TransactionState.Disposed:
                throw new TransactionDisposedException();
            }
        }
        public async Task <Transaction> Put(TransactionAction transaction)
        {
            try{
                List <Task> TaskList = new List <Task>();
                var         e        = new Employee();
                e.EmployeeId = transaction.Transaction.EmployeeId;
                employeeRepo.GetEmployee(e);
                var newTransaction = await transactionRepo.AddTransaction(transaction.Transaction);

                foreach (Item i in transaction.Items)
                {
                    i.TransactionId = newTransaction.TransactionId;
                    TaskList.Add(itemRepo.AddItem(i));
                }
                Task.WaitAll(TaskList.ToArray());
                await transactionRepo.SaveAsync();

                return(newTransaction);
            }catch (KeyNotFoundException) {
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
            }
        }
Beispiel #25
0
        /// <inheritdoc/>
        public async ValueTask <long> AddMessage(
            long transId,
            long queueId,
            byte[] payload,
            DateTime addDateTime,
            string metaData,
            int priority,
            int maxAttempts,
            DateTime?expiryDateTime,
            int correlation,
            string groupName,
            TransactionAction transactionAction,
            MessageState messageState)
        {
            const string sql = "INSERT INTO Messages (QueueId, TransactionId, TransactionAction, State, AddDateTime, Priority, MaxAttempts, Attempts, ExpiryDateTime, Payload, CorrelationId, GroupName, Metadata) VALUES " +
                               "(@QueueId, @TransactionId, @TransactionAction, @State, @AddDateTime, @Priority, @MaxAttempts, 0, @ExpiryDateTime, @Payload, @CorrelationId, @GroupName, @Metadata);" +
                               "SELECT last_insert_rowid();";

            return(await this.ExecuteAsync <long>(async (connection) =>
            {
                var param = new
                {
                    QueueId = queueId,
                    TransactionId = transId,
                    TransactionAction = transactionAction,
                    State = messageState,
                    AddDateTime = addDateTime.ToUnixEpoch(),
                    Priority = priority,
                    MaxAttempts = maxAttempts,
                    ExpiryDateTime = expiryDateTime?.ToUnixEpoch(),
                    Payload = payload,
                    CorrelationId = correlation,
                    GroupName = groupName,
                    Metadata = metaData
                };

                return await connection.ExecuteScalarAsync <long>(sql, param: param);
            }));
        }
Beispiel #26
0
        /// <inheritdoc/>
        public async ValueTask <long> AddMessage(
            long transId,
            long queueId,
            byte[] payload,
            DateTime addDateTime,
            string metaData,
            int priority,
            int maxAttempts,
            DateTime?expiryDateTime,
            int correlation,
            string groupName,
            TransactionAction transactionAction,
            MessageState messageState)
        {
            const string sql = "INSERT INTO messages (queue_id, transaction_id, transaction_action, state, add_datetime, priority, max_attempts, attempts, expiry_datetime, payload, correlation_id, group_name, metadata) VALUES " +
                               "(@QueueId, @TransactionId, @TransactionAction, @State, @AddDateTime, @Priority, @MaxAttempts, 0, @ExpiryDateTime, @Payload, @CorrelationId, @GroupName, @Metadata) returning id;";

            return(await this.ExecuteAsync <long>(async (connection) =>
            {
                var param = new
                {
                    QueueId = queueId,
                    TransactionId = transId,
                    TransactionAction = transactionAction,
                    State = messageState,
                    AddDateTime = addDateTime,
                    Priority = priority,
                    MaxAttempts = maxAttempts,
                    ExpiryDateTime = expiryDateTime,
                    Payload = payload,
                    CorrelationId = correlation,
                    GroupName = groupName,
                    Metadata = metaData
                };

                return await connection.ExecuteScalarAsync <long>(sql, param: param);
            }));
        }
Beispiel #27
0
 private IEnumerator TransactionIn()
 {
     LoadingContainer.gameObject.SetActive(false);
     while (true)
     {
         TransactionImage.color = new Color(TargetColor.r, TargetColor.g, TargetColor.b, TransactionImage.color.a - ColorStep);
         if (TransactionImage.color.a < 0.1f && !_isClean)
         {
             _isClean = true;
             TransactionImage.gameObject.SetActive(false);
             yield return(new WaitForEndOfFrame());
         }
         if (_isClean)
         {
             if (TranactionInEnd != null)
             {
                 TranactionInEnd();
                 TranactionInEnd = null;
             }
             yield break;
         }
         yield return(new WaitForEndOfFrame());
     }
 }
Beispiel #28
0
 TransactionAction IOmegaService.UpdateTransactionDate(ApplicationVersion version, TransactionAction transaction, DateTime dateTime)
 {
     return(RunSecurity(version, user =>
     {
         CheckRightChangeBalance(user);
         _repository.UpdateTransactionDate(transaction, dateTime, user);
         transaction.TransactionDate = dateTime;
         return transaction;
     }));
 }
        /// <summary>
        /// Does the recieve and execute using a local MessageQueueTransaction.
        /// </summary>
        /// <param name="mq">The mqessage queue.</param>
        /// <param name="status">The transactional status.</param>
        /// <returns>true if should continue peeking, false otherwise.</returns>
        protected virtual bool DoRecieveAndExecuteUsingResourceTransactionManagerWithTxQueue(MessageQueue mq,
                                                                                             ITransactionStatus status)
        {
            #region Logging

            if (LOG.IsDebugEnabled)
            {
                LOG.Debug("Executing DoRecieveAndExecuteUsingResourceTransactionManagerWithTxQueue");
            }

            #endregion Logging

            using (MessageQueueTransaction messageQueueTransaction = new MessageQueueTransaction())
            {
                messageQueueTransaction.Begin();

                #region Logging

                if (LOG.IsTraceEnabled)
                {
                    LOG.Trace("Started MessageQueueTransaction for queue = [" + mq.Path + "]");
                }

                #endregion

                Message message;

                #region ReceiveMessage

                try
                {
                    #region Logging

                    if (LOG.IsTraceEnabled)
                    {
                        LOG.Trace("Receiving message with zero timeout for queue = [" + mq.Path + "]");
                    }

                    #endregion

                    message = mq.Receive(TimeSpan.Zero, messageQueueTransaction);
                }
                catch (MessageQueueException ex)
                {
                    if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                    {
                        //expected to occur occasionally

                        #region Logging

                        if (LOG.IsTraceEnabled)
                        {
                            LOG.Trace(
                                "MessageQueueErrorCode.IOTimeout: No message available to receive.  May have been processed by another thread.");
                        }

                        #endregion

                        status.SetRollbackOnly();
                        return(false); // no more peeking unless this is the last listener thread
                    }
                    else
                    {
                        // A real issue in receiving the message

                        #region Logging

                        if (LOG.IsErrorEnabled)
                        {
                            LOG.Error("Error receiving message from DefaultMessageQueue [" + mq.Path +
                                      "], closing queue and clearing connection cache.");
                        }

                        #endregion

                        lock (messageQueueMonitor)
                        {
                            mq.Close();
                            MessageQueue.ClearConnectionCache();
                        }
                        throw; // will cause rollback in surrounding platform transaction manager and log exception
                    }
                }

                #endregion

                if (message == null)
                {
                    #region Logging

                    if (LOG.IsTraceEnabled)
                    {
                        LOG.Trace("Message recieved is null from Queue = [" + mq.Path + "]");
                    }

                    #endregion

                    status.SetRollbackOnly();
                    return(false); // no more peeking unless this is the last listener thread
                }

                try
                {
                    #region Logging

                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug("Received message [" + message.Id + "] on queue [" + mq.Path + "]");
                    }

                    #endregion

                    MessageReceived(message);

                    if (ExposeContainerManagedMessageQueueTransaction)
                    {
                        TransactionSynchronizationManager.BindResource(
                            MessageQueueTransactionManager.CURRENT_TRANSACTION_SLOTNAME,
                            new LocallyExposedMessageQueueResourceHolder(messageQueueTransaction));
                    }

                    DoExecuteListener(message);

                    #region Logging

                    if (LOG.IsTraceEnabled)
                    {
                        LOG.Trace("MessageListener executed");
                    }

                    #endregion

                    messageQueueTransaction.Commit();

                    #region Logging

                    if (LOG.IsTraceEnabled)
                    {
                        LOG.Trace("Committed MessageQueueTransaction for queue [" + mq.Path + "]");
                    }

                    #endregion
                }
                catch (Exception ex)
                {
                    TransactionAction action =
                        HandleTransactionalListenerException(ex, message, messageQueueTransaction);
                    if (action == TransactionAction.Rollback)
                    {
                        messageQueueTransaction.Abort();

                        #region Logging

                        if (LOG.IsDebugEnabled)
                        {
                            LOG.Debug(
                                "Exception handler's TransactionAction has rolled back MessageQueueTransaction for queue [" +
                                mq.Path + "]");
                        }

                        #endregion
                    }
                    else
                    {
                        // Will remove from the message queue
                        messageQueueTransaction.Commit();

                        #region Logging

                        if (LOG.IsDebugEnabled)
                        {
                            LOG.Debug(
                                "Exception handler's TransactionAction has committed MessageQueueTransaction for queue [" +
                                mq.Path + "]");
                        }

                        #endregion
                    }
                    //Outer db-tx will rollback
                    throw;
                }
                finally
                {
                    if (ExposeContainerManagedMessageQueueTransaction)
                    {
                        TransactionSynchronizationManager.UnbindResource(
                            MessageQueueTransactionManager.CURRENT_TRANSACTION_SLOTNAME);
                    }
                    message.Dispose();
                }
                return(true);
            }
        }
        /// <summary>
        /// Does the recieve and execute using message queue transaction manager.
        /// </summary>
        /// <param name="mq">The message queue.</param>
        /// <param name="status">The transactional status.</param>
        /// <returns>true if should continue peeking, false otherise</returns>
        protected virtual bool DoRecieveAndExecuteUsingMessageQueueTransactionManager(MessageQueue mq,
                                                                                      ITransactionStatus status)
        {
            #region Logging

            if (LOG.IsDebugEnabled)
            {
                LOG.Debug("Executing DoRecieveAndExecuteUsingMessageQueueTransactionManager");
            }

            #endregion Logging

            Message message;

            #region Receive message

            try
            {
                message = mq.Receive(TimeSpan.Zero, QueueUtils.GetMessageQueueTransaction(null));
            }
            catch (MessageQueueException ex)
            {
                if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    //expected to occur occasionally
                    if (LOG.IsTraceEnabled)
                    {
                        LOG.Trace("IOTimeout: Message to receive was already processed by another thread.");
                    }
                    status.SetRollbackOnly();
                    return(false); // no more peeking unless this is the last listener thread
                }
                else
                {
                    // A real issue in receiving the message

                    #region Logging

                    if (LOG.IsErrorEnabled)
                    {
                        LOG.Error("Error receiving message from DefaultMessageQueue [" + mq.Path +
                                  "], closing queue and clearing connection cache.");
                    }

                    #endregion

                    lock (messageQueueMonitor)
                    {
                        mq.Close();
                        MessageQueue.ClearConnectionCache();
                    }
                    throw; // will cause rollback in MessageQueueTransactionManager and log exception
                }
            }

            #endregion

            if (message == null)
            {
                #region Logging

                if (LOG.IsTraceEnabled)
                {
                    LOG.Trace("Message recieved is null from Queue = [" + mq.Path + "]");
                }

                #endregion

                status.SetRollbackOnly();
                return(false); // no more peeking unless this is the last listener thread
            }

            try
            {
                #region Logging

                if (LOG.IsDebugEnabled)
                {
                    LOG.Debug("Received message [" + message.Id + "] on queue [" + mq.Path + "]");
                }

                #endregion

                MessageReceived(message);
                DoExecuteListener(message);

                #region Logging

                if (LOG.IsTraceEnabled)
                {
                    LOG.Trace("MessageListener executed");
                }

                #endregion
            }
            catch (Exception ex)
            {
                //Exception may indicate rollback of database transaction in service layer.
                //Let the handler determine if the message should be removed from the queue.
                TransactionAction action =
                    HandleTransactionalListenerException(ex, message, QueueUtils.GetMessageQueueTransaction(null));
                if (action == TransactionAction.Rollback)
                {
                    #region Logging

                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug(
                            "Exception handler's TransactionAction has rolled back MessageQueueTransaction for queue [" +
                            mq.Path + "]");
                    }

                    #endregion

                    status.SetRollbackOnly();
                    return(false); // no more peeking unless this is the last listener thread
                }
                else
                {
                    LOG.Info("Committing MessageQueueTransaction due to explicit commit request by exception handler.");
                }
            }
            finally
            {
                message.Dispose();
            }
            return(true);
        }
Beispiel #31
0
 internal static string GetHttpMethod(TransactionAction transactionAction)
 {
     switch (transactionAction)
     {
         case TransactionAction.Created:
             return "POST";
         case TransactionAction.Updated:
             return "PUT";
         case TransactionAction.Deleted:
             return "DELETE";
     }
     return "";
 }
Beispiel #32
0
		private void OnTransactionClosed (DesignerHostTransaction raiser, TransactionAction action)
		{
			bool commit = false;
			bool lastTransaction = false;

			if (_transactions.Peek () != raiser)
				throw new InvalidOperationException ("Current transaction differs from the one a commit was requested for.");

			if (_transactions.Count == 1)
				lastTransaction = true;
			if (action == TransactionAction.Commit)
				commit = true;

			_transactions.Pop ();

			if (TransactionClosed != null)
				TransactionClosed (this, new DesignerTransactionCloseEventArgs (commit, lastTransaction));
		}
Beispiel #33
0
        /// <inheritdoc/>
        public async ValueTask <int> UpdateMessageAttemptCount(IStorageTransaction storageTrans, long transId, TransactionAction transactionAction, MessageState messageState)
        {
            const string sql = "Update messages set attempts = attempts + 1 " +
                               "where transaction_id = @TransId AND transaction_action = @TransactionAction AND state = @MessageState;";
            var sqliteConnection = storageTrans.NpgsqlTransaction().Connection;

            return(await this.ExecuteAsync <int>(
                       async (connection) =>
            {
                return await connection.ExecuteAsync(
                    sql,
                    transaction: (storageTrans as DbTransaction)?.NpgsqlTransaction,
                    param: new
                {
                    TransId = transId,
                    TransactionAction = transactionAction,
                    MessageState = messageState
                });
            },
                       sqliteConnection));
        }
Beispiel #34
0
        /// <inheritdoc/>
        public async ValueTask <int> UpdateMessages(IStorageTransaction storageTrans, long transId, TransactionAction transactionAction, MessageState oldMessageState, MessageState newMessageState, DateTime?closeDateTime)
        {
            const string sql = "Update messages set transaction_id = null, transaction_action = 0,  " +
                               "state = @NewMessageState, close_datetime = @CloseDateTime " +
                               "where transaction_id = @TransId AND transaction_action = @TransactionAction AND state = @OldMessageState;";
            var sqliteConnection = storageTrans.NpgsqlTransaction().Connection;

            return(await this.ExecuteAsync <int>(
                       async (connection) =>
            {
                return await connection.ExecuteAsync(
                    sql,
                    transaction: (storageTrans as DbTransaction)?.NpgsqlTransaction,
                    param: new
                {
                    TransId = transId,
                    TransactionAction = transactionAction,
                    OldMessageState = oldMessageState,
                    NewMessageState = newMessageState,
                    CloseDateTime = closeDateTime
                });
            },
                       sqliteConnection));
        }
Beispiel #35
0
 public static HttpStatusCode GetHttpStatus(TransactionStatus transactionStatus, TransactionAction transactionAction)
 {
     switch (transactionStatus)
     {
         case TransactionStatus.Success:
             //switch (transactionAction)
             //{
             //    case TransactionAction.Created:
             //        return HttpStatusCode.Created;
             //    case TransactionAction.Updated:
             //        return HttpStatusCode.Accepted;
             //    case TransactionAction.Deleted:
             //        return HttpStatusCode.Accepted;
             //}
             return HttpStatusCode.OK;
             //break;
     }
     return HttpStatusCode.Conflict;
 }