Beispiel #1
0
        public void CalculateTransactionsTestThrowsNullReferenceException186()
        {
            List <Transaction> list;
            string             s;

            Transaction[] transactions = new Transaction[1];
            Transaction   s0           = new Transaction();

            s0.Amount          = 0L;
            s0.IsPending       = false;
            s0.AggregationTime = (string)null;
            s0.AccountId       = (string)null;
            s0.ClearDate       = 0L;
            s0.TransactionId   = (string)null;
            s0.RawMerchant     = (string)null;
            s0.Categorization  = (string)null;
            s0.Merchant        = (string)null;
            s0.TransactionTime = default(DateTime);
            transactions[0]    = s0;
            list = new List <Transaction>((IEnumerable <Transaction>)transactions);
            Process s1 = new Process();
            TransactionCollection s2 = new TransactionCollection();

            s2.Error        = (string)null;
            s2.Transactions = list;
            s = this.CalculateTransactionsTest(s1, s2);
        }
 public TransactionCollection FetchAll()
 {
     TransactionCollection coll = new TransactionCollection();
     Query qry = new Query(Transaction.Schema);
     coll.LoadAndCloseReader(qry.ExecuteReader());
     return coll;
 }
Beispiel #3
0
        private async Task <MongoDbTransaction> GetLastTransactionInternal()
        {
            // look for potential last transaction
            var res = await TransactionCollection.Find(x => true)
                      .SortByDescending(x => x.Timestamp)
                      .FirstOrDefaultAsync();

            if (res == null)
            {
                return(null);
            }

            // look if a pending transaction
            var resp = await PendingTransactionCollection.Find(x => true).SortByDescending(x => x.Timestamp).FirstOrDefaultAsync();

            if (resp == null) // no pending transaction
            {
                // return last transaction
                return(res);
            }
            else
            {
                // else return last transaction no younger than pending transaction
                res = await TransactionCollection.Find(x => x.Timestamp < resp.Timestamp)
                      .SortByDescending(x => x.Timestamp)
                      .FirstOrDefaultAsync();

                return(res);
            }
        }
Beispiel #4
0
        public int FbExecuteNonQuery(TransactionCollection command)
        {
            var rowAffect = 0;

            try
            {
                OpenFbData();

                foreach (Transaction t in command)
                {
                    Com = GetCommandDb(t.SqlCommand, t.ExecuteType);

                    if (t.Parameter != null)
                    {
                        SetParameter(t.Parameter, ref Com);
                    }

                    rowAffect += Com.ExecuteNonQuery();
                }
            }
            finally
            {
                ReleaseResource();
            }

            return(rowAffect);
        }
        public async Task <ByteString> GetTransaction(ByteString mutationHash)
        {
            var key = mutationHash.ToByteArray();
            var res = await TransactionCollection.Find(x => x.MutationHash == key).SingleOrDefaultAsync();

            return(res == null ? null : new ByteString(res.RawData));
        }
        public async Task <TransactionCollection> GetExpensesByCriteria(SearchCriteria criteria)
        {
            var result = new TransactionCollection();

            var qry = _dbset.Where(e => DbFunctions.TruncateTime(e.Date) >= DbFunctions.TruncateTime(criteria.DateFrom) &&
                                   DbFunctions.TruncateTime(e.Date) <= DbFunctions.TruncateTime(criteria.DateTo));

            if (criteria.MinAmount.HasValue)
            {
                qry = qry.Where(o => o.Amount >= criteria.MinAmount);
            }
            if (criteria.MaxAmount.HasValue)
            {
                qry = qry.Where(o => o.Amount <= criteria.MaxAmount);
            }

            result.Categories = _mapperService.Map <IEnumerable <Category> >(await qry.Select(o => o.Category).Distinct().ToListAsync());

            if (criteria.CategoryIDs.Any())
            {
                qry = qry.Where(o => criteria.CategoryIDs.Contains(o.CategoryId));
            }
            if (!string.IsNullOrEmpty(criteria.SortBy))
            {
                qry = qry.OrderBy(criteria.SortBy + (criteria.SortAsc == true ? " ascending" : " descending"));
            }
            if (criteria.Skip.HasValue && criteria.Take.HasValue)
            {
                qry = qry.Skip(criteria.Skip.Value).Take(criteria.Take.Value);
            }

            result.Transactions = _mapperService.Map <IEnumerable <Transaction> >(await qry.Include(e => e.Category).ToListAsync());
            return(result);
        }
Beispiel #7
0
        public string GetCreditCardTransactions(TransactionCollection transactions)
        {
            string returnValue = string.Empty;

            if (transactions != null && transactions.Transactions != null && transactions.Transactions.Count > 0)
            {
                StringBuilder messageBuilder = new StringBuilder();
                var           ccPayments     = from cParent in transactions.Transactions
                                               join cChild in transactions.Transactions
                                               on cParent.TransactionTime.ToString(Constants.MonthYearFormat) equals cChild.TransactionTime.ToString(Constants.MonthYearFormat)

                                                   where
                                               cParent.TransactionId != cChild.TransactionId &&
                                               cParent.Amount == -1 * cChild.Amount &&
                                               cParent.TransactionTime.Subtract(cChild.TransactionTime).Hours < 24
                                               //&& cParent.TransactionTime.ToString(Constants.MonthYearFormat) == "2014-11"
                                               select cParent;

                string print = "Credit Card Payments";
                messageBuilder.AppendLine();
                messageBuilder.AppendLine(print);
                messageBuilder.AppendLine(new string('-', print.Length * 2) + "\n");
                CultureInfo culture = this.GetCultureInfoForNegativePattern();

                messageBuilder.Append("{");
                foreach (var ccPayment in ccPayments)
                {
                    messageBuilder.AppendLine(string.Format(culture, @"""{0}"":{{""Merchant"":""{1}"",""Amount"":""{2:C}""}}", ccPayment.TransactionTime.ToString(Constants.MonthYearFormat), ccPayment.Merchant, ccPayment.Amount));
                }
                messageBuilder.Append("}");
                returnValue = messageBuilder.ToString();
            }
            return(returnValue);
        }
        private string PrintTransactions(bool detailedView)
        {
            if (selectedCustomer.Transactions.Count == 0)
            {
                return("<none>");
            }

            StringBuilder         display      = new StringBuilder(1000);
            TransactionCollection transactions = selectedCustomer.Transactions;

            foreach (Transaction transaction in transactions)
            {
                display.Append(transaction.Timestamp.ToString("yyyy-MM-dd"));

                display.AppendFormat("  {0}", transaction.Name);
                if (transaction.Status == Transaction.TransactionStatus.Pending)
                {
                    display.Append(" [Pending]");
                }
                if (detailedView)
                {
                    display.Append("\r\n");
                    AppendDetails(display, transaction);
                }
                display.Append("\r\n");
                display.Append("\r\n");
            }
            return(display.ToString());
        }
Beispiel #9
0
        public async Task <IReadOnlyList <ByteString> > GetTransactions(ByteString from)
        {
            // find last transaction to return
            var resl = await GetLastTransactionInternal();

            if (resl == null)
            {
                return(new List <ByteString>().AsReadOnly());
            }

            // find first transaction to return
            MongoDbTransaction resf = null;

            if (from != null)
            {
                var cmpkey = from.ToByteArray();
                resf = await TransactionCollection.Find(x => x.TransactionHash == cmpkey).FirstOrDefaultAsync();
            }

            List <MongoDbTransaction> l;

            if (resf == null)
            {
                l = await TransactionCollection.Find(x => x.Timestamp <= resl.Timestamp).SortBy(x => x.Timestamp).ToListAsync();
            }
            else
            {
                l = await TransactionCollection.Find(x => x.Timestamp > resf.Timestamp && x.Timestamp <= resl.Timestamp)
                    .SortBy(x => x.Timestamp).ToListAsync();
            }

            return(l.Select(x => new ByteString(x.RawData)).ToList().AsReadOnly());
        }
Beispiel #10
0
        private async void button1_Click(object sender, EventArgs e)
        {
            //The below commented code is the calling code for API for some reason I could not able to call and getting the below error
            //Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host
            //I decide to get the data from https://2016.api.levelmoney.com/ and store them locally in json file and query the data

            //HttpClient client = new HttpClient();
            //client.BaseAddress = new Uri("https://2016.api.levelmoney.com/");
            //client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //HttpResponseMessage response = client.GetAsync("/api/v2/core/get-all-transactions/?uid=1110590645&token=2B5075227E074DECE543EB29AA60A9D4&api-toke=AppTokenForInterview").Result;
            //TransactionCollection transactions = await response.Content.ReadAsAsync<TransactionCollection>();


            TransactionCollection transactions = null;

            //Loading json data to transaction collection
            using (StreamReader stream = new StreamReader(Path.Combine(Application.StartupPath, "TransactionData.json")))
            {
                transactions = (TransactionCollection)JsonConvert.DeserializeObject(stream.ReadToEnd(), typeof(TransactionCollection));
            }

            Process process = new Process();

            if (transactions != null && transactions.Transactions != null && transactions.Transactions.Count > 0)
            {
                richTextBox1.Text  = process.CalculateTransactions(transactions);
                richTextBox1.Text += process.GetCreditCardTransactions(transactions);
            }
            else
            {
                richTextBox1.Text = "No Records to process";
            }
        }
Beispiel #11
0
        private Account BuildAccount(Guid accountId)
        {
            var customerId = Guid.NewGuid();
            TransactionCollection transactions = BuildTransactions(accountId);

            return(Account.Load(accountId, customerId, transactions));
        }
        public TransactionEditor()
        {
            Transactions   = new TransactionCollection();
            UsePreCloseDay = true;

            InitializeComponent();
        }
        public TransactionEditor()
        {
            Transactions = new TransactionCollection();
            UsePreCloseDay = true;

            InitializeComponent();
        }
 /// <summary>
 /// Fetch by order id.
 /// </summary>
 /// <param name="orderId">The order id.</param>
 /// <returns></returns>
 public TransactionCollection FetchByOrderId(int orderId)
 {
     IDataReader reader = SPs.FetchAssociatedOrderTransactions(orderId).GetReader();
       TransactionCollection transactionCollection = new TransactionCollection();
       transactionCollection.LoadAndCloseReader(reader);
       transactionCollection.Sort(Transaction.Columns.TransactionDate, true);
       return transactionCollection;
 }
Beispiel #15
0
        private Account BuildAccount(double creditAmount)
        {
            var accountId  = Guid.NewGuid();
            var customerId = Guid.NewGuid();
            TransactionCollection transactions = BuildTransactions(accountId, creditAmount);

            return(Account.Load(accountId, customerId, transactions));
        }
Beispiel #16
0
        public ProgramView(TransactionCollection collection)
        {
            _collection = collection;
            InitializeComponent();
            InitializeTransactionsView();

            InitializeAddTranasctionView();
            Chart();
        }
        public async Task <AccountResult> GetAccount(Guid accountId)
        {
            using (IDbConnection db = new SqlConnection(_connectionString))
            {
                string           accountSQL = @"SELECT * FROM Account WHERE Id = @accountId";
                Entities.Account account    = await db
                                              .QueryFirstOrDefaultAsync <Entities.Account>(accountSQL, new { accountId });

                if (account == null)
                {
                    return(null);
                }

                string credits =
                    @"SELECT * FROM [Credit]
                      WHERE AccountId = @accountId";

                List <ITransaction> transactionsList = new List <ITransaction>();

                using (var reader = db.ExecuteReader(credits, new { accountId }))
                {
                    var parser = reader.GetRowParser <Credit>();

                    while (reader.Read())
                    {
                        ITransaction transaction = parser(reader);
                        transactionsList.Add(transaction);
                    }
                }

                string debits =
                    @"SELECT * FROM [Debit]
                      WHERE AccountId = @accountId";

                using (var reader = db.ExecuteReader(debits, new { accountId }))
                {
                    var parser = reader.GetRowParser <Debit>();

                    while (reader.Read())
                    {
                        ITransaction transaction = parser(reader);
                        transactionsList.Add(transaction);
                    }
                }

                TransactionCollection transactionCollection = new TransactionCollection();

                foreach (var item in transactionsList.OrderBy(e => e.TransactionDate))
                {
                    transactionCollection.Add(item);
                }

                Account       result        = Account.Load(account.Id, account.CustomerId, transactionCollection);
                AccountResult accountResult = new AccountResult(result);
                return(accountResult);
            }
        }
        public string CalculateTransactionsTest(
            [PexAssumeUnderTest] Process target,
            TransactionCollection transactions
            )
        {
            string result = target.CalculateTransactions(transactions);

            return(result);
            // TODO: add assertions to method ProcessTest.CalculateTransactionsTest(Process, TransactionCollection)
        }
        public async Task <IReadOnlyList <ByteString> > GetRecordMutations(ByteString recordKey)
        {
            var key = recordKey.ToByteArray();
            var res = await TransactionCollection.Find(Builders <MongoDbTransaction> .Filter.AnyEq(x => x.Records, key))
                      .Project(x => x.MutationHash)
                      .SortBy(x => x.Timestamp)
                      .ToListAsync();

            return(res.Select(x => new ByteString(x)).ToList().AsReadOnly());
        }
Beispiel #20
0
        /// <summary>
        /// Get all accounts
        /// </summary>
        /// <returns>Collection of accounts</returns>
        public TransactionCollection Get()
        {
            TransactionCollection Transactions = new TransactionCollection();

            foreach (Transaction transaction in DB.Transactions)
            {
                Transactions.Add(transaction);
            }
            return(Transactions);
        }
Beispiel #21
0
        /// <summary>
        /// Metoda uloží kolekce v modelu do XAML souborů (MaterialCollection, EmployeeCollection, ContractCollection, OverviewModel, TransactionCollection, DeletedMaterialCollection, DeletedEmployeeCollection, DeletedContractCollection).
        /// </summary>
        public void Save()
        {
            // K ukládání je využit serializér
            XmlSerializer materialSerializer = new XmlSerializer(MaterialCollection.GetType());

            using (StreamWriter sw = new StreamWriter(materialTrack))
            {
                materialSerializer.Serialize(sw, MaterialCollection);
            }
            XmlSerializer employeeSerializer = new XmlSerializer(EmployeeCollection.GetType());

            using (StreamWriter sw = new StreamWriter(employeeTrack))
            {
                employeeSerializer.Serialize(sw, EmployeeCollection);
            }
            XmlSerializer contractSerializer = new XmlSerializer(ContractCollection.GetType());

            using (StreamWriter sw = new StreamWriter(contractTrack))
            {
                contractSerializer.Serialize(sw, ContractCollection);
            }

            XmlSerializer overviwSerializer = new XmlSerializer(OverviewModel.GetType());

            using (StreamWriter sw = new StreamWriter(overviewTrack))
            {
                overviwSerializer.Serialize(sw, OverviewModel);
            }
            XmlSerializer accountSerializer = new XmlSerializer(TransactionCollection.GetType());

            using (StreamWriter sw = new StreamWriter(transactionTrack))
            {
                accountSerializer.Serialize(sw, TransactionCollection);
            }

            XmlSerializer deletedMaterialSerializer = new XmlSerializer(DeletedMaterialCollection.GetType());

            using (StreamWriter sw = new StreamWriter(deletedMaterialTrack))
            {
                deletedMaterialSerializer.Serialize(sw, DeletedMaterialCollection);
            }
            XmlSerializer deletedEmployeeSerializer = new XmlSerializer(DeletedEmployeeCollection.GetType());

            using (StreamWriter sw = new StreamWriter(deletedEmployeeTrack))
            {
                deletedEmployeeSerializer.Serialize(sw, DeletedEmployeeCollection);
            }
            XmlSerializer deletedContractSerializer = new XmlSerializer(DeletedContractCollection.GetType());

            using (StreamWriter sw = new StreamWriter(deletedContractTrack))
            {
                deletedContractSerializer.Serialize(sw, DeletedContractCollection);
            }
            FillingAllCollections();
        }
        public async Task <AccountResult> GetAccount(Guid accountId)
        {
            Entities.Account account = await _context
                                       .Accounts
                                       .FindAsync(accountId);

            List <Entities.Credit> credits = await _context
                                             .Credits
                                             .Where(e => e.AccountId == accountId)
                                             .ToListAsync();

            List <Entities.Debit> debits = await _context
                                           .Debits
                                           .Where(e => e.AccountId == accountId)
                                           .ToListAsync();

            List <ITransaction> transactions = new List <ITransaction>();

            foreach (Entities.Credit transactionData in credits)
            {
                Credit transaction = Credit.Load(
                    transactionData.Id,
                    transactionData.AccountId,
                    transactionData.Amount,
                    transactionData.TransactionDate);

                transactions.Add(transaction);
            }

            foreach (Entities.Debit transactionData in debits)
            {
                Debit transaction = Debit.Load(
                    transactionData.Id,
                    transactionData.AccountId,
                    transactionData.Amount,
                    transactionData.TransactionDate);

                transactions.Add(transaction);
            }

            var orderedTransactions = transactions.OrderBy(o => o.TransactionDate).ToList();

            TransactionCollection transactionCollection = new TransactionCollection();

            transactionCollection.Add(orderedTransactions);

            Account result = Account.Load(
                account.Id,
                account.CustomerId,
                transactionCollection);

            AccountResult re = new AccountResult(result);

            return(re);
        }
Beispiel #23
0
        private TransactionCollection BuildTransactions(Guid accountId, double creditAmount)
        {
            var transactions = new TransactionCollection();

            var amount = new Amount(creditAmount);
            var credit = new Credit(accountId, amount);

            transactions.Add(credit);

            return(transactions);
        }
        public async Task <Account> Get(Guid id)
        {
            Entities.Account account = await _context
                                       .Accounts
                                       .Find(e => e.Id == id)
                                       .SingleOrDefaultAsync();

            List <Entities.Credit> credits = await _context
                                             .Credits
                                             .Find(e => e.AccountId == id)
                                             .ToListAsync();

            List <Entities.Debit> debits = await _context
                                           .Debits
                                           .Find(e => e.AccountId == id)
                                           .ToListAsync();

            List <ITransaction> transactions = new List <ITransaction>();

            foreach (Entities.Credit transactionData in credits)
            {
                Credit transaction = new Credit(
                    transactionData.Id,
                    transactionData.AccountId,
                    transactionData.Amount,
                    transactionData.TransactionDate);

                transactions.Add(transaction);
            }

            foreach (Entities.Debit transactionData in debits)
            {
                Debit transaction = new Debit(
                    transactionData.Id,
                    transactionData.AccountId,
                    transactionData.Amount,
                    transactionData.TransactionDate);

                transactions.Add(transaction);
            }

            var orderedTransactions = transactions.OrderBy(o => o.TransactionDate).ToList();

            TransactionCollection transactionCollection = new TransactionCollection();

            transactionCollection.Add(orderedTransactions);

            Account result = new Account(
                account.Id,
                account.CustomerId,
                transactionCollection);

            return(result);
        }
Beispiel #25
0
        public TransactionCollection GetTransactions(int transactions)
        {
            var collection = new TransactionCollection();

            for (int i = 0; i < transactions; i++)
            {
                collection.Transactions.Add(GenerateTransaction(i % 2 == 0));
            }

            return(collection);
        }
Beispiel #26
0
		internal void AttachTransactions(TransactionCollection transactions)
		{
			foreach (Transaction transaction in transactions)
			{
				Package package = FindPackageById(transaction.PackageId);
				if (package == null)
					continue;
				package.Transactions.Add(transaction);
				package.TransactionsLoaded = true;
			}
		}
        /************************************************************************/

        #region Constructor (protected)
        /// <summary>
        /// Initializes a new instance of the <see cref="BankStatementBase"/> class.
        /// </summary>
        /// <param name="rootNode">The root node from which to find data for this class.</param>
        protected BankStatementBase(XmlNode rootNode) : base(rootNode)
        {
            if (rootNode != null)
            {
                StartDate    = GetDateTimeValue(rootNode, nameof(StartDate));
                EndDate      = GetDateTimeValue(rootNode, nameof(EndDate));
                Ledger       = new Balance(GetNestedNode(rootNode, GetNodeName(nameof(Ledger))));
                Available    = new Balance(GetNestedNode(rootNode, GetNodeName(nameof(Available))));
                Transactions = new TransactionCollection(GetNestedNode(rootNode, GetNodeName(nameof(Transactions))), this);
            }
        }
Beispiel #28
0
            /// <summary>
            /// Creates an object that commits or rejects several batched operations as a unit.
            /// </summary>
            public Transaction(TransactionCollection transactionCollection)
            {
                // Initialize the object
                this.Index                 = transactionCollection.Count;
                this.Exceptions            = new List <Exception>();
                this.Methods               = new MethodCollection();
                this.transactionCollection = transactionCollection;

                // This transaction is the current transaction.
                this.previousTransaction           = this.transactionCollection.Current;
                this.transactionCollection.current = this;
            }
Beispiel #29
0
 /// <summary>
 /// Metoda odstraní zakázku a pokud byla standartně provedena, vytvoří i novou transakci.
 /// </summary>
 /// <param name="selectedContract">Vybraná zakázka</param>
 /// <param name="workPrice">Cena za provedení zakázky</param>
 /// <param name="changeAccountCollection">Potvrzení, jesti má být vytvořena nová transakce</param>
 public void DeleteContract(Contract selectedContract, double?workPrice, bool changeAccountCollection)
 {
     if (changeAccountCollection)
     {
         TransactionCollection.Add(new Transaction(selectedContract.ContractName.ToString(), Transaction.TransactionType.ContractAdd, (selectedContract.Reward - (double)workPrice)));
     }
     // Smazání zakáky
     ContractCollection.Remove(selectedContract);
     DeletedContractCollection.Add(new Contract(selectedContract.ContractName, selectedContract.SubmitterName, selectedContract.Pieces, selectedContract.Reward, selectedContract.KindMaterials));
     RefreshOverviewFactory();
     Save();
 }
Beispiel #30
0
 private int FindPayPalOrderId(int paypalGatewayId, string transactionId)
 {
     if (!string.IsNullOrEmpty(transactionId))
     {
         TransactionCollection parentTransactions = TransactionDataSource.LoadForProviderTransaction(paypalGatewayId, transactionId);
         if ((parentTransactions != null) && (parentTransactions.Count > 0))
         {
             return(parentTransactions[0].Payment.OrderId);
         }
     }
     return(0);
 }
Beispiel #31
0
        public void CalculateTransactionsTest852()
        {
            string  s;
            Process s0 = new Process();
            TransactionCollection s1 = new TransactionCollection();

            s1.Error        = (string)null;
            s1.Transactions = (List <Transaction>)null;
            s = this.CalculateTransactionsTest(s0, s1);
            Assert.AreEqual <string>("", s);
            Assert.IsNotNull((object)s0);
        }
Beispiel #32
0
        public void Multiple_Transactions_Should_Be_Added()
        {
            TransactionCollection transactionCollection = new TransactionCollection();

            transactionCollection.Add(new List <ITransaction>()
            {
                new Credit(Guid.Empty, 100),
                new Debit(Guid.Empty, 30)
            });

            Assert.Equal(2, transactionCollection.GetTransactions().Count);
        }
Beispiel #33
0
        private void OnSubmitReport(object sender, RoutedEventArgs e)
        {
            DateTime rpt = DateTime.MinValue;

            try
            {
                rpt = DateTime.Parse(ReportDate);
            }
            catch { }
            Transactions = new TransactionCollection();
            Finances     = new FinancialObjectCollection();
            foreach (InventoryTransactionObject tran1 in Cache.Current.ReadyForOpenCartUpdate)
            {
                if (((tran1.TransactionTime.CompareTo(rpt) >= 0 && tran1.TransactionTime.CompareTo(rpt.AddDays(1)) <= 0 || rpt.Year < 2014) && !ShowUnexportedOnly) || (ShowUnexportedOnly && !tran1.ExportedToWeb))
                {
                    Transactions.Add(tran1);
                }
            }
            foreach (FinancialObject fin1 in Cache.Current.CurrentFinancials)
            {
                if (fin1.TransactionDateTime.CompareTo(rpt) >= 0 && fin1.TransactionDateTime.CompareTo(rpt.AddDays(1)) <= 0)
                {
                    Finances.Add(fin1);
                }
            }
            MessageBox.Show("Complete");

            /*
             *
             * foreach (InventoryTransactionObject tran1 in working)
             * {
             *
             *  Cache.Current.ReadyForOpenCartUpdate.Add(tran1);
             *  Cache.Current.InventoryActivity.Remove(tran1);
             * }
             * if (tran != null)
             * {
             *  Cache.Current.ReadyForOpenCartUpdate.Add(tran);
             *  working.Add(tran);
             * }
             * foreach (FinancialObject fin1 in financialList)
             * {
             *  Cache.Current.StagedFinancials.Add(fin1);
             *  Cache.Current.CurrentFinancials.Remove(fin1);
             * }
             * if (fin != null)
             * {
             *  Cache.Current.StagedFinancials.Add(fin);
             *  financialList.Add(fin);
             * }
             * */
        }
Beispiel #34
0
        private async Task RollbackTransaction(byte[] hash)
        {
            // Rollback is idempotent && reentrant : may be call twice even at the same time
            try
            {
#if DEBUG
                Logger.LogDebug($"Rollbacking transaction {new ByteString(hash)}");
#endif
                // get affected records
                var trn = await PendingTransactionCollection.Find(x => x.TransactionHash.Equals(hash)).SingleOrDefaultAsync();

                if (trn != null)
                {
                    // revert records values & version
                    foreach (var r in trn.InitialRecords)
                    {
                        await RecordCollection.FindOneAndUpdateAsync(
                            x => x.Key.Equals(r.Key) && x.TransactionLock.Equals(trn.LockToken),
                            Builders <MongoDbRecord> .Update.Set(x => x.Value, r.Value).Set(x => x.Version, r.Version).Unset(x => x.TransactionLock)
                            );
                    }

                    foreach (var r in trn.AddedRecords)
                    {
                        await RecordCollection.FindOneAndDeleteAsync(
                            x => x.Key.Equals(r) && x.TransactionLock.Equals(trn.LockToken)
                            );
                    }

                    // remove transaction
                    await TransactionCollection.DeleteOneAsync(x => x.TransactionHash.Equals(hash));

                    await RecordCollection.UpdateOneAsync(
                        x => x.TransactionLock == trn.LockToken,
                        Builders <MongoDbRecord> .Update
                        .Unset(x => x.TransactionLock)
                        );

                    // remove pending transaction
                    await PendingTransactionCollection.DeleteOneAsync(x => x.TransactionHash.Equals(hash));

                    Logger.LogInformation($"Transaction {new ByteString(hash)} rollbacked");
                }
            }
            catch (Exception ex)
            {
                var msg = "Error rollbacking transaction : " + new ByteString(hash).ToString();
                Logger.LogCritical(msg, ex);
                throw new Exception(msg, ex);
            }
        }
Beispiel #35
0
        private Cache()
        {
            Inventory = new ActiveInventoryCollection();
            Inventory.Load(InventoryFile);
            InventoryActivity = new TransactionCollection();
            InventoryActivity.Load(InventoryActivityFile);

            ReadyForOpenCartUpdate = new TransactionCollection();
            ReadyForOpenCartUpdate.Load(ReadyToPostFile);

            if (Configuration.Current.FileVersion < Configuration.CurrentFileVersion)
            {
                DoVersionUpdateProcess();
            }

            CurrentFinancials = new FinancialObjectCollection();
            CurrentFinancials.Load(FinancialsFile);


            StagedFinancials = new FinancialObjectCollection();
            StagedFinancials.Load(StagedFinancialsFile);
        }
        protected void gv_Transaction_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
            int id = Convert.ToInt32(gv_Transaction.DataKeys[row.RowIndex].Values[0]);
            string _FromEntityID =gv_Transaction.DataKeys[row.RowIndex].Values[1].ToString();
            string _ToEntityID = gv_Transaction.DataKeys[row.RowIndex].Values[2].ToString();

            using (DataEntryServiceClient _client = new DataEntryServiceClient())
            {
                PeriodServiceClient _pclient = new PeriodServiceClient();
                Period _period = new PeriodCollection(_pclient.GetCurrentPeriod())[0];
                if (e.CommandName.Equals("Btn_Notice"))
                {
                    _client.SetNotices(id, Convert.ToInt32(Session["Userid"]));
                    GetData(_period);

                }
                else if (e.CommandName.Equals("Btn_Confirm"))
                {
                    Transaction _tran = new TransactionCollection(_client.LoadTransactionByID(id))[0];
                    _tran.Updater.UserID = Convert.ToInt32(Session["Userid"]);
                    _tran.Period = _period;
                    _client.SetConfirm(_tran);
                    GetData(_period);

                }
                else if (e.CommandName.Equals("Btn_Edit"))
                {
                    Session["IsAdd"] = false;
                    tx_FromEntity.Text = gv_Transaction.Rows[row.RowIndex].Cells[0].Text ;
                    tx_ToEntity.Text = gv_Transaction.Rows[row.RowIndex].Cells[2].Text;
                    tx_Amount.Text = gv_Transaction.Rows[row.RowIndex].Cells[5].Text;
                    lb_FromEntityID.Text = _FromEntityID;
                    lb_ToEntityID.Text = _ToEntityID;
                    lb_FromCurrency.Text = gv_Transaction.Rows[row.RowIndex].Cells[1].Text;
                    lb_ToCurrency.Text = gv_Transaction.Rows[row.RowIndex].Cells[3].Text;
                    tx_ExchangeRate.Text = gv_Transaction.Rows[row.RowIndex].Cells[4].Text;
                    btn_Confirm.Text = "";
                    lb_ID.Text = id.ToString();
                    up_Edit.Update();
                    Session["Rowindex"] = row.RowIndex;
                    mp1.Show();

                }
                gv_Transaction.Rows[row.RowIndex].BackColor = System.Drawing.ColorTranslator.FromHtml("#023e91");
            }
        }
        protected void btn_Confirm_Click(object sender, EventArgs e)
        {
            CheckExchange();
            if (tx_FromEntity.Text.Equals("") || tx_ToEntity.Text.Equals(""))
            {
                Alert(" You have to select [ From cloumn ] or [ To Entity ] . ");
                return;
            }
            if (tx_Amount.Text.Equals(""))
            {
                Alert(" You have to key in To Amount . ");
                return;
            }
            if (tx_FromAmount.Text.Equals(""))
            {
                Alert(" You have to key in From Amount . ");
                return;
            }
            string regex = "^[0-9]{0,5}$|^[0-9]{0,5}\\.[0-9]{0,2}$ ";
            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
            | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);
            if (!reg.IsMatch(tx_Amount.Text))
            {
                Alert(" Please check Amount column . ");
                return;
            }
            using (DataEntryServiceClient _client = new DataEntryServiceClient())
            {
                PeriodServiceClient _pclient = new PeriodServiceClient();
                Period _period = new PeriodCollection(_pclient.GetCurrentPeriod())[0];

                int _FromEntityID = Convert.ToInt32(lb_FromEntityID.Text);
                int _ToEntityID = Convert.ToInt32(lb_ToEntityID.Text);
                decimal _Amount = Convert.ToDecimal(tx_Amount.Text);
                decimal _FromAmount = Convert.ToDecimal(tx_FromAmount.Text);
                if ((bool)Session["IsAdd"])
                {
                    Transaction _tran = new Transaction();
                    _tran.Period.ID = _period.ID;
                    _tran.IsPay = IsPay.N;
                    _tran.Creator.UserID = Convert.ToInt32(Session["Userid"]);
                    _tran.Amount = _FromAmount;
                    _tran.FromEntity.EntityID = _FromEntityID;
                    _tran.ToEntity.EntityID = _ToEntityID;
                    _tran.FromCurrency = lb_FromCurrency.Text;
                    _tran.ToCurrency = lb_ToCurrency.Text;
                    _tran.ExchangeRate = Convert.ToDecimal(tx_ExchangeRate.Text);
                    _tran.To_Amount = _Amount;
                    _client.InsertTransaction(_tran);
                    mp1.Hide();
                    GetData(_period);
                }
                else
                {
                    Transaction _tran = new TransactionCollection(_client.LoadTransactionByID(Convert.ToInt32(lb_ID.Text)))[0];
                    _tran.FromEntity.EntityID = _FromEntityID;
                    _tran.ToEntity.EntityID = _ToEntityID;
                    _tran.Amount = _FromAmount;
                    _tran.To_Amount = _Amount;
                    _tran.FromCurrency = lb_FromCurrency.Text;
                    _tran.ToCurrency = lb_ToCurrency.Text;
                    _tran.ExchangeRate = Convert.ToDecimal(tx_ExchangeRate.Text);
                    _client.Updatetransaction(_tran);
                    mp1.Hide();
                    GetData(_period);

                }
            }
            if(Session["Rowindex"]!=null)
                gv_Transaction.Rows[Convert.ToInt32(Session["Rowindex"])].BackColor = System.Drawing.ColorTranslator.FromHtml("#023e91");
        }
 public TransactionCollection FetchByID(object TxKey)
 {
     TransactionCollection coll = new TransactionCollection().Where("Tx_Key", TxKey).Load();
     return coll;
 }
 public void InsertTransactionCollection(TransactionCollection _collection)
 {
     using (TransactionAccessClient _tran = new TransactionAccessClient(EndpointName.TransactionAccess))
     {
         _tran.InsertTransactionCollection(_collection.ToArray());
     }
 }
 /// <summary>
 /// Loads all transactions for the current business from the data source that were applied to a given account.
 /// </summary>
 /// <param name="workbook">
 /// The workbook used to associate the loaded transactions with.
 /// </param>
 /// <param name="account">The account that will be used to search for transactions.</param>
 /// <returns>The loaded transactions.</returns>
 public override TransactionCollection FetchTransactions(Workbook workbook, Account account)
 {
     TransactionCollection results = new TransactionCollection();
     results.AddRange(ReadTransactions(workbook, account));
     return results;
 }
        private void GetData(Period _period)
        {
            DataEntryServiceClient _client = new DataEntryServiceClient();
            TransactionCollection _collection = new TransactionCollection();
            if(!_period.ID.Equals(0))
                _collection = new TransactionCollection(_client.LoadTransactionByPeriodID(_period.ID));
            else
                _collection = new TransactionCollection(_client.LoadTransaction());
            DataTable dt = new DataTable();
            dt.Columns.Add("id"); dt.Columns.Add("FromEntity"); dt.Columns.Add("ToEntity"); dt.Columns.Add("FromEntityid");
            dt.Columns.Add("ToEntityid"); dt.Columns.Add("Amount"); dt.Columns.Add("Notice"); dt.Columns.Add("NoticeTime");
            dt.Columns.Add("Pay"); dt.Columns.Add("Confirm"); dt.Columns.Add("ConfirmTime"); dt.Columns.Add("Updater");
            dt.Columns.Add("Creator"); dt.Columns.Add("FromCurrency"); dt.Columns.Add("ToCurrency"); dt.Columns.Add("ExchangeRate");
            foreach (Transaction _tran in _collection)
            {
                DataRow newRow = dt.NewRow();
                newRow["id"] = _tran.ID;
                newRow["FromEntity"] = _tran.FromEntity.EntityName;
                newRow["ToEntity"] = _tran.ToEntity.EntityName;
                newRow["FromEntityid"] = _tran.FromEntity.EntityID;
                newRow["ToEntityid"] = _tran.ToEntity.EntityID;
                newRow["Amount"] = string.Format("{0:N2}",_tran.Amount);
                newRow["Notice"] = _tran.NoticeUser.UserName;
                if (!_tran.NoticeTime.ToShortDateString().Equals("0001/1/1"))
                    newRow["NoticeTime"] = _tran.NoticeTime;

                newRow["Pay"] = _tran.IsPay;
                newRow["Confirm"] = _tran.ConfirmUser.UserName;
                if (!_tran.ConfirmTime.ToShortDateString().Equals("0001/1/1"))
                newRow["ConfirmTime"] = _tran.ConfirmTime;
                newRow["Updater"] = _tran.Updater.UserName;
                newRow["Creator"] = _tran.Creator.UserName;

                newRow["FromCurrency"] = _tran.FromCurrency;
                newRow["ToCurrency"] = _tran.ToCurrency;
                newRow["ExchangeRate"] = _tran.ExchangeRate;

                dt.Rows.Add(newRow);
            }
            gv_Transaction.DataSource = dt;
            gv_Transaction.DataBind();
            up_gvGrid.Update();
        }
 private void OnSubmitReport(object sender, RoutedEventArgs e)
 {
     DateTime rpt = DateTime.MinValue;
     try
     {
         rpt = DateTime.Parse(ReportDate);
     }
     catch { }
     Transactions = new TransactionCollection();
     Finances = new FinancialObjectCollection();
     foreach (InventoryTransactionObject tran1 in Cache.Current.ReadyForOpenCartUpdate)
     {
         if (((tran1.TransactionTime.CompareTo(rpt) >= 0 && tran1.TransactionTime.CompareTo(rpt.AddDays(1)) <= 0 || rpt.Year < 2014) && !ShowUnexportedOnly) || (ShowUnexportedOnly && !tran1.ExportedToWeb))
         {
             Transactions.Add(tran1);
         }
     }
     foreach (FinancialObject fin1 in Cache.Current.CurrentFinancials)
     {
         if (fin1.TransactionDateTime.CompareTo(rpt) >= 0 && fin1.TransactionDateTime.CompareTo(rpt.AddDays(1)) <= 0)
         {
             Finances.Add(fin1);
         }
     }
     MessageBox.Show("Complete");
     /*
      *   
     foreach (InventoryTransactionObject tran1 in working)
     {
         
         Cache.Current.ReadyForOpenCartUpdate.Add(tran1);
         Cache.Current.InventoryActivity.Remove(tran1);
     }
     if (tran != null)
     {
         Cache.Current.ReadyForOpenCartUpdate.Add(tran);
         working.Add(tran);
     }
     foreach (FinancialObject fin1 in financialList)
     {
         Cache.Current.StagedFinancials.Add(fin1);
         Cache.Current.CurrentFinancials.Remove(fin1);
     }
     if (fin != null)
     {
         Cache.Current.StagedFinancials.Add(fin);
         financialList.Add(fin);
     }
      * */
 }
Beispiel #43
0
 public DatabaseTransactionFactory(Database database)
 {
     this.database = database;
     OpenTransactions = new TransactionCollection();
 }
Beispiel #44
0
 /// <summary>
 /// Creates a new customer, which holds account and transaction information.
 /// </summary>
 /// <param name="accounts">The accounts for this customer.</param>
 public Customer(BankAccountCollection accounts)
 {
     this.accounts = accounts;
     this.transactionHistory = new TransactionCollection();
 }
Beispiel #45
0
 /// <summary>
 /// Creates a new BankAccount instance with a specific opening balance for the account.
 /// </summary>
 /// <param name="openingAccountBalance">Balance to open the account with.</param>
 public BankAccount(decimal openingAccountBalance)
 {
     this.balance = openingAccountBalance;
     this.pendingTransactions = new TransactionCollection();
 }
 public TransactionHistoryForm(TransactionCollection transactions)
 {
     InitializeComponent();
     this.transactions = transactions;
 }
 public TransactionCollection FetchByID(object TransactionId)
 {
     TransactionCollection coll = new TransactionCollection().Where("TransactionId", TransactionId).Load();
     return coll;
 }
 public TransactionCollection FetchByQuery(Query qry)
 {
     TransactionCollection coll = new TransactionCollection();
     coll.LoadAndCloseReader(qry.ExecuteReader());
     return coll;
 }
Beispiel #49
0
            private void Dispose(bool disposing)
            {
                if (disposing) {
                    if (OpenTransactions != null) {
                        foreach (var transaction in OpenTransactions) {
                            if (transaction != null)
                                transaction.Dispose();
                        }

                        OpenTransactions.Clear();
                    }
                }

                database = null;
                OpenTransactions = null;
            }