/// <summary>
        /// Get a list containing all transactions that meet the specified criteria.
        /// </summary>
        /// <param name="accessParams"></param>
        /// <param name="itemIDs"></param>
        /// <param name="stationIDs"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public static TransactionList LoadTransactions(List<FinanceAccessParams> accessParams, List<int> itemIDs,
            List<long> stationIDs, DateTime startDate, DateTime endDate, string type)
        {
            TransactionList retVal = new TransactionList();

            //---------------------------------------------------------------------------------------------------

            EMMADataSet.TransactionsDataTable table = new EMMADataSet.TransactionsDataTable();
            table = GetTransData(accessParams, itemIDs, new List<long>(), stationIDs, startDate, endDate, type);

            foreach (EMMADataSet.TransactionsRow row in table)
            {
                Transaction trans = new Transaction(row);
                retVal.Add(trans);
            }

            //---------------------------------------------------------------------------------------------------
            // This was an attempt to speed up loading of data by only loading IDs initally and
            // then retrieving other information as required.
            // It was not much faster on the inital load and gave worse stuttering during operation
            // so it's no longer used. Instead we simply limit the inital data retrieval on
            // the view form to the last week's worth of data.
            //---------------------------------------------------------------------------------------------------

            /*string itemString = "";
            string stationString = "";
            foreach (int item in itemIDs) { itemString = itemString + (itemString.Length == 0 ? "" : ",") + item; }
            foreach (int station in stationIDs) { stationString = stationString + (stationString.Length == 0 ? "" : ",") + station; }

            SqlConnection connection = new SqlConnection(Properties.Settings.Default.EMMA_DatabaseConnectionString);
            SqlDataAdapter adapter = null;
            SqlCommand command = null;
            connection.Open();

            command = new SqlCommand("TransCountByItemAndLoc", connection);
            command.CommandType = System.Data.CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@accessParams", FinanceAccessParams.BuildAccessList(accessParams)));
            command.Parameters.Add(new SqlParameter("@itemIDs", itemString));
            command.Parameters.Add(new SqlParameter("@stationIDs", stationString));
            command.Parameters.Add(new SqlParameter("@regionIDs", ""));
            command.Parameters.Add(new SqlParameter("@startDate", SqlDateTime.MinValue.Value));
            command.Parameters.Add(new SqlParameter("@endDate", SqlDateTime.MaxValue.Value));
            command.Parameters.Add(new SqlParameter("@transType", ""));
            adapter = new SqlDataAdapter(command);

            // lock on the transactions table adapter, even though we're not actually using it, we're still
            // accessing the same database table.
            lock (tableAdapter)
            {
                SqlDataReader reader = adapter.SelectCommand.ExecuteReader();
                try
                {
                    while (reader.Read())
                    {
                        Transaction trans = new Transaction(reader.GetInt64(0));
                        retVal.Add(trans);
                    }
                }
                finally
                {
                    reader.Close();
                }
            }*/

            //---------------------------------------------------------------------------------------------------

            return retVal;
        }
        private void ViewTrans_Load(object sender, EventArgs e)
        {
            try
            {
                _transactions = new TransactionList();
                _transBindingSource = new BindingSource();
                _transBindingSource.DataSource = _transactions;

                DataGridViewCellStyle style = new DataGridViewCellStyle(PriceColumn.DefaultCellStyle);
                style.Format = IskAmount.FormatString();
                PriceColumn.DefaultCellStyle = style;
                TotalValueColumn.DefaultCellStyle = style;
                UnitProfitColumn.DefaultCellStyle = style;

                transactionGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                transactionGrid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;

                transactionGrid.DataSource = _transBindingSource;
                IDColumn.DataPropertyName = "Id";
                DateTimeColumn.DataPropertyName = "Datetime";
                ItemColumn.DataPropertyName = "Item";
                PriceColumn.DataPropertyName = "Price";
                BuyerColumn.DataPropertyName = "Buyer";
                QuantityColumn.DataPropertyName = "Quantity";
                TotalValueColumn.DataPropertyName = "Total";
                SellerColumn.DataPropertyName = "Seller";
                BuyerCharacterColumn.DataPropertyName = "BuyerChar";
                SellerCharacterColumn.DataPropertyName = "SellerChar";
                StationColumn.DataPropertyName = "Station";
                RegionColumn.DataPropertyName = "Region";
                BuyerIDColumn.DataPropertyName = "BuyerID";
                SellerIDColumn.DataPropertyName = "SellerID";
                BuyerCharIDColumn.DataPropertyName = "BuyerCharID";
                SellerCharIDColumn.DataPropertyName = "SellerCharID";
                BuyerWalletColumn.DataPropertyName = "BuyerWallet";
                SellerWalletColumn.DataPropertyName = "SellerWallet";
                UnitProfitColumn.DataPropertyName = UserAccount.Settings.CalcProfitInTransView ?
                    "GrossUnitProfit" : "PureGrossUnitProfit";

                UserAccount.Settings.GetColumnWidths(this.Name, transactionGrid);

                dtpEndDate.Value = DateTime.Now;
                dtpStartDate.Value = DateTime.Now.AddDays(-2);

                dtpEndDate.DropDown+=new EventHandler(dtpEndDate_DropDown);
                dtpEndDate.CloseUp+=new EventHandler(dtpEndDate_CloseUp);
                dtpEndDate.KeyDown += new KeyEventHandler(dtpEndDate_KeyDown);
                dtpEndDate.Leave += new EventHandler(dtpEndDate_Leave);

                dtpStartDate.DropDown += new EventHandler(dtpStartDate_DropDown);
                dtpStartDate.CloseUp += new EventHandler(dtpStartDate_CloseUp);
                dtpStartDate.KeyDown += new KeyEventHandler(dtpStartDate_KeyDown);
                dtpStartDate.Leave += new EventHandler(dtpStartDate_Leave);

                List<CharCorpOption> charcorps = UserAccount.CurrentGroup.GetCharCorpOptions(
                    APIDataType.Transactions);
                _possibleOwners = new List<long>();
                foreach (CharCorpOption chop in charcorps)
                {
                    _possibleOwners.Add(chop.Corp ? chop.CharacterObj.CorpID : chop.CharacterObj.CharID);
                }
                cmbOwner.DisplayMember = "Name";
                cmbOwner.ValueMember = "Data";
                charcorps.Sort();
                cmbOwner.DataSource = charcorps;
                cmbOwner.SelectedValue = 0;
                cmbOwner.SelectedIndexChanged += new EventHandler(cmbOwner_SelectedIndexChanged);
                cmbOwner.Enabled = false;
                chkIngoreOwner.Checked = true;
                chkIngoreOwner.CheckedChanged += new EventHandler(chkIngoreOwner_CheckedChanged);

                cmbWallet.SelectedIndexChanged += new EventHandler(cmbWallet_SelectedIndexChanged);
                cmbType.SelectedIndexChanged += new EventHandler(cmbType_SelectedIndexChanged);

                _recentItems = UserAccount.CurrentGroup.Settings.RecentItems;
                _recentItems.Sort();
                cmbItem.Items.AddRange(_recentItems.ToArray());
                cmbItem.AutoCompleteSource = AutoCompleteSource.ListItems;
                cmbItem.AutoCompleteMode = AutoCompleteMode.Suggest;
                cmbItem.KeyDown += new KeyEventHandler(cmbItem_KeyDown);
                cmbItem.SelectedIndexChanged += new EventHandler(cmbItem_SelectedIndexChanged);
                cmbItem.Tag = 0;

                _recentStations = UserAccount.CurrentGroup.Settings.RecentStations;
                _recentStations.Sort();
                cmbStation.Items.AddRange(_recentStations.ToArray());
                cmbStation.AutoCompleteSource = AutoCompleteSource.ListItems;
                cmbStation.AutoCompleteMode = AutoCompleteMode.Suggest;
                cmbStation.KeyDown += new KeyEventHandler(cmbStation_KeyDown);
                cmbStation.SelectedIndexChanged += new EventHandler(cmbStation_SelectedIndexChanged);
                cmbStation.Tag = 0;

                chkCalcProfit.Checked = UserAccount.Settings.CalcProfitInTransView;
                chkCalcProfit.CheckedChanged += new EventHandler(chkCalcProfit_CheckedChanged);

                this.FormClosing += new FormClosingEventHandler(ViewTransactions_FormClosing);
                DisplayWallets();
                chkIgnoreWallet.CheckedChanged += new EventHandler(chkIgnoreWallet_CheckedChanged);
                DisplayTrans();
            }
            catch (Exception ex)
            {
                // Creating new EMMAexception will cause error to be logged.
                EMMAException emmaex = ex as EMMAException;
                if (emmaex == null)
                {
                    emmaex = new EMMAException(ExceptionSeverity.Critical, "Error setting up transactions form", ex);
                }
                MessageBox.Show("Problem setting up transactions view.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public static bool GetResultsPage(int startPos, int pageSize, ref TransactionList transactions)
        {
            if (startPos <= 0) startPos = 1;
            EMMADataSet.TransactionsDataTable table = new EMMADataSet.TransactionsDataTable();
            lock (tableAdapter)
            {
                tableAdapter.FillByResultsPage(table, startPos, pageSize);
            }
            foreach (EMMADataSet.TransactionsRow transaction in table)
            {
                transactions.Add(new Transaction(transaction));
            }

            return table.Count == pageSize;
        }
        private void DisplayTrans()
        {
            if (_allowRefresh)
            {
                List<int> itemIDs = new List<int>();
                itemIDs.Add(int.Parse(cmbItem.Tag.ToString()));
                List<long> stationIDs = new List<long>();
                stationIDs.Add(long.Parse(cmbStation.Tag.ToString()));
                DateTime utcStart = new DateTime();
                DateTime utcEnd = new DateTime();
                string type = cmbType.Text;

                Cursor = Cursors.WaitCursor;

                try
                {
                    long ownerID = 0;
                    if (cmbOwner.SelectedValue != null && !chkIngoreOwner.Checked)
                    {
                        CharCorp data = (CharCorp)cmbOwner.SelectedValue;
                        ownerID = data.corp ? data.characterObj.CorpID : data.characterObj.CharID;
                    }
                    int walletID = 0;
                    if (cmbWallet.SelectedValue != null && !chkIgnoreWallet.Checked)
                    {
                        walletID = (int)cmbWallet.SelectedValue;
                    }

                    List<FinanceAccessParams> accessParams = new List<FinanceAccessParams>();
                    if (ownerID == 0)
                    {
                        foreach (long id in _possibleOwners)
                        {
                            accessParams.Add(new FinanceAccessParams(id));
                        }
                    }
                    else
                    {
                        List<short> wallets = new List<short>();
                        if (walletID != 0)
                        {
                            wallets.Add((short)walletID);
                        }
                        accessParams.Add(new FinanceAccessParams(ownerID, wallets));
                    }

                    utcStart = dtpStartDate.Value.ToUniversalTime();
                    utcEnd = dtpEndDate.Value.ToUniversalTime();

                    //ListSortDirection sortDirection = ListSortDirection.Descending;
                    //DataGridViewColumn sortColumn = transactionGrid.SortedColumn;
                    //if (transactionGrid.SortOrder == SortOrder.Ascending) sortDirection = ListSortDirection.Ascending;
                    List<SortInfo> sortinfo = transactionGrid.GridSortInfo;

                    _transactions = Transactions.LoadTransactions(accessParams, itemIDs, stationIDs,
                        utcStart, utcEnd, type);
                    _transBindingSource.DataSource = _transactions;

                    //transactionGrid.AutoResizeColumns();
                    //transactionGrid.AutoResizeRows();

                    //if (sortColumn != null)
                    //{
                    //    transactionGrid.Sort(sortColumn, sortDirection);
                    //}
                    //else
                    //{
                    //    transactionGrid.Sort(DateTimeColumn, ListSortDirection.Descending);
                    //}
                    if (sortinfo.Count == 0)
                    {
                        DataGridViewColumn column = transactionGrid.Columns["DateTimeColumn"];
                        sortinfo.Add(new SortInfo(column.Index, column.DataPropertyName));
                    }
                    transactionGrid.GridSortInfo = sortinfo;

                    Text = "Viewing " + _transBindingSource.Count + " transactions";
                }
                finally
                {
                    Cursor = Cursors.Default;
                }
            }
        }
        private void ViewItemDetail_Load(object sender, EventArgs e)
        {
            try
            {
                chkOwners.ItemCheck += new ItemCheckEventHandler(chkOwners_ItemCheck);
                chkOwners.SelectedIndexChanged += new EventHandler(chkOwners_SelectedIndexChanged);
                RefreshCharList();

                EveDataSet.invTypesDataTable allitems = UserAccount.CurrentGroup.TradedItems.GetAllItems();
                ItemInfo[] info = new ItemInfo[allitems.Count];
                for(int i = 0 ; i < allitems.Count; i++)
                {
                    EveDataSet.invTypesRow item = allitems[i];
                    info[i] = new ItemInfo(item.typeID, item.typeName);
                }
                chkItems.Sorted = true;
                chkItems.Items.AddRange(info);

                DataGridViewCellStyle style = new DataGridViewCellStyle(BuyOrderPriceColumn.DefaultCellStyle);
                style.Format = IskAmount.FormatString();
                BuyOrderPriceColumn.DefaultCellStyle = style;
                SellOrderPriceColumn.DefaultCellStyle = style;
                TransactionsPriceColumn.DefaultCellStyle = style;
                TransactionsTotalColumn.DefaultCellStyle = style;
                TransactionsGrossProfitColumn.DefaultCellStyle = style;
                TransactionsGrossUnitProfit.DefaultCellStyle = style;

                buyOrdersView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                buyOrdersView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
                buyOrdersView.AutoGenerateColumns = false;
                BuyOrderDateTimeColumn.DataPropertyName = "Date";
                BuyOrderItemColumn.DataPropertyName = "Item";
                BuyOrderMovement12HoursColumn.DataPropertyName = "TwelveHourMovement";
                BuyOrderMovement2DaysColumn.DataPropertyName = "TwoDayMovement";
                BuyOrderMovement7DaysColumn.DataPropertyName = "SevenDayMovement";
                BuyOrderOwnerColumn.DataPropertyName = "Owner";
                BuyOrderPriceColumn.DataPropertyName = "Price";
                BuyOrderRangeColumn.DataPropertyName = "RangeText";
                BuyOrderRegionColumn.DataPropertyName = "Region";
                BuyOrderRemainingUnits.DataPropertyName = "RemainingVol";
                BuyOrderStationColumn.DataPropertyName = "Station";
                BuyOrderStatus.DataPropertyName = "State";
                BuyOrderSystemColumn.DataPropertyName = "System";
                BuyOrderTotaUnits.DataPropertyName = "TotalVol";
                BuyOrderPercentageCompleteColumn.DataPropertyName = "PercentageCompleted";

                sellOrdersView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                sellOrdersView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
                sellOrdersView.AutoGenerateColumns = false;
                SellOrderDateColumn.DataPropertyName = "Date";
                SellOrderItemColumn.DataPropertyName = "Item";
                SellOrderMovement12HoursColumn.DataPropertyName = "TwelveHourMovement";
                SellOrderMovement2DaysColumn.DataPropertyName = "TwoDayMovement";
                SellOrderMovement7DaysColumn.DataPropertyName = "SevenDayMovement";
                SellOrderOwnerColumn.DataPropertyName = "Owner";
                SellOrderPriceColumn.DataPropertyName = "Price";
                SellOrderRangeColumn.DataPropertyName = "RangeText";
                SellOrderRegionColumn.DataPropertyName = "Region";
                SellOrderRemainingUnitsColumn.DataPropertyName = "RemainingVol";
                SellOrderStationColumn.DataPropertyName = "Station";
                SellOrderStatusColumn.DataPropertyName = "State";
                SellOrderSystemColumn.DataPropertyName = "System";
                SellOrderTotalUnitsColumn.DataPropertyName = "TotalVol";
                SellOrderPercentageCompleteColumn.DataPropertyName = "PercentageCompleted";
                SellOrderLocalStockAvailable.DataPropertyName = "LocalStockAvailable";
                SellOrderMatchingBuyOrderExistsColumn.DataPropertyName = "BuyOrderExistsForThisItem";

                transactionsView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                transactionsView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
                transactionsView.AutoGenerateColumns = false;
                TransactionsBuyerCharacterColumn.DataPropertyName = "BuyerChar";
                TransactionsBuyerColumn.DataPropertyName = "Buyer";
                TransactionsBuyerWalletColumn.DataPropertyName = "BuyerWallet";
                TransactionsDateTimeColumn.DataPropertyName = "Datetime";
                TransactionsItemColumn.DataPropertyName = "Item";
                TransactionsPriceColumn.DataPropertyName = "Price";
                TransactionsQuantityColumn.DataPropertyName = "Quantity";
                TransactionsSellerCharacterColumn.DataPropertyName = "SellerChar";
                TransactionsSellerColumn.DataPropertyName = "Seller";
                TransactionsSellerWalletColumn.DataPropertyName = "SellerWallet";
                TransactionsStationColumn.DataPropertyName = "Station";
                TransactionsTotalColumn.DataPropertyName = "Total";
                TransactionsGrossProfitColumn.DataPropertyName = "GrossProfit";
                TransactionsGrossUnitProfit.DataPropertyName = "GrossUnitProfit";

                inventoryView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                inventoryView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
                inventoryView.AutoGenerateColumns = false;
                InventoryItemColumn.DataPropertyName = "Item";
                InventoryQuantityColumn.DataPropertyName = "Quantity";
                InventoryRegionColumn.DataPropertyName = "Region";
                InventoryLocationColumn.DataPropertyName = "Location";
                InventorySystemColumn.DataPropertyName = "System";
                InventoryOwnerColumn.DataPropertyName = "Owner";

                _transactions = new TransactionList();
                _inventory = new AssetList();
                transactionsView.DataSource = _transactions;
                inventoryView.DataSource = _inventory;
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    new EMMAException(ExceptionSeverity.Error, "Problem loading item detail view", ex);
                }
                MessageBox.Show("Problem loading item detail view:\r\n" + ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void UpdateTransactions()
        {
            try
            {
                Transactions.BuildResults(_finParams, _itemIDs, new List<long>(), new List<long>(),
                    dtpStartDate.Value, dtpEndDate.Value, "any");
                _transactionsDataVisible = true;
                RefreshGUI();

                int pageSize = 20;
                int startRow = 1;
                TransactionList transactions = new TransactionList();

                while (Transactions.GetResultsPage(startRow, pageSize, ref transactions))
                {
                   AddTransactions(transactions);
                    transactions = new TransactionList();
                    startRow += pageSize;
                }
                AddTransactions(transactions);
                _transactionsGettingData = false;
                RefreshGUI();
            }
            catch (ThreadAbortException)
            {
                // User has aborted, just drop out.
            }
            catch (Exception ex)
            {
                new EMMAException(ExceptionSeverity.Error, "Error when updating transaction data in item detail", ex);
            }
        }
        private void StartUpdate()
        {
            Cursor = Cursors.WaitCursor;

            try
            {
                _ordersDataVisible = false;
                _inventoryDataVisible = false;
                _transactionsDataVisible = false;
                _ordersGettingData = true;
                _inventoryGettingData = true;
                _transactionsGettingData = true;
                RefreshGUI();

                _inventory = new AssetList();
                _transactions = new TransactionList();
                inventoryView.DataSource = _inventory;
                transactionsView.DataSource = _transactions;

                // Generate finance access parameters
                _finParams = new List<FinanceAccessParams>();
                Dictionary<long, List<int>>.Enumerator enumerator = _useDataFrom.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    // If we are accessing all wallets for a corp then no need to bether with this
                    // as the default is to access everything when a blank list is supplied.
                    List<short> walletIDs = new List<short>();
                    if (enumerator.Current.Value.Count < 7)
                    {
                        foreach (short walletId in enumerator.Current.Value)
                        {
                            walletIDs.Add(walletId);
                        }
                    }

                    _finParams.Add(new FinanceAccessParams(enumerator.Current.Key, walletIDs));
                }

                // Generate asset access parameters
                _assetParams = new List<AssetAccessParams>();
                foreach (object item in chkOwners.CheckedItems)
                {
                    bool done = false;
                    CharCorpOption owner = (CharCorpOption)item;

                    foreach (AssetAccessParams character in _assetParams)
                    {
                        if (character.OwnerID == owner.Data.ID)
                        {
                            // If the specified ownerID is already in the access parameter list then
                            // don't add it again.
                            done = true;
                        }
                    }

                    if (!done)
                    {
                        _assetParams.Add(new AssetAccessParams(owner.Data.ID));
                    }
                }

                _itemIDs = new List<int>();
                foreach (object item in chkItems.CheckedItems)
                {
                    _itemIDs.Add(((ItemInfo)item).ID);
                }

                _orderPlaceholderType = OrderPlaceholderType.None;
                if (rdbItemPlaceholders.Checked)
                {
                    _orderPlaceholderType = OrderPlaceholderType.PerItem;
                }
                else if (rdbAllPlaceholders.Checked)
                {
                    _orderPlaceholderType = OrderPlaceholderType.PerItemPerEntity;
                }

                // Kick off the threads that will do the updating of the data tables.
                _ordersUpdateThread = new Thread(new ThreadStart(UpdateOrders));
                _ordersUpdateThread.Start();
                _transactionsUpdateThread = new Thread(new ThreadStart(UpdateTransactions));
                _transactionsUpdateThread.Start();
                _inventoryUpdateThread = new Thread(new ThreadStart(UpdateInventory));
                _inventoryUpdateThread.Start();
            }
            catch (Exception ex)
            {
                new EMMAException(ExceptionSeverity.Error, "Error when starting data update in item detail", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
 private void AddTransactions(TransactionList transactions)
 {
     if (this.InvokeRequired)
     {
         AddTransCallback callback = new AddTransCallback(AddTransactions);
         object[] parameters = new object[1];
         parameters[0] = transactions;
         this.Invoke(callback, parameters);
     }
     else
     {
         foreach (Transaction trans in transactions)
         {
             _transactions.Add(trans);
         }
         //transactionsView.Refresh();
         lblTransactionsRetrieved.Text = _transactions.Count + " Transactions retrieved";
     }
 }