/// <summary>
        /// Handlers for the ComboBox class of controls.
        /// </summary>
        /// <param name="sender">The object that originated the event.</param>
        /// <param name="routedEventArgs">The routed event arguments.</param>
        private void OnSelectorSelectionChanged(object sender, RoutedEventArgs routedEventArgs)
        {
            // The main idea of this handler is to sort out the user generated actions from the machine generated actions.  Once
            // its determined that it was a user action, a background thread is called to change the associated field to the value
            // selected by the ComboBox.
            SelectionChangedEventArgs selectionChangedEventArgs = routedEventArgs as SelectionChangedEventArgs;

            // Handle changes to ComboBox elements.
            if (selectionChangedEventArgs.OriginalSource is ComboBox)
            {
                ComboBox comboBox = selectionChangedEventArgs.OriginalSource as ComboBox;
                IContent iContent = comboBox.DataContext as IContent;

                // This filters all the ComboBox events looking for user initiated actions that are bound to the data model.
                if (InputHelper.IsUserInitiated(comboBox, ComboBox.SelectedValueProperty) &&
                    iContent != null && iContent.Key is DataTableCoordinate)
                {
                    // At this point, a ComboBox was modified by the user and it is connected to a data model field.  This will extract
                    // the coordinates of the field in the table.  That, in turn, drives the decision about how to update the shared
                    // data model.
                    DataTableCoordinate dataTableCoordiante = iContent.Key as DataTableCoordinate;
                    ExecutionRow        executionRow        = dataTableCoordiante.DataRow as ExecutionRow;
                }
            }
        }
Esempio n. 2
0
        // exemplo: w1(x)-r2(y)-w2(y)-c2-w1(y)
        public void History(string entryTransaction, TextBox output, TextBox RunningRow, TextBox WaitingTransaction, TextBox AbortedTransaction, TextBox Queue, TextBox DataLock)
        {
            string[] transactionList;

            // Quebra a string de entrada em um vetor de string
            transactionList = entryTransaction.Split('-');
            OutPut          = output;

            if (ExecutionRow == null)
            {
                ExecutionRow = new Queue <string>(transactionList);
            }

            if (ExecutionRow.Count > 0)
            {
                RunCommand(ExecutionRow.Dequeue());
                CheckWaitingQueue();
                RunningRow.Text         = RetornaRunningRow();
                WaitingTransaction.Text = ReturnWaitingTransactions();
                AbortedTransaction.Text = ReturnTransactionsAborteds();
                Queue.Text    = ReturnQueue();
                DataLock.Text = ReturnDataLock();
                SetFinalPoint(OutPut);
                RunningRow.Refresh();
                WaitingTransaction.Refresh();
                AbortedTransaction.Refresh();
                DataLock.Refresh();
                SetFinalPoint(Queue);
            }
            else
            {
                OutPut.Text += "\r\nExecução finalizada.";
                SetFinalPoint(OutPut);
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            [Table("executionsTable", Connection = "StorageAccount")] ICollector <ExecutionRow> outputTable,
            ILogger log)
        {
            log.LogInformation($"{FunctionNames.MortgageCalculatorFunction} start");

            // Retrieve loan, interest and numberOfPayments from HTTP Request
            #region [ Retrieve request parameters ]
            decimal loan;
            if (!GetLoanFromQueryString(req, out loan))
            {
                log.LogError($"Loan not valid");
                return(new BadRequestObjectResult("Loan not valid"));
            }

            double interest;
            if (!GetInterestFromQueryString(req, out interest))
            {
                log.LogError($"Annual Interest not valid");
                return(new BadRequestObjectResult("Annual Interest not valid"));
            }

            uint nPayments;
            if (!GetNumberOfPaymentsFromQueryString(req, out nPayments))
            {
                log.LogError($"Number of payments not valid");
                return(new BadRequestObjectResult("Number of payments not valid"));
            }
            #endregion [ Retrieve request parameters ]

            var calculatorResult =
                await mortgageCalculator.CalculateMontlyRateAsync(loan, interest, nPayments);

            #region [ Create the response ]
            var executionRow = new ExecutionRow(DateTime.Now)
            {
                AnnualInterest   = interest,
                ErrorCode        = calculatorResult.Error?.Code,
                MonthlyRate      = calculatorResult.Result,
                MortgageLoan     = loan,
                NumberOfPayments = nPayments,
                Result           = calculatorResult.Succeed
            };

            outputTable.Add(executionRow);
            #endregion [ Create the response ]

            if (calculatorResult.Succeed)
            {
                return(new OkObjectResult(calculatorResult.Result));
            }

            return(new BadRequestObjectResult(calculatorResult.Error.Message));
        }
        /// <summary>
        /// Handlers for the Toggle button class of controls.
        /// </summary>
        /// <param name="sender">The object that originated the event.</param>
        /// <param name="routedEventArgs">The routed event arguments.</param>
        private void OnToggleButtonChange(object sender, RoutedEventArgs routedEventArgs)
        {
            // The main idea of this handler is to sort out the user generated actions from the machine generated actions.  Once
            // its determined that it was a user action, a background thread is called to change the associated field to the value
            // selected by the ToggleButton.
            ToggleButton toggleButton = routedEventArgs.OriginalSource as ToggleButton;
            IContent     iContent     = toggleButton.DataContext as IContent;

            // This filters all the ToggleButton events looking for user initiated actions that are bound to the data model.
            if (InputHelper.IsUserInitiated(toggleButton, ToggleButton.IsCheckedProperty) &&
                iContent != null && iContent.Key is DataTableCoordinate)
            {
                // At this point, a ToggleButton was modified by the user and it is connected to a data model field.  This will
                // extract the coordinates of the field in the table.  That, in turn, drives the decision about how to update the
                // shared data model.
                DataTableCoordinate dataTableCoordiante = iContent.Key as DataTableCoordinate;
                ExecutionRow        executionRow        = dataTableCoordiante.DataRow as ExecutionRow;
            }
        }
Esempio n. 5
0
        private void CheckWaitingQueue()
        {
            // Analisa primeiro comando de cada transação.
            List <int> excludes = new List <int>();

            foreach (var TransactionNumber in WaitingTransactionsList.Keys)
            {
                TransactionQueueCommand commandsTransactions = WaitingTransactionsList[TransactionNumber];
                if (!commandsTransactions.Transaction.LockType.Equals(TransactionTypeLock.Aborted))
                {
                    string       firstCommand = commandsTransactions.CheckCommand();
                    LockDataType LockDataType = ReturnLockType(firstCommand.Substring(0, 1));

                    FreeData freeData = ReturnFreeData(commandsTransactions.Transaction, LockDataType, commandsTransactions.WaitingData);

                    // Se o dado estiver disponivel remove todos os dados da fila e adiciona novamente à fila de execução
                    int    RemovedTransaction = 0;
                    string ciclo   = "";
                    string retorno = "";
                    switch (freeData)
                    {
                    case FreeData.FreeData:
                    case FreeData.SharedTransactionsData:
                    case FreeData.OtherSharedTransactionsData:

                        Queue <string> tempQueue = new Queue <string>();

                        // Remove tudo que está na fila de execução para adicionar a fila de espera na frente
                        while (ExecutionRow.Count > 0)
                        {
                            tempQueue.Enqueue(ExecutionRow.Dequeue());
                        }

                        while (commandsTransactions.QueueCommands.Count > 0)
                        {
                            AddOutPut("Comando: " + commandsTransactions.CheckCommand() + " adicionado à fila de execução.");
                            ExecutionRow.Enqueue(commandsTransactions.RemoveCommand());
                        }

                        // Adiciona os commandos de volta a fila de execução
                        while (tempQueue.Count > 0)
                        {
                            ExecutionRow.Enqueue(tempQueue.Dequeue());
                        }

                        commandsTransactions.Transaction.LockType = TransactionTypeLock.Executing;

                        // Adiciona à lista de excluídos para remover no final
                        excludes.Add(TransactionNumber);
                        break;

                    case FreeData.ExclusiveOtherTransactionsData:

                        // Realiza validação para analisar se a transação entrou em deadlock
                        retorno            = CheckDeadLock(TransactionNumber, commandsTransactions.WaitingData);
                        RemovedTransaction = int.Parse(retorno.Substring(0, retorno.IndexOf("|")));

                        ciclo = retorno.Substring(retorno.IndexOf("|") + 1);
                        if (RemovedTransaction > -1)
                        {
                            excludes.Add(RemovedTransaction);
                            // Desaloca dados da transação.
                            string       msg          = "";
                            Transactions Transactions = TransactionsList[RemovedTransaction];

                            // Realiza unlock do dado e retira da lista de dados utilizados.
                            string[] usedData = Transactions.ReturnDataUsed();
                            msg  = "----------- DEAD LOCK ----------- " + "\r\n";
                            msg += ciclo + "\r\n";
                            msg += "Transação " + RemovedTransaction + " eliminada, pois foi a que executou menos comandos.\r\n";
                            AddOutPut(msg);
                            foreach (var dado in usedData)
                            {
                                // Adiciona saída unclok para dados liberados
                                AddOutPut(CreateLock(LockDataType.Unlock, Transactions.TransactionNumber, dado, Transactions.ReturnDataLockType(dado)));
                                // Remove dado e transação da lista de dados locks
                                RemoveDataLocksList(Transactions, dado);
                                // Remove dado da lista de transações
                                Transactions.RemoveData(dado);
                            }
                            Transactions.LockType = TransactionTypeLock.Aborted;
                        }
                        break;
                    }
                }
            }

            foreach (var transactionNumber in excludes)
            {
                WaitingTransactionsList.Remove(transactionNumber);
            }
        }
 private bool FilterBlotters(ExecutionRow executionRow)
 {
     return(this.blotterList.BinarySearch(executionRow.BlotterId) >= 0);
 }
 private Schema.Execution.Execution MatchSelector(ExecutionRow executionRow)
 {
     Schema.Execution.Execution match = new Schema.Execution.Execution();
     return(match.Select(executionRow));
 }
Esempio n. 8
0
        /// <summary>
        /// Handler for validating Execution records.
        /// </summary>
        /// <param name="sender">The object that originated the event.</param>
        /// <param name="e">The event arguments.</param>
        internal static void OnExecutionRowValidate(object sender, ExecutionRowChangeEventArgs e)
        {
            DestinationOrderRow  destinationOrderRow;
            Decimal              executedQuantity;
            DataModelTransaction dataModelTransaction;
            Decimal              orderedQuantity;

            // The Business Rules will be enforced on this Execution.  Note that it is locked at the point this handler is called.
            ExecutionRow executionRow = e.Row;

            // The action on the row determines which rule to evaluate.
            switch (e.Action)
            {
            case DataRowAction.Add:

                // This rule will update the status of the owning Destination Order based on the quantity executed.
                dataModelTransaction = DataModelTransaction.Current;

                // The aggregate of the quantities executed will determine whether the Destination Order requires a status change.
                destinationOrderRow = executionRow.DestinationOrderRow;
                destinationOrderRow.AcquireReaderLock(dataModelTransaction);
                if (destinationOrderRow.RowState == DataRowState.Detached)
                {
                    return;
                }

                // This calculates the quantity outstanding on an order and the quantity executed on the order.
                orderedQuantity  = destinationOrderRow.OrderedQuantity - destinationOrderRow.CanceledQuantity;
                executedQuantity = 0.0M;
                foreach (ExecutionRow siblingRow in destinationOrderRow.GetExecutionRows())
                {
                    siblingRow.AcquireReaderLock(dataModelTransaction);
                    executedQuantity += siblingRow.ExecutionQuantity;
                }

                // This rule will set the status on the owning Destination Order based on the amont outstanding and the amount ordered.  First, if the quantity
                // executed is greater than the quantity ordered, the Order goes into an error state.  We can't reject executions as they come from an external
                // source, but the order can be flag and put into an error state.
                if (executedQuantity > orderedQuantity)
                {
                    if (destinationOrderRow.StatusId != StatusMap.FromCode(Status.Error))
                    {
                        UpdateDestinationOrderStatus(destinationOrderRow, Status.Error);
                    }
                }
                else
                {
                    // When the total quantity executed is reduced to zero then the order goes back into the initial state.
                    if (executedQuantity == 0.0m)
                    {
                        if (destinationOrderRow.StatusId != StatusMap.FromCode(Status.New))
                        {
                            UpdateDestinationOrderStatus(destinationOrderRow, Status.New);
                        }
                    }
                    else
                    {
                        // While the executed quantity is still less than the outstanding quantity the order is consdered to be partially filled.  Otherwise,
                        // the order is completely filled.
                        if (executedQuantity < orderedQuantity)
                        {
                            if (destinationOrderRow.StatusId != StatusMap.FromCode(Status.PartiallyFilled))
                            {
                                UpdateDestinationOrderStatus(destinationOrderRow, Status.PartiallyFilled);
                            }
                        }
                        else
                        {
                            if (destinationOrderRow.StatusId != StatusMap.FromCode(Status.Filled))
                            {
                                UpdateDestinationOrderStatus(destinationOrderRow, Status.Filled);
                            }
                        }
                    }
                }

                break;

            case DataRowAction.Delete:

                // A middle tier context is required to lock the rows so the quantities can be aggregated.
                dataModelTransaction = DataModelTransaction.Current;

                // The aggregate of the quantities executed will determine whether the Destination Order requires a status change.
                destinationOrderRow = (DestinationOrderRow)executionRow.GetParentRow(
                    DataModel.Execution.DestinationOrderExecutionRelation,
                    DataRowVersion.Original);
                destinationOrderRow.AcquireReaderLock(dataModelTransaction);
                if (destinationOrderRow.RowState == DataRowState.Detached)
                {
                    return;
                }

                // This calculates the quantity outstanding on an order and the quantity executed on the order.
                orderedQuantity  = destinationOrderRow.OrderedQuantity - destinationOrderRow.CanceledQuantity;
                executedQuantity = 0.0M;
                foreach (ExecutionRow siblingRow in destinationOrderRow.GetExecutionRows())
                {
                    siblingRow.AcquireReaderLock(dataModelTransaction);
                    executedQuantity += siblingRow.ExecutionQuantity;
                }

                // When the total quantity executed is reduced to zero then the order goes back into the initial state.  Note that it is impossible for the
                // order to transition into a error state by deleting an execution.
                if (executedQuantity == 0.0m)
                {
                    if (destinationOrderRow.StatusId != StatusMap.FromCode(Status.New))
                    {
                        UpdateDestinationOrderStatus(destinationOrderRow, Status.New);
                    }
                }
                else
                {
                    // While the executed quantity is still less than the outstanding quantity the order is consdered to be partially filled.  Note that it is
                    // impossible for the order to transition to a filled state by deleting an execution.
                    if (executedQuantity < orderedQuantity)
                    {
                        if (destinationOrderRow.StatusId != StatusMap.FromCode(Status.PartiallyFilled))
                        {
                            UpdateDestinationOrderStatus(destinationOrderRow, Status.PartiallyFilled);
                        }
                    }
                }

                break;
            }
        }