private void btnAutoDiv_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            try
            {
                DivUpdateInfo info = Dividends.UpdateFromJournal(false);
                string corpNames = "";
                foreach (string corp in info.missingCorps)
                {
                    corpNames = corpNames + (corpNames.Length == 0 ? "" : ", ") + corp;
                }
                MessageBox.Show("Dividends processing completed\r\n" + info.dividendsAdded + " dividends added" +
                    (info.dividendsNotAdded == 0 ? "" :
                    "\r\n" + info.dividendsNotAdded + " dividends could not be added because the corp " +
                    "is not defined\r\nList of undefined corp names: " + corpNames + "\r\n" +
                    "Create these corps and then run dividend auto add again."));
            }
            catch (Exception ex)
            {
                EMMAException emmaex = ex as EMMAException;
                if (emmaex == null)
                {
                    emmaex = new EMMAException(ExceptionSeverity.Error, "Problem creating dividend entries from" +
                        "journal data.", ex);
                }
                MessageBox.Show("Error trying to create new dividends: " + ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        void GroupLocationList_Load(object sender, EventArgs e)
        {
            try
            {
                _locations = GroupLocations.GetGroupLocationsData();
                _locationsBindingSource = new BindingSource();
                _locationsBindingSource.DataSource = _locations;

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

                locationsGrid.AutoGenerateColumns = false;
                locationsGrid.DataSource = _locationsBindingSource;
                NameColumn.DataPropertyName = "Name";
                DescriptionColumn.DataPropertyName = "Description";
            }
            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 group location form", ex);
                }
                MessageBox.Show("Problem setting up group location view.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            bool checkForUpdates = true;
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].Equals("/u"))
                {
                    try
                    {
                        checkForUpdates = bool.Parse(args[i + 1]);
                    }
                    catch
                    {
                        checkForUpdates = true;
                    }
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                Main main = new Main(checkForUpdates);
                if(!main.IsDisposed)
                {
                    Application.Run(main);
                }
            }
            catch (Exception ex)
            {
                // Creating new exception will cause error to be logged.
                EMMAException emmaex = ex as EMMAException;
                if (emmaex == null)
                {
                    emmaex = new EMMAException(ExceptionSeverity.Critical, "Unhandled exception", ex);
                }
                MessageBox.Show("An unexpected error has occured.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                try
                {
                    // Attempt to logout. This will save all settings, etc.
                    UserAccount.Logout();
                }
                catch (Exception ex2)
                {
                    EMMAException emmaex2 = ex2 as EMMAException;
                    if (emmaex2 == null)
                    {
                        emmaex2 = new EMMAException(ExceptionSeverity.Critical,
                            "Error during automatic log out", ex2);
                    }
                }

                // Close the application. In some cases it may still be able to continue but it's
                // much safer to just shut things down.
                Application.Exit();
            }
        }
        public void Run()
        {
            Thread.Sleep(500); // Wait for half a second to allow the calling thread to display the dialog...
            int checks = 2;

            try
            {
                UpdateStatus(0, checks, "Checking database", "", false);

                // Check 1 - Check for duplicated, dividend data.
                UpdateStatus(0, checks, "", "Checking for duplicated dividend entries", false);
                int total = Dividends.ClearDuplicates();
                if (total == 0)
                {
                    UpdateStatus(1, checks, "", "No duplicates found", false);
                }
                else
                {
                    UpdateStatus(1, checks, "", total + " duplicates found and removed.", false);
                }

                // Check 2 - Move assets/orders stored against character IDs to corp IDs.
                UpdateStatus(1, checks, "", "Checking for corporate assets stored by character ID", false);
                foreach (EVEAccount account in UserAccount.CurrentGroup.Accounts)
                {
                    foreach (APICharacter character in account.Chars)
                    {
                        UpdateStatus(1, checks, "", "Checking " + character.CharName + "...", false);
                        character.Settings.UpdatedOwnerIDToCorpID = false;
                        character.UpdateOwnerIDToCorpID();
                    }
                }

                UpdateStatus(checks, checks, "Checks complete", "", true);
            }
            catch (Exception ex)
            {
                EMMAException emmaex = ex as EMMAException;
                if (emmaex == null)
                {
                    emmaex = new EMMAException(ExceptionSeverity.Error, "Problem verifying data integrity", ex);
                }
                UpdateStatus(-1, -1, "Error", "Problem verifying data integrity: " + ex.Message, true);
            }
        }
        private void ItemValueHistory_Load(object sender, EventArgs e)
        {
            try
            {
                GraphPane pane = priceHistoryGraph.GraphPane;
                pane.Title.Text = "Item price history";

                _recentItems = UserAccount.CurrentGroup.Settings.RecentItems;
                _recentItems.Sort();
                AutoCompleteStringCollection items = new AutoCompleteStringCollection();
                items.AddRange(_recentItems.ToArray());
                txtItem.AutoCompleteCustomSource = items;
                txtItem.AutoCompleteSource = AutoCompleteSource.CustomSource;
                txtItem.AutoCompleteMode = AutoCompleteMode.Suggest;
                txtItem.Leave += new EventHandler(txtItem_Leave);
                txtItem.KeyDown += new KeyEventHandler(txtItem_KeyDown);
                txtItem.Tag = 0;
                txtItem.Text = "";

                EveDataSet.mapRegionsDataTable regions = Regions.GetAllRegions();
                EveDataSet.mapRegionsRow allRegions = regions.NewmapRegionsRow();
                allRegions.regionID = 0;
                allRegions.regionName = "Any Region";
                regions.AddmapRegionsRow(allRegions);
                cmbRegion.DataSource = regions;
                cmbRegion.ValueMember = "regionID";
                cmbRegion.DisplayMember = "regionName";
                cmbRegion.SelectedValue = 0;
                cmbRegion.SelectedValueChanged += new EventHandler(cmbRegion_SelectedValueChanged);
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem loading grid calculator: " +
                        ex.Message, ex);
                }
                MessageBox.Show("Problem loading grid calculator: " + ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Add journal entries from the supplied XML to the database.
        /// </summary>
        /// <param name="corc"></param>
        /// <param name="fileXML"></param>
        /// <returns>The number of rows added to the journal table.</returns>
        private int UpdateJournalFromXML(CharOrCorp corc, XmlDocument fileXML, short walletID)
        {
            int retVal = 0;
            int updatedEntries = 0;
            EMMADataSet.JournalDataTable journalData = new EMMADataSet.JournalDataTable();
            long highestIDSoFar = _apiSettings.GetHighestID(corc, APIDataType.Journal);
            long oldHighestID = _apiSettings.GetHighestID(corc, APIDataType.Journal);
            DateTime dataDate = DateTime.UtcNow;

            try
            {
                XmlNodeList journEntries = null;
                XmlDocument xml = new XmlDocument();

                UpdateStatus(0, 1, "Getting journal entries from file", "", false);
                journEntries = EveAPI.GetResults(fileXML);
                dataDate = EveAPI.GetDataTime(fileXML);
                UpdateStatus(1, 1, "", journEntries.Count + " entries found in file.", false);

                if (journEntries != null && journEntries.Count > 0)
                {
                    // Offset will always be the same since CCP switched over to 64 bit IDs
                    // (At least until we break the 64bit limit... As of mid 2010, we're using
                    // around 2 billion IDs a year so breaking the 64 bit limit will take around
                    // 9 billion years... Don't think it will be a problem :))
                    long offset = 2591720933;
                    int batchPrg = 0;

                    UpdateStatus(0, journEntries.Count, "Processing entries", "", false);

                    // Loop through the results returned from this call to the API and add the line
                    // to the data table.
                    foreach (XmlNode journEntry in journEntries)
                    {
                        bool tryUpdate = false;
                        long id = long.Parse(journEntry.SelectSingleNode("@refID").Value) + offset;
                        long recieverID = 0;
                        if (corc == CharOrCorp.Corp)
                        {
                            // This is a special case.
                            // When bounty prizes are received by the player, corp tax is applied.
                            // This corp tax does not appear as a seperate journal entry for the
                            // character. It is specified by the taxReceiverID and taxAmount fields
                            // on the bounty prize entry itself in the XML.
                            // On the corp side, there is a specifc entry for the tax but it has
                            // the same journalentryID and ownerID2 as the character entry.
                            // This means that EMMA does not differentiate between them and the
                            // corp tax part is lost.
                            // In order to resolve this we simply set receiver ID to be the corp
                            // instead of character in these cases.
                            // Note that 'BuildJournalEntry' has similar processing.
                            if (int.Parse(journEntry.SelectSingleNode("@refTypeID").Value) == 85)
                            {
                                recieverID = _corpID;
                            }
                        }
                        if (recieverID == 0)
                        {
                            recieverID = long.Parse(journEntry.SelectSingleNode("@ownerID2").Value);
                        }

                        //if (id - offset > oldHighestID)
                        //{
                        if (id - offset > highestIDSoFar) { highestIDSoFar = id - offset; }
                        if (Journal.EntryExists(journalData, id, recieverID))
                        {
                            tryUpdate = true;
                        }
                        else
                        {
                            EMMADataSet.JournalRow tmpRow = journalData.FindByIDRecieverID(id, recieverID);
                            if (tmpRow == null)
                            {
                                EMMADataSet.JournalRow newRow =
                                    BuildJournalEntry(journalData, journEntry, offset, walletID, corc);

                                journalData.AddJournalRow(newRow);
                                retVal++;

                                // This section searches the character and journal ref type tables
                                // for the values used in this new journal entry.
                                // If they are not present in the tables then they are added.
                                #region Check other tables and add values if needed.
                                SortedList<long, string> entityIDs = new SortedList<long, string>();
                                entityIDs.Add(newRow.SenderID, journEntry.SelectSingleNode("@ownerName1").Value);
                                if (!entityIDs.ContainsKey(newRow.RecieverID))
                                {
                                    entityIDs.Add(newRow.RecieverID, journEntry.SelectSingleNode("@ownerName2").Value);
                                }
                                foreach (KeyValuePair<long, string> checkName in entityIDs)
                                {
                                    Names.AddName(checkName.Key, checkName.Value);
                                }
                                #endregion
                            }
                            else
                            {
                                tryUpdate = true;
                            }
                        }

                        if (tryUpdate)
                        {
                            EMMADataSet.JournalRow newRow =
                                BuildJournalEntry(journalData, journEntry, offset, walletID, corc);
                            EMMADataSet.JournalRow oldRow = journalData.FindByIDRecieverID(newRow.ID,
                                    newRow.RecieverID);
                            bool updated = false;

                            if (oldRow != null)
                            {
                                if ((newRow.RBalance > 0 && oldRow.RBalance == 0) ||
                                    (newRow.RCorpID != 0 && oldRow.RCorpID == 0))
                                {
                                    oldRow.RBalance = newRow.RBalance;
                                    oldRow.RCorpID = newRow.RCorpID;
                                    oldRow.RArgID = newRow.RArgID;
                                    oldRow.RArgName = newRow.RArgName;
                                    oldRow.RWalletID = newRow.RWalletID;
                                    updated = true;
                                }
                                if ((newRow.SBalance > 0 && oldRow.SBalance == 0) ||
                                    (newRow.SCorpID != 0 && oldRow.SCorpID == 0))
                                {
                                    oldRow.SBalance = newRow.SBalance;
                                    oldRow.SCorpID = newRow.SCorpID;
                                    oldRow.SArgID = newRow.SArgID;
                                    oldRow.SArgName = newRow.SArgName;
                                    oldRow.SWalletID = newRow.SWalletID;
                                    updated = true;
                                }
                            }

                            if (updated)
                            {
                                updatedEntries++;
                            }
                        }

                        //}

                        batchPrg++;
                        UpdateStatus(batchPrg, journEntries.Count, "", "", false);
                    }

                    SetHighestID(corc, APIDataType.Journal, highestIDSoFar);
                }

                UpdateStatus(0, 0, retVal + " journal entries added to database.", "", false);
                UpdateStatus(0, 0, updatedEntries + " existing journal entries updated.", "", true);

                if (journalData.Count > 0)
                {
                    Journal.Store(journalData);
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    // If we've caught a standard exception rather than an EMMA one then log
                    // it by creating a new exception.
                    // Note that we don't need to actually throw it..
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Error when adding journal data", ex);
                }

                SetLastAPIUpdateError(corc, APIDataType.Journal, ex.Message);
                UpdateStatus(-1, 0, "Error", ex.Message, true);
            }

            if (UpdateEvent != null)
            {
                UpdateEvent(this, new APIUpdateEventArgs(APIDataType.Journal,
                    corc == CharOrCorp.Char ? _charID : _corpID,
                    APIUpdateEventType.UpdateCompleted));
            }

            return retVal;
        }
        private void UpdateIndustryJobsFromXML(CharOrCorp corc, XmlDocument fileXML)
        {
            EMMADataSet.IndustryJobsDataTable jobsData = new EMMADataSet.IndustryJobsDataTable();

            try
            {
                XmlNodeList jobEntries = null;

                UpdateStatus(0, 1, "Getting industry jobs from file", "", false);
                jobEntries = EveAPI.GetResults(fileXML);
                UpdateStatus(1, 1, "", jobEntries.Count + " industry jobs found in file.", false);

                if (jobEntries != null && jobEntries.Count > 0)
                {
                    UpdateStatus(0, jobEntries.Count, "Processing jobs", "", false);

                    foreach (XmlNode jobEntry in jobEntries)
                    {
                        EMMADataSet.IndustryJobsRow jobRow = BuildIndustryJobRow(jobsData, jobEntry);
                        if (IndustryJobs.GetJob(jobsData, jobRow.ID))
                        {
                            // The job already exists in the database. Update if needed.
                            EMMADataSet.IndustryJobsRow oldJobRow = jobsData.FindByID(jobRow.ID);
                            if (oldJobRow.Completed != jobRow.Completed ||
                                oldJobRow.CompletedStatus != jobRow.CompletedStatus ||
                                oldJobRow.CompletedSuccessfully != jobRow.CompletedSuccessfully ||
                                oldJobRow.EndProductionTime.CompareTo(jobRow.EndProductionTime) != 0 ||
                                oldJobRow.PauseProductionTime.CompareTo(jobRow.PauseProductionTime) != 0)
                            {
                                oldJobRow.Completed = jobRow.Completed;
                                oldJobRow.CompletedStatus = jobRow.CompletedStatus;
                                oldJobRow.CompletedSuccessfully = jobRow.CompletedSuccessfully;
                                oldJobRow.EndProductionTime = jobRow.EndProductionTime;
                                oldJobRow.PauseProductionTime = jobRow.PauseProductionTime;
                            }
                            else
                            {
                                // No changes
                            }
                        }
                        else
                        {
                            // This is a new job. Add it to the database.
                            jobsData.AddIndustryJobsRow(jobRow);
                        }

                    }
                }

                if (jobsData != null && jobsData.Count > 0)
                {
                    IndustryJobs.Store(jobsData);
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    // If we've caught a standard exception rather than an EMMA one then log it by creating a
                    // new exception.
                    // Note that we don't need to actually throw it..
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Error when adding industry jobs", ex);
                }

                SetLastAPIUpdateError(corc, APIDataType.IndustryJobs, ex.Message);
                UpdateStatus(-1, 0, "Error", ex.Message, true);
            }

            if (UpdateEvent != null)
            {
                UpdateEvent(this, new APIUpdateEventArgs(APIDataType.IndustryJobs,
                    corc == CharOrCorp.Char ? _charID : _corpID,
                    APIUpdateEventType.UpdateCompleted));
            }
        }
        private void UpdateAssetsFromXML(CharOrCorp corc, XmlDocument xml)
        {
            DateTime earliestUpdate = GetLastAPIUpdateTime(corc, APIDataType.Assets).AddHours(23);
            EMMADataSet.AssetsDataTable assetData = new EMMADataSet.AssetsDataTable();
            DateTime dataDate = DateTime.MinValue;

            try
            {
                XmlNodeList assetList = null;

                UpdateStatus(0, 1, "Getting asset data from file", "", false);

                dataDate = EveAPI.GetDataTime(xml);
                DateTime assetsEffectiveDate = corc == CharOrCorp.Char ?
                    Settings.CharAssetsEffectiveDate : Settings.CorpAssetsEffectiveDate;
                if (dataDate.CompareTo(assetsEffectiveDate) < 0)
                {
                    UpdateStatus(1, 1, "Error", "This data in this file is from " + dataDate.ToString() +
                        ". EMMA has already imported asset data dated " + assetsEffectiveDate + " therefore the" +
                        " database will not be updated.", true);
                    assetList = null;
                }
                else
                {
                    assetList = EveAPI.GetResults(xml);
                    UpdateStatus(1, 1, "", assetList.Count + " asset data lines found.", false);
                }

                if (assetList != null)
                {
                    // Set the 'processed' flag to false for all of this char/corp's assets.
                    Assets.SetProcessedFlag(corc == CharOrCorp.Corp ? _corpID : _charID, (int)AssetStatus.States.Normal, false);
                    Assets.SetProcessedFlag(corc == CharOrCorp.Corp ? _corpID : _charID, (int)AssetStatus.States.ForSaleViaMarket, false);
                    Assets.SetProcessedFlag(corc == CharOrCorp.Corp ? _corpID : _charID, (int)AssetStatus.States.ForSaleViaContract, false);
                    Assets.SetProcessedFlag(corc == CharOrCorp.Corp ? _corpID : _charID, (int)AssetStatus.States.InTransit, false);

                    AssetList changes = new AssetList();

                    // Create an in-memory datatable with all of the changes required to the assets
                    // database in order to reflect the data in the xml file.
                    UpdateAssets(assetData, assetList, 0, corc, 0, changes);
                    // Use the currently active sell order to account for assets that appear to be
                    // missing.
                    UpdateStatus(0, 0, "Processing active sell orders", "", false);
                    Assets.ProcessSellOrders(assetData, changes, corc == CharOrCorp.Corp ? _corpID : _charID);
                    UpdateStatus(0, 0, "", "Complete", false);
                    // Use transactions that occured after the effective date of the asset data file
                    // to ensure that the asset list is as up-to-date as possible.
                    UpdateStatus(0, 0, "Updating assets from transactions that occur after " +
                        "the asset file's effective date", "", false);
                    long maxID = Assets.UpdateFromTransactions(assetData, changes, _charID, _corpID,
                        corc == CharOrCorp.Corp, dataDate);
                    if (corc == CharOrCorp.Char) { Settings.CharAssetsTransUpdateID = maxID; }
                    else { Settings.CorpAssetsTransUpdateID = maxID; }
                    UpdateStatus(0, 0, "", "Complete", false);

                    AssetList gained = new AssetList();
                    AssetList lost = new AssetList();
                    if ((corc == CharOrCorp.Char && Settings.FirstUpdateDoneAssetsChar) ||
                        (corc == CharOrCorp.Corp && Settings.FirstUpdateDoneAssetsCorp))
                    {
                        UpdateStatus(0, 0, "Analysing changes to assets", "", false);
                        Assets.AnalyseChanges(assetData, corc == CharOrCorp.Corp ? _corpID : _charID,
                            changes, out gained, out lost);
                        UpdateStatus(0, 0, "", "Complete", false);
                    }
                    // If this is the first assets update then we want to try and assign sensible cost
                    // values to assets that we have not yet got a value for.
                    if ((corc == CharOrCorp.Char && !Settings.FirstUpdateDoneAssetsChar) ||
                        (corc == CharOrCorp.Corp && !Settings.FirstUpdateDoneAssetsCorp))
                    {
                        Assets.AssignApproxCosts(assetData, corc == CharOrCorp.Corp ? _corpID : _charID);
                    }

                    if (corc == CharOrCorp.Char)
                    {
                        _unacknowledgedGains = gained;
                        _unacknowledgedLosses = lost;
                    }
                    else
                    {
                        _corpUnacknowledgedGains = gained;
                        _corpUnacknowledgedLosses = lost;
                    }

                    UpdateStatus(0, 0, "Updating assets database", "", false);
                    Assets.UpdateDatabase(assetData);
                    UpdateStatus(0, 0, "", "Complete", false);

                    // Set all 'for sale via contract' and 'in transit' assets in the database to processed.
                    // These types of assets would not be expected to show up in either the XML from the
                    // API or the list of current market orders.
                    // Any assets of these types that have been moved to a different state (e.g. in transit
                    // items that have arrived or contracts that have expired) will have been updated already
                    // in this method or ProcessSellOrders.
                    // Therefore, the ones that are left are still in the same situation as before.
                    // i.e. either 'for sale via contract' or 'in transit'.
                    // We set them to processed to prevent them from being removed along with other
                    // unprocessed assets.
                    Assets.SetProcessedFlag(corc == CharOrCorp.Corp ? _corpID : _charID,
                        (int)AssetStatus.States.ForSaleViaContract, true);
                    Assets.SetProcessedFlag(corc == CharOrCorp.Corp ? _corpID : _charID,
                        (int)AssetStatus.States.InTransit, true);
                    // Clear any remaining assets that have not been processed.
                    Assets.ClearUnProcessed(corc == CharOrCorp.Corp ? _corpID : _charID, false);
                    Assets.SetProcessedFlag(corc == CharOrCorp.Corp ? _corpID : _charID, 0, false);

                    UpdateStatus(0, 0, assetData.Count + " asset database entries modified.", "", false);

                    // Update the assets effective date setting.
                    // Also set the 'FirstUpdateDone' flag
                    if (corc == CharOrCorp.Char)
                    {
                        Settings.CharAssetsEffectiveDate = dataDate;
                        Settings.FirstUpdateDoneAssetsChar = true;
                    }
                    else
                    {
                        Settings.CorpAssetsEffectiveDate = dataDate;
                        if (!Settings.FirstUpdateDoneAssetsCorp)
                        {
                            Settings.FirstUpdateDoneAssetsCorp = true;
                            foreach (EVEAccount account in UserAccount.CurrentGroup.Accounts)
                            {
                                foreach (APICharacter character in account.Chars)
                                {
                                    if (character.CharID != _charID && character.CorpID == _corpID)
                                    {
                                        Settings.FirstUpdateDoneAssetsCorp = true;
                                    }
                                }
                            }
                        }
                    }

                    UpdateStatus(1, 1, "", "Complete", true);
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    // If we've caught a standard exception rather than an EMMA one then log it be creating a
                    // new exception.
                    // Note that we don't need to actually throw it..
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Error when processing assets data", ex);
                }

                UpdateStatus(-1, -1, "Error", ex.Message, true);
                SetLastAPIUpdateError(corc, APIDataType.Assets, ex.Message);
            }

            if (UpdateEvent != null)
            {
                if (_unacknowledgedLosses == null) { _unacknowledgedLosses = new AssetList(); }
                if (_unacknowledgedGains == null) { _unacknowledgedGains = new AssetList(); }
                if (_corpUnacknowledgedLosses == null) { _corpUnacknowledgedLosses = new AssetList(); }
                if (_corpUnacknowledgedGains == null) { _corpUnacknowledgedGains = new AssetList(); }

                if ((corc == CharOrCorp.Char && _unacknowledgedLosses.Count + _unacknowledgedGains.Count == 0) ||
                    (corc == CharOrCorp.Corp && _corpUnacknowledgedGains.Count + _corpUnacknowledgedLosses.Count == 0))
                {
                    UpdateEvent(this, new APIUpdateEventArgs(APIDataType.Assets,
                        corc == CharOrCorp.Char ? _charID : _corpID,
                        APIUpdateEventType.UpdateCompleted));
                }
                else
                {
                    SetLastAPIUpdateError(corc, APIDataType.Assets, "AWAITING ACKNOWLEDGEMENT");
                    UpdateEvent(this, new APIUpdateEventArgs(APIDataType.Assets,
                        corc == CharOrCorp.Char ? _charID : _corpID,
                        APIUpdateEventType.AssetsAwaitingAcknowledgement));
                }
            }
        }
        /// <summary>
        /// Download XML from the Eve API
        /// </summary>
        /// <param name="corc"></param>
        /// <param name="type"></param>
        private void RetrieveAPIXML(CharOrCorp corc, APIDataType type)
        {
            TimeSpan timeBetweenUpdates = UserAccount.Settings.GetAPIUpdatePeriod(type);
            DateTime earliestUpdate = GetLastAPIUpdateTime(corc, type).Add(timeBetweenUpdates);
            DateTime dataDate = DateTime.MinValue;

            short walletID = corc == CharOrCorp.Corp ? (short)1000 : (short)0;
            decimal beforeID = 0;
            bool finishedDownloading = false;
            bool walletExhausted = false;
            bool noData = true;
            bool abort = false;
            string xmlFile = "";
            int rowCount = 200;
            XmlDocument xml = null;

            long currentMaxID = 0;
            if (type == APIDataType.Transactions) { currentMaxID = _apiSettings.GetHighestID(corc, APIDataType.Transactions); }
            if (type == APIDataType.Journal) { currentMaxID = _apiSettings.GetHighestID(corc, APIDataType.Journal); }

            try
            {
                // Make sure we don't download if we've already done so recently.
                if (earliestUpdate.CompareTo(DateTime.UtcNow) > 0)
                {
                    throw new EMMAEveAPIException(ExceptionSeverity.Warning, 1000, "Cannot get " +
                        type.ToString() + " data so soon after the last update. Wait until at least " +
                        earliestUpdate.ToLongTimeString() + " before updating.");
                }

                while (!finishedDownloading)
                {
                    try
                    {
                        // Set parameters that will be passed to the API
                        #region Set parameters
                        StringBuilder parameters = new StringBuilder();
                        parameters.Append("keyID=");
                        parameters.Append(_userID);
                        parameters.Append("&vCode=");
                        parameters.Append(_apiKey);
                        parameters.Append("&characterID=");
                        parameters.Append(_charID);
                        if (type == APIDataType.Journal || type == APIDataType.Transactions)
                        {
                            parameters.Append("&rowCount=");
                            parameters.Append(rowCount);
                            if (walletID != 0)
                            {
                                parameters.Append("&accountKey=");
                                parameters.Append(walletID);
                            }
                            if (beforeID != 0)
                            {
                                parameters.Append("&fromID=");
                                parameters.Append(beforeID);
                            }
                        }
                        if (type == APIDataType.Assets || type == APIDataType.Orders)
                        {
                            parameters.Append("&version=2");
                        }
                        #endregion

                        xml = EveAPI.GetXml(EveAPI.URL_EveApiHTTPS + EveAPI.GetURL(corc, type),
                            parameters.ToString(), ref xmlFile);
                        XmlNodeList tmp = EveAPI.GetResults(xml);
                        if (xmlFile.Length > 0)
                        {
                            lock (_unprocessedXMLFiles) { _unprocessedXMLFiles.Enqueue(xmlFile); }
                            noData = false;
                        }
                        if (type == APIDataType.Journal || type == APIDataType.Transactions)
                        {
                            if (tmp.Count < rowCount) { walletExhausted = true; }
                        }

                        // Set the last update time based upon the 'cached until'
                        // time rather than the actual time the update occured
                        // Note we could modify the API update period timer instead but
                        // that would cause other issues. It's better for the user if
                        // we just do things this way.
                        if (type == APIDataType.Transactions)
                        {
                            // Transactions XML often gives a cache expiry date time that is too soon.
                            // If we try and update again when it says then it will fail so just wait
                            // for the usual 1 hour. (Or whatever the user has it set to)
                            SetLastAPIUpdateTime(corc, type, DateTime.UtcNow);
                        }
                        else
                        {
                            DateTime nextAllowed = EveAPI.GetCachedUntilTime(xml);
                            SetLastAPIUpdateTime(corc, type, nextAllowed.Subtract(
                                UserAccount.Settings.GetAPIUpdatePeriod(type)));
                        }

                        // If we've been successfull in getting data and this is a corporate data request
                        // then make sure we've got access set to true;
                        if (corc == CharOrCorp.Corp)
                        {
                            Settings.SetCorpAPIAccess(type, true);
                        }

                    }
                    catch (EMMAEveAPIException emmaApiEx)
                    {
                        #region API Error Handling
                        if (emmaApiEx.EveCode == 100)
                        {
                            // Error code 100 indicates that a 'beforeRefID' has been passed in when the
                            // api was not expecting it. If we know for sure that we've already called
                            // the api once then have to abandon the data we have got so far.
                            // (No idea why the API does this, it just happens from time to time)
                            if (!noData)
                            {
                                walletExhausted = true;
                                //SetLastAPIUpdateError(corc, type, "Eve API Error 100");
                            }
                            else
                            {
                                throw emmaApiEx;
                            }
                        }
                        else if (emmaApiEx.EveCode == 101 || emmaApiEx.EveCode == 102 ||
                            emmaApiEx.EveCode == 103 || emmaApiEx.EveCode == 116 || emmaApiEx.EveCode == 117)
                        {
                            // Data already retrieved
                            string err = emmaApiEx.EveDescription;

                            // If there is a cachedUntil tag, dont try and get data again until
                            // after it has expired.
                            DateTime nextAllowed = EveAPI.GetCachedUntilTime(xml);
                            SetLastAPIUpdateTime(corc, type, nextAllowed.Subtract(
                                UserAccount.Settings.GetAPIUpdatePeriod(type)));
                            if (noData)
                            {
                                SetLastAPIUpdateError(corc, type,
                                    "The Eve API reports that this data has already been retrieved, no update has occured.");
                            }
                            walletExhausted = true;
                        }
                        else if (emmaApiEx.EveCode == 200)
                        {
                            // Security level not high enough
                            SetLastAPIUpdateError(corc, type,
                                "You must enter your FULL api key to retrieve financial and asset data.\r\n" +
                                "Use the 'manage group' button to correct this.");
                            abort = true;
                        }
                        else if (emmaApiEx.EveCode == 206 || emmaApiEx.EveCode == 208 ||
                            emmaApiEx.EveCode == 209 || emmaApiEx.EveCode == 213)
                        {
                            // Character does not have required corporate role.
                            Settings.SetCorpAPIAccess(type, false);
                            SetAPIAutoUpdate(corc, type, false);
                            SetLastAPIUpdateError(corc, type, emmaApiEx.Message);
                            abort = true;
                        }
                        else
                        {
                            throw emmaApiEx;
                        }
                        #endregion
                    }

                    /// By default, we're now done..
                    finishedDownloading = true;

                    // However, for some update types, we'll want to go round a few more times
                    #region Determine if we should access API again with different variables
                    if (!abort)
                    {
                        if (type == APIDataType.Journal || type == APIDataType.Transactions)
                        {
                            //XmlNode lastRowNode = xml.SelectSingleNode(@"/eveapi/result/rowset/row[last()]");
                            XmlNodeList results = xml.SelectNodes(@"/eveapi/result/rowset/row");
                            long minID = long.MaxValue;
                            if (results != null)
                            {
                                foreach (XmlNode node in results)
                                {
                                    string idAttribName = "";
                                    if (type == APIDataType.Journal) { idAttribName = "@refID"; }
                                    if (type == APIDataType.Transactions) { idAttribName = "@transactionID"; }
                                    long val = long.Parse(node.SelectSingleNode(idAttribName).Value);
                                    if (val < minID) { minID = val; }
                                }
                            }

                            if (minID != long.MaxValue && minID > currentMaxID)
                            {
                                beforeID = minID;
                            }
                            else { walletExhausted = true; }
                            if (!walletExhausted) { finishedDownloading = false; }
                            if (walletExhausted && corc == CharOrCorp.Corp && walletID < 1006)
                            {
                                walletID++;
                                beforeID = 0;
                                finishedDownloading = false;
                            }
                        }
                    }
                    #endregion
                }

            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    // If we've caught a standard exception rather than an EMMA one then log it be creating a
                    // new exception.
                    // Note that we don't need to actually throw it..
                    emmaEx = new EMMAException(ExceptionSeverity.Error,
                        "Error when downloading " + type.ToString() + " from Eve API", ex);
                }

                SetLastAPIUpdateError(corc, type, ex.Message);
                noData = true;
            }

            // If we have not retrieved any data at all then mark the update as completed.
            if (noData)
            {
                if (UpdateEvent != null)
                {
                    UpdateEvent(this, new APIUpdateEventArgs(type,
                        corc == CharOrCorp.Char ? _charID : _corpID,
                        APIUpdateEventType.UpdateCompleted));
                }
            }
        }
        private bool SaveFilter()
        {
            bool done = false;

            if (txtLocationName.Text.Equals(""))
            {
                MessageBox.Show("You must enter a name for this location filter.", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                try
                {
                    _filterDetail.Name = txtLocationName.Text;
                    _filterDetail.Range = OrderRange.GetRangeFromText(cmbRange.Items[cmbRange.SelectedIndex].ToString());
                    // If range is region wide then remove the station and just add it's region to the filter
                    if (_filterDetail.Range == OrderRange.GetRangeFromText("Region"))
                    {
                        int region = Stations.GetStation(_stations[0].stationID).regionID;
                        _stations.Clear();
                        for (int i = 0; i < chkRegions.Items.Count; i++)
                        {
                            chkRegions.SetSelected(i, true);
                            if (((MiniRegion)chkRegions.SelectedItem)._regionID == region)
                            {
                                chkRegions.SetItemChecked(i, true);
                            }
                        }
                    }
                    List<long> regionIDs = new List<long>();

                    foreach (object region in chkRegions.CheckedItems)
                    {
                        MiniRegion regionData = ((MiniRegion)region);
                        regionIDs.Add(regionData._regionID);
                    }
                    _filterDetail.Regions = regionIDs;

                    List<long> stationIDs = new List<long>();
                    if (_stations.Count > 1)
                    {
                        // If more than one station selected then simply add thier IDs to the filter
                        foreach (EveDataSet.staStationsRow station in _stations)
                        {
                            stationIDs.Add(station.stationID);
                        }
                        _filterDetail.Stations = stationIDs;
                        _filterDetail.StationID = 0;
                    }
                    else if (_stations.Count == 1)
                    {
                        // If only one station selected then we need to set the station ID list based upon
                        // the selected range.
                        _filterDetail.Stations = new List<long>();
                        _filterDetail.StationID = _stations[0].stationID;
                        int range = _filterDetail.Range;
                        List<long> systemIDs = new List<long>();
                        if (range > 0)
                        {
                            // If range is greater than 0 then find the IDs of any systems within range.
                            systemIDs = SolarSystemDistances.GetSystemsInRange(
                               Stations.GetStation(_filterDetail.StationID).solarSystemID, range);
                        }
                        if (range != -1)
                        {
                            // If range is anything except -1 then add the stations in all of the solar systems
                            // in range to the list of stations in the filter.
                            systemIDs.Add(Stations.GetStation(_filterDetail.StationID).solarSystemID);
                            foreach (long systemID in systemIDs)
                            {
                                stationIDs.AddRange(Stations.GetStationsInSystem(systemID));
                            }
                        }
                        else
                        {
                            // If the range is -1 then we just want the one station...
                            stationIDs.Add(_filterDetail.StationID);
                        }
                        _filterDetail.Stations = stationIDs;
                    }

                    GroupLocations.StoreLocation(_filterDetail);
                    done = true;
                }
                catch (Exception ex)
                {
                    EMMAException emmaEx = ex as EMMAException;
                    if (emmaEx == null)
                    {
                        emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem storing custom location.", ex);
                    }
                    MessageBox.Show(emmaEx.Message + ": " + ex.Message, "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return done;
        }
        private void LoadOldEMMAData(object parameterData)
        {
            LoadOldDataParams parameters = (LoadOldDataParams)parameterData;
            string tmpLoadDir = parameters.dataDirectory;
            APICharacter character = parameters.character;
            CharOrCorp corc = parameters.corc;

            try
            {
                int maxStatus = 6;
                UpdateStatus(1, maxStatus, "Importing Data", "Loading Journal (" +
                    (new FileInfo(tmpLoadDir + "Journal.xml").Length / 1024).ToString() + " Kb)", false);
                Journal journ = new Journal();
                journ.StatusChange += new StatusChangeHandler(child_StatusChange);
                journ.LoadOldEmmaXML(tmpLoadDir + "Journal.xml", character.CharID,
                    corc == CharOrCorp.Corp ? character.CorpID : 0);
                UpdateStatus(2, maxStatus, "Importing Data", "Loading Transactions (" +
                    (new FileInfo(tmpLoadDir + "Transactions.xml").Length / 1024).ToString() + " Kb)", false);
                Transactions trans = new Transactions();
                trans.StatusChange += new StatusChangeHandler(child_StatusChange);
                trans.LoadOldEmmaXML(tmpLoadDir + "Transactions.xml", character.CharID,
                    corc == CharOrCorp.Corp ? character.CorpID : 0);
                UpdateStatus(3, maxStatus, "Importing Data", "Loading Contracts (" +
                    (new FileInfo(tmpLoadDir + "Contracts.xml").Length / 1024).ToString() + " Kb) and Contract " +
                    "Items (" + (new FileInfo(tmpLoadDir + "ContractItems.xml").Length / 1024).ToString() + " Kb)",
                    false);
                Contracts cont = new Contracts();
                cont.StatusChange += new StatusChangeHandler(child_StatusChange);
                cont.LoadOldEmmaXML(tmpLoadDir + "Contracts.xml", tmpLoadDir + "ContractItems.xml",
                    corc == CharOrCorp.Char ? character.CharID : character.CorpID);
                // Just need this 'if' for backwards compatibility...
                if (File.Exists(tmpLoadDir + "ShareTrans.xml"))
                {
                    UpdateStatus(4, maxStatus, "Importing Data", "Loading Share Transactions (" +
                        (new FileInfo(tmpLoadDir + "ShareTrans.xml").Length / 1024).ToString() + " Kb)", false);
                    ShareTransactions shareTrans = new ShareTransactions();
                    shareTrans.StatusChange += new StatusChangeHandler(child_StatusChange);
                    shareTrans.LoadOldEmmaXML(tmpLoadDir + "ShareTrans.xml", UserAccount.CurrentGroup.ID);

                    /*
                    UpdateStatus(5, maxStatus, "Importing Data", "Loading Characters (" +
                        (new FileInfo(tmpLoadDir + "APIKeyInfo.xml").Length / 1024).ToString() + " Kb)", false);
                    Names.LoadOldEmmaXML(tmpLoadDir + "APIKeyInfo.xml");
                    UpdateStatus(6, maxStatus, "Importing Data", "Loading Traded Items (" +
                        (new FileInfo(tmpLoadDir + "TradedItems.xml").Length / 1024).ToString() + " Kb)", false);
                    UserAccount.CurrentGroup.ItemsTraded.LoadOldEmmaXML(tmpLoadDir + "TradedItems.xml");
                    */
                }

                UpdateStatus(maxStatus - 1, maxStatus, "Tidying up", "", false);
                Directory.Delete(tmpLoadDir, true);
                UpdateStatus(maxStatus, maxStatus, "Import Complete", "", true);

            }
            catch (ThreadAbortException abortEx)
            {
                // User has closed the progress dialog so just throw the exception to the next level.
                throw abortEx;
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem importing old EMMA data", ex);
                }
                UpdateStatus(-1, -1, "Error", ex.Message, true);
            }
        }
        private void ViewUnacknowledgedOrders_Load(object sender, EventArgs e)
        {
            try
            {
                _orders = new OrdersList();
                //_ordersBindingSource = new BindingSource();
                //_ordersBindingSource.DataSource = _orders;

                DataGridViewCellStyle iskStyle = new DataGridViewCellStyle(PriceColumn.DefaultCellStyle);
                iskStyle.Format = IskAmount.FormatString();
                PriceColumn.DefaultCellStyle = iskStyle;
                DataGridViewCellStyle dayStyle = new DataGridViewCellStyle(DurationColumn.DefaultCellStyle);
                dayStyle.Format = "# Days;-# Days;# Days";
                DurationColumn.DefaultCellStyle = dayStyle;

                ordersGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                ordersGrid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
                ordersGrid.AutoGenerateColumns = false;

                //ordersGrid.DataSource = _ordersBindingSource;
                DateTimeColmun.DataPropertyName = "Date";
                OwnerColumn.DataPropertyName = "Owner";
                ItemColumn.DataPropertyName = "Item";
                PriceColumn.DataPropertyName = "Price";
                StationColumn.DataPropertyName = "Station";
                TypeColumn.DataPropertyName = "Type";
                QuantityColumn.DataPropertyName = "TotalVol";
                RangeColumn.DataPropertyName = "RangeText";
                DurationColumn.DataPropertyName = "Duration";
                AcknowledgeColumn.Image = icons.Images["tick.gif"];
                ordersGrid.CellContentClick += new DataGridViewCellEventHandler(ordersGrid_CellContentClick);

                //ordersGrid.Sort(DateTimeColmun, ListSortDirection.Ascending);
                List<SortInfo> sort = new List<SortInfo>();
                sort.Add(new SortInfo(0, "Date"));
                ordersGrid.GridSortInfo = sort;

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

                _lastNumberOfOrders = 0;
                this.FormClosing += new FormClosingEventHandler(ViewUnacknowledgedOrders_FormClosing);
                DisplayOrders();
            }
            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 orders form", ex);
                }
                MessageBox.Show("Problem setting up unacknowledged orders view.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void DoExport2(object datagridview)
        {
            // Just wait to make sure the progress dialog is displayed
            Thread.Sleep(100);
            DataGridView table = datagridview as DataGridView;

            try
            {
                string filename = _filename;
                string directory = filename.Remove(filename.LastIndexOf(Path.DirectorySeparatorChar));
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                UserAccount.Settings.CSVExportDir = directory;
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }

                StringBuilder line = new StringBuilder();
                StreamWriter writer = File.CreateText(filename);
                try
                {
                    List<int> visibleColumns = new List<int>();

                    // Get column names..
                    UpdateStatus(0, table.Rows.Count + 1, "Writing column headers..", "", false);
                    for (int col = 0; col < table.Columns.Count; col++)
                    {
                        DataGridViewColumn column = table.Columns[col];
                        if (column.Visible)
                        {
                            if (line.Length > 0) { line.Append(","); }
                            line.Append(column.HeaderText);
                            visibleColumns.Add(col);
                        }
                    }
                    UpdateStatus(1, table.Rows.Count + 1, "Writing column headers..", "Done", false);
                    // ..then output the data.
                    for (int row = 0; row < table.Rows.Count; row++)
                    {
                        UpdateStatus(row + 1, table.Rows.Count + 1, "Writing data..", "", false);
                        line = new StringBuilder();
                        for (int i = 0; i < visibleColumns.Count; i++)
                        {
                            if (line.Length > 0) { line.Append(","); }
                            line.Append(table[visibleColumns[i], row].Value.ToString());
                        }
                        writer.WriteLine(line.ToString());
                    }
                    UpdateStatus(0, 0, "", "Done", false);
                }
                finally
                {
                    writer.Close();
                }

                UpdateStatus(0, 0, "CSV created successfully", "", true);
            }
            catch (Exception ex)
            {
                // Creating new EMMAexception will cause error to be logged.
                EMMAException emmaex = ex as EMMAException;
                if (emmaex == null)
                {
                    emmaex = new EMMAException(ExceptionSeverity.Error, "Error exporting to CSV", ex);
                }
                UpdateStatus(0, 0, "Error", "Problem exporting to CSV.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", true);
            }
        }
        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);
            }
        }
        private bool StoreData()
        {
            bool retVal = true;

            try
            {
                _corpData.Name = txtName.Text;
                _corpData.Description = txtDescription.Text;
                _corpData.Ticker = txtTicker.Text;
                _corpData.NAVDate = dtpNavDate.Value.ToUniversalTime();
                _corpData.CEO = txtCEO.Text;
                _corpData.Bank = chkBank.Checked;
                _corpData.PayoutPeriod = (CorpPayoutPeriod)cmbPayoutPeriod.SelectedValue;
                _corpData.CorpRiskRating = (RiskRating)cmbRiskRating.SelectedValue;

                PublicCorps.StoreCorp(_corpData);

                if (_corpData.ShareValue != _oldShareVal)
                {
                    ShareValueHistory.SetShareValue(_corpData.ID, DateTime.UtcNow, _corpData.ShareValue);
                }
                if (_corpData.Bank && _corpData.ExpectedPayout != _oldInterestRate)
                {
                    if (MessageBox.Show("The interest rate has been changed.\r\nDo you wish to recalculate all " +
                        "historical interest payments using the new rate?", "Question",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        BankAccounts.ClearAllInterestPayments(_corpData.ID);
                    }
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaex = ex as EMMAException;
                if(emmaex == null)
                {
                    emmaex = new EMMAException(ExceptionSeverity.Error, "Problem storing public corp data", ex);
                }
                MessageBox.Show("Error storing corp data: " + ex.Message, "Error", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                retVal = false;
            }

            return retVal;
        }
        private void MaintBankAccount_Load(object sender, EventArgs e)
        {
            try
            {
                if (_oldCorpData != null)
                {
                    cmbAccountCorp.Enabled = false;
                    if (_oldCorpData.OwnerID != 0)
                    {
                        cmbOwner.Enabled = false;
                    }
                }

                _corpData = PublicCorps.GetAll(true, false);
                _corpData.Sort("Name ASC");
                cmbAccountCorp.DisplayMember = "Name";
                cmbAccountCorp.ValueMember = "ID";
                cmbAccountCorp.DataSource = _corpData;
                if (_oldCorpData != null)
                {
                    cmbAccountCorp.SelectedValue = _oldCorp;
                }

                cmbAccountCorp.SelectedIndexChanged += new EventHandler(cmbAccountCorp_SelectedIndexChanged);
                cmbOwner.SelectedIndexChanged += new EventHandler(cmbOwner_SelectedIndexChanged);

                if (_corp == null)
                {
                    _corp = new PublicCorp();
                }
                CorpChanged();

                //DisplayOwners();
                //DisplayData();
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem loading " +
                        "bank account window", ex);
                }
                MessageBox.Show("Problem loading bank account window: " + ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void DisplayData()
        {
            try
            {
                _accountExists = _oldCorpData != null;

                if (cmbOwner.SelectedValue != null && (_oldOwner == 0 || _oldCorpData == null))
                {
                    long newOwner = ((CharCorp)cmbOwner.SelectedValue).ID;
                    //if (_lastOwner > 0 && _lastOwner != newOwner && _lastCorp > 0)
                    //{
                    //    BankAccounts.DeleteAccount(_lastCorp, _lastOwner);
                    //}
                    _corp.OwnerID = newOwner;
                    //_corp.ReloadBankAccountDetails();
                }

                _lastOwner = _corp.OwnerID;

                if ((_oldCorpData == null || _oldOwner <= 0) && _corp.ID > 0 && _corp.OwnerID > 0)
                {
                    // Account does not exist, we must create it.
                    BankAccounts.StoreAccount(_corp, UserAccount.CurrentGroup.ID, _corp.OwnerID);
                    _accountExists = true;
                }

                if (_accountExists)
                {
                    btnDeposit.Enabled = true;
                    btnWithdraw.Enabled = true;
                    btnRecalcInterest.Enabled = true;
                    btnAdjust.Enabled = true;
                    btnDelete.Enabled = true;

                    lblBalance.Text = new IskAmount(_corp.AmountInAccount).ToString();
                    lblInterest.Text = new IskAmount(_corp.TotalInterest).ToString();

                    _trans = BankAccounts.GetAccountTransactions(_corp.BankAccountID);
                    _bindingSource.DataSource = _trans;
                    SetFilter();

                    DataGridViewCellStyle iskStyle = new DataGridViewCellStyle(AmountColumn.DefaultCellStyle);
                    iskStyle.Format = IskAmount.FormatString();
                    AmountColumn.DefaultCellStyle = iskStyle;

                    TransHistoryGrid.AutoGenerateColumns = false;
                    DateColumn.DataPropertyName = "Date";
                    AmountColumn.DataPropertyName = "Change";
                    TypeColumn.DataPropertyName = "TypeDescription";
                    TransHistoryGrid.DataSource = _bindingSource;

                    DataGridViewColumn sortColumn = DateColumn;
                    ListSortDirection sortDirection = ListSortDirection.Descending;
                    if (TransHistoryGrid.SortedColumn != null) { sortColumn = TransHistoryGrid.SortedColumn; }
                    if (TransHistoryGrid.SortOrder == SortOrder.Ascending)
                    {
                        sortDirection = ListSortDirection.Ascending;
                    }
                    TransHistoryGrid.Sort(sortColumn, sortDirection);
                }
                else
                {
                    btnDeposit.Enabled = false;
                    btnWithdraw.Enabled = false;
                    btnRecalcInterest.Enabled = false;
                    btnAdjust.Enabled = false;
                    btnDelete.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem refreshing " +
                        "bank account window", ex);
                }
                MessageBox.Show("Problem refreshing bank account window: " + ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }
        private bool Store()
        {
            bool retVal = true ;

            try
            {
                _dividend.Date = dtpDate.Value;
                _dividend.CorpID = (int)cmbCorp.SelectedValue;
                Dividends.StoreDividend(_dividend);
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem storing dividend data", ex);
                }
                MessageBox.Show("Error storing dividend data: " + ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                retVal = false;
            }

            return retVal;
        }
        private void ViewAssets_Load(object sender, EventArgs e)
        {
            Diagnostics.ResetAllTimers();
            try
            {
                Diagnostics.StartTimer("ViewAssets");
                Diagnostics.StartTimer("ViewAssets.Part1");
                DataGridViewCellStyle style = new DataGridViewCellStyle(CostColumn.DefaultCellStyle);
                style.Format = IskAmount.FormatString();
                CostColumn.DefaultCellStyle = style;

                _assets = new AssetList();
                _assetsBindingSource = new BindingSource();
                _assetsBindingSource.DataSource = _assets;

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

                AssetsGrid.DataSource = _assetsBindingSource;
                OwnerColumn.DataPropertyName = "Owner";
                ItemColumn.DataPropertyName = "Item";
                LocationColumn.DataPropertyName = "Location";
                QuantityColumn.DataPropertyName = "Quantity";
                AutoConExcludeColumn.DataPropertyName = "AutoConExclude";
                ReprocessorExcludeColumn.DataPropertyName = "ReprocessorExclude";
                StatusColumn.DataPropertyName = "Status";
                CostColumn.DataPropertyName = UserAccount.Settings.CalcCostInAssetView ? "UnitBuyPrice" : "PureUnitBuyPrice";
                //_regularStyle = OwnerColumn.DefaultCellStyle.Clone();
                //_inTransitStyle = OwnerColumn.DefaultCellStyle.Clone();
                //_inTransitStyle.BackColor = Color.Yellow;

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

                _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;
                Diagnostics.StopTimer("ViewAssets.Part1");

                Diagnostics.StartTimer("ViewAssets.Part2");
                List<CharCorpOption> charcorps = UserAccount.CurrentGroup.GetCharCorpOptions(APIDataType.Assets);
                _corporateOwners = new List<long>();
                _personalOwners = new List<long>();
                foreach (CharCorpOption chop in charcorps)
                {
                    if (chop.Corp)
                    {
                        _corporateOwners.Add(chop.CharacterObj.CorpID);
                    }
                    else
                    {
                        _personalOwners.Add(chop.CharacterObj.CharID);
                    }
                }
                cmbOwner.DisplayMember = "Name";
                cmbOwner.ValueMember = "Data";
                charcorps.Sort();
                cmbOwner.DataSource = charcorps;
                cmbOwner.SelectedValue = 0;
                cmbOwner.Enabled = false;
                cmbOwner.SelectedIndexChanged += new EventHandler(cmbOwner_SelectedIndexChanged);
                chkIngoreOwner.Checked = true;
                chkIngoreOwner.CheckedChanged += new EventHandler(chkIngoreOwner_CheckedChanged);
                chkCalcCost.Checked = UserAccount.Settings.CalcCostInAssetView;
                chkCalcCost.CheckedChanged += new EventHandler(chkCalcCost_CheckedChanged);
                Diagnostics.StopTimer("ViewAssets.Part2");

                Diagnostics.StartTimer("ViewAssets.Part3");
                //DisplayAssets();
                BuildAccessList();
                DisplayTree();
                Diagnostics.StopTimer("ViewAssets.Part3");

                assetsTree.AfterExpand += new TreeViewEventHandler(assetsTree_AfterExpand);
                assetsTree.AfterSelect += new TreeViewEventHandler(assetsTree_AfterSelect);
                this.FormClosing += new FormClosingEventHandler(ViewAssets_FormClosing);

                Diagnostics.StopTimer("ViewAssets");
                Diagnostics.DisplayDiag("View assets setup time: " +
                    Diagnostics.GetRunningTime("ViewAssets").ToString() +
                    "\r\n  Initalise: " + Diagnostics.GetRunningTime("ViewAssets.Part1").ToString() +
                    "\r\n  Setup owners: " + Diagnostics.GetRunningTime("ViewAssets.Part2").ToString() +
                    "\r\n  Display Tree: " + Diagnostics.GetRunningTime("ViewAssets.Part3").ToString());
            }
            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 assets form", ex);
                }
                MessageBox.Show("Problem setting up assets view.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void UpdateOrdersFromXML(CharOrCorp corc, XmlDocument fileXML)
        {
            EMMADataSet.OrdersDataTable orderData = new EMMADataSet.OrdersDataTable();
            int added = 0;
            int updated = 0;

            try
            {

                Orders.SetProcessed(corc == CharOrCorp.Corp ? _corpID : _charID, false);

                XmlNodeList orderEntries = null;
                XmlDocument xml = new XmlDocument();

                UpdateStatus(0, 1, "Getting orders from file", "", false);
                orderEntries = EveAPI.GetResults(fileXML);
                UpdateStatus(1, 1, "", orderEntries.Count + " orders found in file.", false);

                if (orderEntries != null && orderEntries.Count > 0)
                {
                    UpdateStatus(0, orderEntries.Count, "Processing orders", "", false);

                    foreach (XmlNode orderEntry in orderEntries)
                    {
                        EMMADataSet.OrdersRow orderRow = BuildOrdersRow(orderData, orderEntry, corc);
                        int id = 0;

                        if (!Orders.Exists(orderData, orderRow, ref id, _corpID, _charID))
                        {
                            // Order does not exist in the database so add it.
                            orderData.AddOrdersRow(orderRow);
                            if (orderRow.OrderState == (short)OrderState.ExpiredOrFilled)
                            {
                                bool notify = false;
                                notify = UserAccount.CurrentGroup.Settings.OrdersNotifyEnabled &&
                                    ((UserAccount.CurrentGroup.Settings.OrdersNotifyBuy && orderRow.BuyOrder) ||
                                    (UserAccount.CurrentGroup.Settings.OrdersNotifySell && !orderRow.BuyOrder));
                                if (notify)
                                {
                                    orderRow.OrderState = (short)OrderState.ExpiredOrFilledAndUnacknowledged;
                                }
                                else
                                {
                                    orderRow.OrderState = (short)OrderState.ExpiredOrFilledAndAcknowledged;
                                }
                            }
                            added++;
                        }
                        else
                        {
                            EMMADataSet.OrdersRow oldRow = orderData.FindByID(id);

                            if (oldRow.TotalVol == orderRow.TotalVol &&
                                oldRow.RemainingVol == orderRow.RemainingVol &&
                                oldRow.MinVolume == orderRow.MinVolume && oldRow.Range == orderRow.Range &&
                                oldRow.Duration == orderRow.Duration && oldRow.Escrow == orderRow.Escrow &&
                                oldRow.Price == orderRow.Price && oldRow.OrderState == orderRow.OrderState &&
                                oldRow.EveOrderID == orderRow.EveOrderID)
                            {
                                // If the order from the XML exactly matches what we have in the database
                                // then just set the processed flag and remove it from the orderData table
                                // without setting it to be removed from the database.
                                //Orders.SetProcessedByID(oldRow.ID, true);
                                orderData.RemoveOrdersRow(oldRow);
                            }
                            else
                            {
                                // Set the row to processed right now.
                                oldRow.Processed = true;
                                // Accept the changes to the row (will only be the processed flag at
                                // this point) and set the processed flag on the database.
                                // This will prevent the row from being double matched with another
                                // order later.
                                // The 'accept changes' will prevent the concurency error that we
                                // would get if we only updated the processed flag on the database
                                // side.
                                oldRow.AcceptChanges();
                                //Orders.SetProcessedByID(oldRow.ID, true);

                                // If the order was active and is now completed/expired then flag it for
                                // the unacknowledged orders viewer to display.
                                bool notify = false;
                                notify = UserAccount.CurrentGroup.Settings.OrdersNotifyEnabled &&
                                    ((UserAccount.CurrentGroup.Settings.OrdersNotifyBuy && orderRow.BuyOrder) ||
                                    (UserAccount.CurrentGroup.Settings.OrdersNotifySell && !orderRow.BuyOrder));

                                if (/*orderRow.RemainingVol == 0 &&*/
                                    orderRow.OrderState == (short)OrderState.ExpiredOrFilled &&
                                    (oldRow.OrderState == (short)OrderState.Active ||
                                    oldRow.OrderState == (short)OrderState.ExpiredOrFilled))
                                {
                                    if (notify)
                                    {
                                        oldRow.OrderState = (short)OrderState.ExpiredOrFilledAndUnacknowledged;
                                        // No longer needed as the unacknowledged orders form is displayed/refreshed
                                        // as needed when refreshing the main form after an update is complete.
                                        //if (UpdateEvent != null)
                                        //{
                                        //    UpdateEvent(this, new APIUpdateEventArgs(APIDataType.Orders,
                                        //        corc == CharOrCorp.Corp ? _corpID : _charID,
                                        //        APIUpdateEventType.OrderHasExpiredOrCompleted));
                                        //}
                                    }
                                    else
                                    {
                                        oldRow.OrderState = (short)OrderState.ExpiredOrFilledAndAcknowledged;
                                    }
                                }
                                else if (orderRow.OrderState != (short)OrderState.ExpiredOrFilled)
                                {
                                    oldRow.OrderState = orderRow.OrderState;
                                }

                                if (oldRow.TotalVol != orderRow.TotalVol ||
                                    oldRow.RemainingVol != orderRow.RemainingVol ||
                                    oldRow.MinVolume != orderRow.MinVolume || oldRow.Range != orderRow.Range ||
                                    oldRow.Duration != orderRow.Duration || oldRow.Escrow != orderRow.Escrow ||
                                    oldRow.Price != orderRow.Price || oldRow.EveOrderID != orderRow.EveOrderID)
                                {
                                    oldRow.TotalVol = orderRow.TotalVol;
                                    oldRow.RemainingVol = orderRow.RemainingVol;
                                    oldRow.MinVolume = orderRow.MinVolume;
                                    oldRow.Range = orderRow.Range;
                                    oldRow.Duration = orderRow.Duration;
                                    oldRow.Escrow = orderRow.Escrow;
                                    oldRow.Price = orderRow.Price;
                                    oldRow.EveOrderID = orderRow.EveOrderID;
                                    // Note, only other fields are 'buyOrder' and 'issued'. Neither of which we want to change.
                                    updated++;
                                }
                            }
                        }

                        UpdateStatus(added + updated, orderEntries.Count, "", "", false);
                    }
                }

                UpdateStatus(0, 0, added + " orders added to database.", "", false);
                UpdateStatus(0, 0, updated + " orders updated.", "", true);

                if (orderData.Count > 0)
                {
                    Orders.Store(orderData);
                }

                Orders.FinishUnProcessed(corc == CharOrCorp.Corp ? _corpID : _charID);
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    // If we've caught a standard exception rather than an EMMA one then log it by creating a
                    // new exception.
                    // Note that we don't need to actually throw it..
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Error when adding market orders", ex);
                }

                SetLastAPIUpdateError(corc, APIDataType.Orders, ex.Message);
                UpdateStatus(-1, 0, "Error", ex.Message, true);
            }

            if (UpdateEvent != null)
            {
                UpdateEvent(this, new APIUpdateEventArgs(APIDataType.Orders,
                    corc == CharOrCorp.Char ? _charID : _corpID,
                    APIUpdateEventType.UpdateCompleted));
            }
        }
        /// <summary>
        /// Update the database transactions table from the specified XML.
        /// </summary>
        /// <param name="corc"></param>
        /// <param name="fileXML"></param>
        /// <returns></returns>
        private int UpdateTransactionsFromXML(CharOrCorp corc, XmlDocument fileXML, short walletID)
        {
            int retVal = 0;
            EMMADataSet.TransactionsDataTable transData = new EMMADataSet.TransactionsDataTable();
            long highestIDSoFar = _apiSettings.GetHighestID(corc, APIDataType.Transactions);
            long highestID = 0;
            DateTime ticker = DateTime.UtcNow.AddSeconds(-10);

            try
            {
                int updated = 0;

                XmlNodeList transEntries = null;
                XmlDocument xml = new XmlDocument();

                UpdateStatus(0, 1, "Getting transactions from file", "", false);
                transEntries = EveAPI.GetResults(fileXML);
                UpdateStatus(1, 1, "", transEntries.Count + " entries found in file.", false);

                if (transEntries != null && transEntries.Count > 0)
                {
                    int batchPrg = 0;
                    UpdateStatus(0, transEntries.Count, "Processing transactions", "", false);

                    XmlNode entryIDNode = transEntries[0].SelectSingleNode("@transactionID");
                    //long fileMaxID = long.Parse(entryIDNode.Value,
                    //    System.Globalization.CultureInfo.InvariantCulture.NumberFormat);

                    // Loop through the results returned from this call to the API and add the line to
                    // the data table if the transactionID is not already in the database.
                    foreach (XmlNode transEntry in transEntries)
                    {
                        XmlNode transIDNode = transEntry.SelectSingleNode("@transactionID");
                        long transID = long.Parse(transIDNode.Value,
                            System.Globalization.CultureInfo.InvariantCulture.NumberFormat);

                        if (transID > highestID) { highestID = transID; }

                        //if (transID > highestIDSoFar)
                        //{
                        if (!Transactions.TransactionExists(transData, transID) &&
                            transData.FindByID(transID) == null)
                        {
                            // Actually create the line and add it to the data table
                            SortedList<long, string> nameIDs = new SortedList<long, string>();
                            EMMADataSet.TransactionsRow newRow = BuildTransRow(transID, transData,
                                transEntry, walletID, nameIDs, false);

                            transData.AddTransactionsRow(newRow);
                            retVal++;

                            // This section searches the character, item and station ref type tables
                            // for the values used in this new transaction entry.
                            // If they are not present in the table then they are added.
                            #region Check other tables and add values if needed.
                            foreach (KeyValuePair<long, string> checkName in nameIDs)
                            {
                                Names.AddName(checkName.Key, checkName.Value);
                            }
                            Items.AddItem(newRow.ItemID, transEntry.SelectSingleNode("@typeName").Value);
                            #endregion
                        }
                        else
                        {
                            SortedList<long, string> nameIDs = new SortedList<long, string>();
                            // We've got a transaction that already exists in the database,
                            // update the row with additional data if available.
                            EMMADataSet.TransactionsRow newRow =
                                BuildTransRow(transID, transData, transEntry, walletID, nameIDs, true);
                            EMMADataSet.TransactionsRow oldRow = transData.FindByID(transID);
                            bool updateDone = false;

                            if (newRow.BuyerWalletID != oldRow.BuyerWalletID && newRow.BuyerWalletID != 0)
                            {
                                oldRow.BuyerWalletID = newRow.BuyerWalletID;
                                updateDone = true;
                            }
                            if (newRow.SellerWalletID != oldRow.SellerWalletID && newRow.SellerWalletID != 0)
                            {
                                oldRow.SellerWalletID = newRow.SellerWalletID;
                                updateDone = true;
                            }
                            // If a corp sells somthing to another corp (or itself) then we will get into
                            // the position of having the other party set as a character when in fact
                            // it is that character's corp.
                            // We check for this here and correct it if required.
                            if (oldRow.BuyerID == _charID && newRow.BuyerID == _corpID)
                            {
                                oldRow.BuyerID = newRow.BuyerID;
                                oldRow.BuyerCharacterID = newRow.BuyerCharacterID;
                                oldRow.BuyerWalletID = newRow.BuyerWalletID;
                                oldRow.BuyerForCorp = newRow.BuyerForCorp;
                                updateDone = true;
                            }
                            if (oldRow.SellerID == _charID && newRow.SellerID == _corpID)
                            {
                                oldRow.SellerID = newRow.SellerID;
                                oldRow.SellerCharacterID = newRow.SellerCharacterID;
                                oldRow.SellerWalletID = newRow.SellerWalletID;
                                oldRow.SellerForCorp = newRow.SellerForCorp;
                                updateDone = true;
                            }

                            if (updateDone)
                            {
                                updated++;
                            }
                        }
                        //}

                        batchPrg++;
                        UpdateStatus(batchPrg, transEntries.Count, "", "", false);
                    }
                }

                if (highestID > highestIDSoFar)
                {
                    SetHighestID(corc, APIDataType.Transactions, highestID);
                }

                UpdateStatus(0, 0, retVal + " transactions added to database.", "", false);
                UpdateStatus(0, 0, updated + " transactions updated.", "", false);

                if (transData.Count > 0)
                {
                    Transactions.Store(transData);

                    UpdateStatus(1, 1, "", "Complete", true);
                }

            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    // If we've caught a standard exception rather than an EMMA one then log it be creating a
                    // new exception.
                    // Note that we don't need to actually throw it..
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Error when adding transactions", ex);
                }

                SetLastAPIUpdateError(corc, APIDataType.Transactions, ex.Message);
                UpdateStatus(-1, 0, "Error", ex.Message, true);
            }

            if (UpdateEvent != null)
            {
                UpdateEvent(this, new APIUpdateEventArgs(APIDataType.Transactions,
                    corc == CharOrCorp.Char ? _charID : _corpID,
                    APIUpdateEventType.UpdateCompleted));
            }

            return retVal;
        }
Example #22
0
        public Main(bool checkForUpdates)
        {
            Diagnostics.StartTimer("TotalStartupTimer");
            Diagnostics.StartTimer("DisplaySplash");
            splash = new SplashScreen(this);
            Thread t0 = new Thread(ShowSplash);
            t0.Start();
            Diagnostics.StopTimer("DisplaySplash");

            Diagnostics.StartTimer("InitGUI");
            InitializeComponent();
            this.FormClosing += new FormClosingEventHandler(Main_FormClosing);
            // Set main window start state/position/size
            this.StartPosition = FormStartPosition.Manual;
            this.WindowState = EveMarketMonitorApp.Properties.Settings.Default.WindowState;
            if (EveMarketMonitorApp.Properties.Settings.Default.WindowPos.X > 0 &&
                EveMarketMonitorApp.Properties.Settings.Default.WindowPos.X < Screen.PrimaryScreen.WorkingArea.Width &&
                EveMarketMonitorApp.Properties.Settings.Default.WindowPos.Y > 0 &&
                EveMarketMonitorApp.Properties.Settings.Default.WindowPos.Y < Screen.PrimaryScreen.WorkingArea.Height)
            {
                this.Location = EveMarketMonitorApp.Properties.Settings.Default.WindowPos;
            }
            else
            {
                this.Location = new Point(0, 0);
            }
            this.Size = EveMarketMonitorApp.Properties.Settings.Default.WindowSize;
            Diagnostics.StopTimer("InitGUI");

            try
            {
                //splash.ShowMessage("Test Message", "Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DateTime start = DateTime.UtcNow;
                // DO ANY SETUP HERE.
                // The splash screen will be showing while these methods are executed.
                Diagnostics.StartTimer("Environment");
                UpdateStatus(0, 0, "Setting up environment", "", false);
                SetupEnvironment();
                Diagnostics.StopTimer("Environment");
                UpdateStatus(0, 0, "Checking Prerequesits", "", false);
                if (Prerequs())
                {
                    Diagnostics.StartTimer("PingChecks");
                    UpdateStatus(0, 0, "Checking remote servers", "", false);
                    PingServers();
                    Diagnostics.StopTimer("PingChecks");
                    Diagnostics.StartTimer("Updates");
                    // Update settings and user database if needed.
                    UpdateStatus(0, 0, "Initalising database", "", false);
                    //try
                    //{
                    checkForUpdates = checkForUpdates && EveMarketMonitorApp.Properties.Settings.Default.AutoUpdate;
                    if (checkForUpdates)
                    {
                        //DateTime lastCheck = Properties.Settings.Default.LastEMMAUpdateCheck;
                        //if (lastCheck.AddHours(5).CompareTo(DateTime.UtcNow) < 0)
                        //{
                        UpdateStatus(0, 0, "Checking for updates", "", false);
                        // Check for updates to EMMA components
                        AutoUpdate();
                        Properties.Settings.Default.LastEMMAUpdateCheck = DateTime.UtcNow;
                        Properties.Settings.Default.Save();
                        //}
                    }
                    Updater.Update();
                    //}
                    //catch (EMMAException)
                    //{
                    //UpdateStatus(0, 0, "Done", "", true);
                    //MessageBox.Show(splash, "Critical error updating EMMA database. For details, see " +
                    //    "\"Logging/ExceptionLog.txt\"", "Ciritcal error",
                    //    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //}
                    Updater.InitDBs();
                    CheckForDocumentation();
                    Diagnostics.StopTimer("Updates");
                    UpdateStatus(0, 0, "Checking License", "", false);
                    ValidateInstall(false, splash);

                    if (Globals.License != LicenseType.Full &&
                        Globals.License != LicenseType.Lite &&
                        Globals.License != LicenseType.Trial &&
                        Globals.License != LicenseType.Monthly)
                    {
                        this.Close();
                    }
                    else
                    {

                        Diagnostics.StartTimer("MapInit");
                        // Pre-load map data.
                        Map.InitaliseData();
                        UpdateStatus(0, 0, "Getting latest outpost data", "", false);
                        EveAPI.UpdateOutpostData();
                        Diagnostics.StopTimer("MapInit");
                        Diagnostics.StartTimer("AutoLogin");
                        // Log user in if they have auto login turned on
                        AutoLogin();
                        Diagnostics.StopTimer("AutoLogin");
                        //UpdateStatus(0, 0, "Starting program", "", false);

                        // make sure we show the splash screen for a minimum of one second.
                        // ... it looks wierd otherwise.
                        while (start.AddSeconds(1).CompareTo(DateTime.UtcNow) > 0) { }
                    }
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    emmaEx = new EMMAException(ExceptionSeverity.Critical, "Error during startup", ex);
                }
                splash.ShowMessage("Problem during EMMA startup.\r\nCheck " + EMMAException.logFile +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus(0, 0, "Done", "", true);
                this.Close();
            }
            finally
            {
                Diagnostics.StartTimer("LoadMainForm");
                UpdateStatus(0, 0, "Done", "", true);
                splash = null;
            }
        }
        private void LoadEMMAFile(object filenameData)
        {
            int maxStatus = 7;
            string filename = (string)filenameData;
            string tmpLoadDir = string.Format("{0}Temp{1}Load{1}",
                Globals.AppDataDir, Path.DirectorySeparatorChar);
            UpdateStatus(0, maxStatus, "", "Decompressing files", false);
            try
            {
                Directory.CreateDirectory(tmpLoadDir);
                float saveVersion = Compression.DecompressDirectory(filename, tmpLoadDir);

                if (saveVersion == 0)
                {
                    UpdateStatus(0, 0, "Error: File version is too old", "", true);
                }
                else if (saveVersion == 1)
                {
                    if (filename.ToUpper().EndsWith(".CDAT"))
                    {
                        Dictionary<int, int> IDChanges = new Dictionary<int, int>();
                        try
                        {
                            PublicCorps.LoadOldEmmaXML(tmpLoadDir + "CorpData.xml", ref IDChanges);
                            Dividends.LoadOldEmmaXML(tmpLoadDir + "Dividends.xml", IDChanges);
                            WebLinks.LoadOldEmmaXML(tmpLoadDir + "WebLinks.xml", IDChanges);
                            // Try to link journal entries to the dividends
                            Dividends.UpdateFromJournal(true);
                            UpdateStatus(1, 1, "Complete", "", true);
                        }
                        catch (ThreadAbortException abortEx)
                        {
                            // User has closed the progress dialog so just throw the exception to the next level.
                            throw abortEx;
                        }
                        catch (Exception ex)
                        {
                            EMMAException emmaEx = ex as EMMAException;
                            if (emmaEx == null)
                            {
                                emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem importing old EMMA public corp data", ex);
                            }
                            UpdateStatus(-1, -1, "Error", ex.Message, true);
                        }
                    }
                    else
                    {
                        APICharacter character = UserAccount.CurrentGroup.Accounts[0].Chars[0];
                        CharOrCorp corc = CharOrCorp.Char;

                        // Determine correct APICharacter instance to use when loading the data.
                        SortedList<object, string> options = new SortedList<object, string>();
                        List<CharCorpOption> charcorps = UserAccount.CurrentGroup.GetCharCorpOptions();
                        charcorps.Sort();
                        foreach (CharCorpOption opt in charcorps)
                        {
                            options.Add(opt.Data, opt.Name);
                        }

                        OptionPicker picker = new OptionPicker("Select Char/Corp",
                            "Please select the character or corp to use when loading this file into the database.",
                            options);

                        if (picker.ShowDialog() != DialogResult.Cancel)
                        {
                            CharCorp chosen = (CharCorp)picker.SelectedItem;
                            character = chosen.characterObj;
                            corc = chosen.corp ? CharOrCorp.Corp : CharOrCorp.Char;
                        }

                        LoadOldDataParams parameters = new LoadOldDataParams();
                        parameters.dataDirectory = tmpLoadDir;
                        parameters.corc = corc;
                        parameters.character = character;
                        LoadOldEMMAData(parameters);
                    }
                }
                else if (saveVersion == 2)
                {
                }
            }
            catch (ThreadAbortException)
            {
                // User has closed the progress dialog so just allow the execution to fall out of this loop.
            }
        }
        private void Contracts_Load(object sender, EventArgs e)
        {
            try
            {
                EMMADataSet.ContractTypeDataTable types = ContractTypes.GetAll();
                // Remove the 'Cargo' type.
                // This is used by the Delivery  planner and we don't want users either viewing
                // or creating that type of contract.
                /*DataRow[] cargoType = types.Select("ID = 3");
                if (cargoType != null && cargoType.Length > 0)
                {
                    types.RemoveContractTypeRow((EMMADataSet.ContractTypeRow)cargoType[0]);
                }*/
                cmbType.DisplayMember = "Description";
                cmbType.ValueMember = "ID";
                cmbType.DataSource = types;
                cmbType.SelectedValue = (short)ContractType.Courier;
                cmbType.SelectedIndexChanged += new EventHandler(cmbType_SelectedIndexChanged);

                _contracts = new ContractList();
                _contractsBindingSource = new BindingSource();
                _contractsBindingSource.DataSource = _contracts;

                DataGridViewCellStyle iskStyle = new DataGridViewCellStyle(RewardColumn.DefaultCellStyle);
                iskStyle.Format = IskAmount.FormatString();
                RewardColumn.DefaultCellStyle = iskStyle;
                CollateralColumn.DefaultCellStyle = iskStyle;
                ExpectedProfitColumn.DefaultCellStyle = iskStyle;

                contractsGrid.AutoGenerateColumns = false;
                contractsGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
                contractsGrid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;

                contractsGrid.DataSource = _contractsBindingSource;
                ContractIDColumn.DataPropertyName = "ID";
                OwnerColumn.DataPropertyName = "Owner";
                IssueDateColumn.DataPropertyName = "IssueDate";
                PickupStationColumn.DataPropertyName = "PickupStation";
                DestinationStationColumn.DataPropertyName = "DestinationStation";
                RewardColumn.DataPropertyName = "Reward";
                CollateralColumn.DataPropertyName = "Collateral";
                ExpectedProfitColumn.DataPropertyName = "ExpectedProfit";
                StatusColumn.DataPropertyName = "Status";
                CompletedColumn.Image = icons.Images["tick.gif"];
                FailedColumn.Image = icons.Images["cross.gif"];
                ExpiredColumn.Image = icons.Images["expired.gif"];
                contractsGrid.CellClick += new DataGridViewCellEventHandler(contractsGrid_CellClick);
                contractsGrid.CellDoubleClick += new DataGridViewCellEventHandler(contractsGrid_CellDoubleClick);
                UserAccount.Settings.GetColumnWidths(this.Name, contractsGrid);

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

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

                cmbPickup.Tag = 0;
                cmbPickup.Items.AddRange(_recentStations.ToArray());
                cmbPickup.AutoCompleteSource = AutoCompleteSource.ListItems;
                cmbPickup.AutoCompleteMode = AutoCompleteMode.Suggest;
                cmbPickup.KeyDown += new KeyEventHandler(cmbPickup_KeyDown);
                cmbPickup.SelectedIndexChanged += new EventHandler(cmbPickup_SelectedIndexChanged);

                EMMADataSet.ContractStatesDataTable states = ContractStatus.GetAll();
                BindingSource statusSource = new BindingSource();
                statusSource.DataSource = states;
                statusSource.Sort = "Description";
                cmbStatus.DisplayMember = "Description";
                cmbStatus.ValueMember = "ID";
                cmbStatus.DataSource = statusSource;
                cmbStatus.SelectedValue = 1;
                cmbStatus.SelectedIndexChanged += new EventHandler(cmbStatus_SelectedIndexChanged);

                this.FormClosing += new FormClosingEventHandler(ViewContracts_FormClosing);
                RefreshGUI();
                DisplayContracts();
            }
            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 contracts form", ex);
                }
                MessageBox.Show("Problem setting up contracts view.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #25
0
        /// <summary>
        /// Update player-owned outpost data from the API.
        /// </summary>
        public static void UpdateOutpostData()
        {
            try
            {
                DateTime nextUpdate = Properties.Settings.Default.LastOutpostUpdate.AddDays(1);

                if (DateTime.UtcNow.CompareTo(nextUpdate) >= 0)
                {
                    XmlDocument xml = GetXml(URL_EveApiHTTPS + URL_OutpostListApi, "");
                    XmlNodeList results = GetResults(xml);

                    foreach (XmlNode outpost in results)
                    {
                        XmlNode stationIDNode = outpost.SelectSingleNode("@stationID");
                        XmlNode stationNameNode = outpost.SelectSingleNode("@stationName");
                        XmlNode solarSystemNode = outpost.SelectSingleNode("@solarSystemID");
                        XmlNode corpIDNode = outpost.SelectSingleNode("@corporationID");

                        long stationID = 0, solarSystemID = 0, corpID = 0;
                        string stationName = "";

                        stationID = long.Parse(stationIDNode.Value,
                            System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
                        stationName = stationNameNode.Value;
                        solarSystemID = long.Parse(solarSystemNode.Value,
                            System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
                        corpID = long.Parse(corpIDNode.Value,
                            System.Globalization.CultureInfo.InvariantCulture.NumberFormat);

                        Stations.AddStation(stationID, stationName, solarSystemID, corpID);
                    }

                    Properties.Settings.Default.LastOutpostUpdate = DateTime.UtcNow;
                    Properties.Settings.Default.Save();
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaex = ex as EMMAException;
                if (emmaex == null)
                {
                    emmaex = new EMMAException(ExceptionSeverity.Warning, "Problem updating outpost data.", ex);
                }
                // Not much we can do about it and it's not critical so just allow things to continue.
            }
        }
        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                // Store the 'included' flags for any chars/corps as they have been setup by the user.
                _characters = new List<APICharacter>();
                foreach (EVEAccount account in _accounts)
                {
                    _characters.AddRange(account.Chars);
                }
                foreach (APICharacter apiChar in _characters)
                {
                    // API key may have been changed so make sure we update it.
                    apiChar.APIKey = UserAccount.CurrentGroup.GetAccount(apiChar.UserID).ApiKey;
                    // update standings for all those that are part of the group
                    //if (apiChar.CharIncWithRptGroup) { apiChar.UpdateStandings(CharOrCorp.Char); }
                    //if (apiChar.CorpIncWithRptGroup) { apiChar.UpdateStandings(CharOrCorp.Corp); }
                    if (apiChar.AccessType == CharOrCorp.Char){apiChar.UpdateStandings(CharOrCorp.Char);}
                    if (apiChar.AccessType == CharOrCorp.Corp){apiChar.UpdateStandings(CharOrCorp.Corp);}

                    if (apiChar.AccessType == CharOrCorp.Char)
                    {
                        apiChar.StoreGroupLevelSettings(SettingsStoreType.Char);
                    }

                    if (apiChar.AccessType == CharOrCorp.Corp)
                    {
                        apiChar.StoreGroupLevelSettings(SettingsStoreType.Corp);
                    }
                    //apiChar.StoreGroupLevelSettings(SettingsStoreType.Both);
                }

                // Make sure to clear 'included' flags for any chars/corps on accounts that have been removed.
                _characters = new List<APICharacter>();
                foreach (EVEAccount account in _removedAccounts)
                {
                    _characters.AddRange(account.Chars);
                }
                foreach (APICharacter apiChar in _characters)
                {
                    apiChar.CharIncWithRptGroup = false;
                    apiChar.CorpIncWithRptGroup = false;
                    apiChar.StoreGroupLevelSettings(SettingsStoreType.Both);
                }

                // Finally, update the list of eve accounts stored against this report group.
                _group.StoreEveAccounts();

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                EMMAException emmaex = ex as EMMAException;
                if (emmaex == null)
                {
                    emmaex = new EMMAException(ExceptionSeverity.Error, "Problem saving report group setup", ex);
                }
                MessageBox.Show("Problem storing data: " + ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #27
0
        private void Main_Load(object sender, EventArgs e)
        {
            try
            {
                Diagnostics.StopTimer("LoadMainForm");
                this.Size = EveMarketMonitorApp.Properties.Settings.Default.WindowSize;

                Diagnostics.StartTimer("Init");
                Initialisation();
                _controlPanel.InitSettings();
                _controlPanel.Show();
                Diagnostics.StopTimer("Init");

                this.Refresh();

                if (EveMarketMonitorApp.Properties.Settings.Default.FirstRun)
                {
                    DisplayTutorial();

                    EveMarketMonitorApp.Properties.Settings.Default.FirstRun = false;
                    EveMarketMonitorApp.Properties.Settings.Default.Save();
                }

                if (_status == SystemStatus.NoUserLoggedIn)
                {
                    // Set these to make sure nothing thinks we're logged in when we're not.
                    UserAccount.Name = "";
                    UserAccount.CurrentGroup = null;
                    Diagnostics.StopTimer("TotalStartupTimer");
                    Diagnostics.DisplayDiag("Total Startup Time: " + Diagnostics.GetRunningTime("TotalStartupTimer") +
                        "\r\n  Display Splashscreen: " + Diagnostics.GetRunningTime("DisplaySplash") +
                        "\r\n  Environment Setup: " + Diagnostics.GetRunningTime("Environment") +
                        "\r\n  Ping Checks: " + Diagnostics.GetRunningTime("PingChecks") +
                        "\r\n  EMMA Update Check: " + Diagnostics.GetRunningTime("Updates") +
                        "\r\n  Map Init: " + Diagnostics.GetRunningTime("MapInit") +
                        "\r\n  Load Main Form: " + Diagnostics.GetRunningTime("LoadMainForm") +
                        "\r\n  Global Init: " + Diagnostics.GetRunningTime("Init"));
                    if (Login())
                    {
                        if (UserAccount.CurrentGroup == null)
                        {
                            SelectReportGroup();
                        }
                    }
                }
                else
                {
                    Diagnostics.StartTimer("RefreshDisplay");
                    RefreshDisplay();
                    Diagnostics.StopTimer("RefreshDisplay");

                    Diagnostics.StopTimer("TotalStartupTimer");
                    Diagnostics.DisplayDiag("Total Startup Time: " + Diagnostics.GetRunningTime("TotalStartupTimer") +
                        "\r\n  Display Splashscreen: " + Diagnostics.GetRunningTime("DisplaySplash") +
                        "\r\n  Init GUI: " + Diagnostics.GetRunningTime("InitGUI") +
                        "\r\n  Environment Setup: " + Diagnostics.GetRunningTime("Environment") +
                        "\r\n  Ping Checks: " + Diagnostics.GetRunningTime("PingChecks") +
                        "\r\n  EMMA Update Check: " + Diagnostics.GetRunningTime("Updates") +
                        "\r\n  Map Init: " + Diagnostics.GetRunningTime("MapInit") +
                        "\r\n  Auto Login: "******"AutoLogin") +
                        "\r\n    Open Account: " + Diagnostics.GetRunningTime("OpenAccount") +
                        "\r\n      Load User Account: " + Diagnostics.GetRunningTime("OpenAccount.LoadAccount") +
                        "\r\n      Load Report Groups: " + Diagnostics.GetRunningTime("OpenAccount.GetGroups") +
                        "\r\n      Load Eve Accounts: " + Diagnostics.GetRunningTime("RptGrp.LoadEveAccounts") +
                        "\r\n      Init User Settings: " + Diagnostics.GetRunningTime("OpenAccount.InitSettings") +
                        "\r\n  Load Main Form: " + Diagnostics.GetRunningTime("LoadMainForm") +
                        "\r\n  Global Init: " + Diagnostics.GetRunningTime("Init") +
                        "\r\n  Refresh Display: " + Diagnostics.GetRunningTime("RefreshDisplay"));
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem loading main form.", ex);
                }
                try
                {
                    MessageBox.Show(null, "Problem loading EMMA:\r\n" + ex.Message, "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception)
                {
                }
                finally
                {
                    _forceClose = true;
                    this.Close();
                }
            }
        }
        private void ViewJournal_Load(object sender, EventArgs e)
        {
            try
            {
                Diagnostics.ResetAllTimers();
                Diagnostics.StartTimer("ViewJournal.Load");
                Diagnostics.StartTimer("ViewJournal.Load.Part1");
                _entries = new JournalList();
                _journalBindingSource = new BindingSource();
                _journalBindingSource.DataSource = _entries;

                DataGridViewCellStyle style = new DataGridViewCellStyle(AmountColumn.DefaultCellStyle);
                style.Format = IskAmount.FormatString();
                AmountColumn.DefaultCellStyle = style;
                DataGridViewCellStyle style2 = new DataGridViewCellStyle(BalanceColumn.DefaultCellStyle);
                style2.Format = IskAmount.FormatString();
                BalanceColumn.DefaultCellStyle = style2;

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

                journalDataGridView.DataSource = _journalBindingSource;
                IDColumn.DataPropertyName = "Id";
                DateColumn.DataPropertyName = "Date";
                TypeColumn.DataPropertyName = "Type";
                OwnerIsSenderColumn.DataPropertyName = "OwnerIsSender";
                Owner1Column.DataPropertyName = "Sender";
                OwnerID1Column.DataPropertyName = "SenderID";
                Owner2Column.DataPropertyName = "Reciever";
                OwnerID2Column.DataPropertyName = "RecieverID";
                ArgIDColumn.DataPropertyName = "ArgID";
                ArgNameColumn.DataPropertyName = "ArgName";
                AmountColumn.DataPropertyName = "Amount";
                BalanceColumn.DataPropertyName = "Balance";
                ReasonColumn.DataPropertyName = "Reason";
                Owner1CorpColumn.DataPropertyName = "SenderCorp";
                Owner2CorpColumn.DataPropertyName = "RecieverCorp";
                Owner1WalletColumn.DataPropertyName = "SenderWallet";
                Owner2WalletColumn.DataPropertyName = "RecieverWallet";

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

                dtpEndDate.Value = DateTime.Now;
                dtpStartDate.Value = DateTime.Now.AddDays(-2);
                dtpEndDate.KeyDown += new KeyEventHandler(dtpEndDate_KeyDown);
                dtpEndDate.Leave += new EventHandler(dtpEndDate_Leave);
                dtpStartDate.KeyDown += new KeyEventHandler(dtpStartDate_KeyDown);
                dtpStartDate.Leave += new EventHandler(dtpStartDate_Leave);

                Diagnostics.StopTimer("ViewJournal.Load.Part1");

                Diagnostics.StartTimer("ViewJournal.Load.Part2");
                List<CharCorpOption> charcorps = UserAccount.CurrentGroup.GetCharCorpOptions(APIDataType.Journal);
                _possibleOwners = new List<long>();
                foreach (CharCorpOption chop in charcorps)
                {
                    _possibleOwners.Add(chop.Corp ? chop.CharacterObj.CorpID : chop.CharacterObj.CharID);
                }
                _accessParams = new List<FinanceAccessParams>();
                foreach (long id in _possibleOwners)
                {
                    _accessParams.Add(new FinanceAccessParams(id));
                }
                cmbOwner.DisplayMember = "Name";
                cmbOwner.ValueMember = "Data";
                charcorps.Sort();
                cmbOwner.DataSource = charcorps;
                cmbOwner.SelectedValue = 0;
                cmbOwner.Enabled = false;
                Diagnostics.StopTimer("ViewJournal.Load.Part2");

                Diagnostics.StartTimer("ViewJournal.Load.Part3");
                EMMADataSet.JournalRefTypesDataTable types = JournalRefTypes.GetTypesByJournal(_accessParams);
                EMMADataSet.JournalRefTypesRow newType = types.NewJournalRefTypesRow();
                newType.ID = 0;
                newType.RefName = "All Types";
                types.AddJournalRefTypesRow(newType);
                BindingSource typesSource = new BindingSource();
                typesSource.DataSource = types;
                typesSource.Sort = "RefName";
                cmbType.DisplayMember = "RefName";
                cmbType.ValueMember = "ID";
                cmbType.DataSource = typesSource;
                cmbType.SelectedValue = 0;
                Diagnostics.StopTimer("ViewJournal.Load.Part3");

                cmbType.SelectedIndexChanged += new EventHandler(cmbType_SelectedIndexChanged);

                cmbOwner.SelectedIndexChanged += new EventHandler(cmbOwner_SelectedIndexChanged);
                chkIngoreOwner.Checked = true;
                chkIngoreOwner.CheckedChanged += new EventHandler(chkIngoreOwner_CheckedChanged);

                cmbWallet.SelectedIndexChanged += new EventHandler(cmbWallet_SelectedIndexChanged);

                DisplayWallets();
                chkIgnoreWallet.CheckedChanged += new EventHandler(chkIgnoreWallet_CheckedChanged);
                txtName.KeyDown += new KeyEventHandler(txtName_KeyDown);
                txtName.Leave += new EventHandler(txtName_Leave);

                Diagnostics.StartTimer("ViewJournal.Load.Part4");
                this.FormClosing += new FormClosingEventHandler(ViewJournal_FormClosing);
                DisplayEntries();
                Diagnostics.StopTimer("ViewJournal.Load.Part4");
                Diagnostics.StopTimer("ViewJournal.Load");

                Diagnostics.DisplayDiag(
                    "Total form load time: " + Diagnostics.GetRunningTime("ViewJournal.Load").ToString() +
                    "\r\nSplit time 1: " + Diagnostics.GetRunningTime("ViewJournal.Load.Part1").ToString() +
                    "\r\nSplit time 2: " + Diagnostics.GetRunningTime("ViewJournal.Load.Part2").ToString() +
                    "\r\nSplit time 3: " + Diagnostics.GetRunningTime("ViewJournal.Load.Part3").ToString() +
                    "\r\nSplit time 4: " + Diagnostics.GetRunningTime("ViewJournal.Load.Part4").ToString());
            }
            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 journal form", ex);
                }
                MessageBox.Show("Problem setting up journal view.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void ViewOrders_Load(object sender, EventArgs e)
        {
            try
            {
                _orders = new OrdersList();
                _ordersBindingSource = new BindingSource();
                _ordersBindingSource.DataSource = _orders;

                DataGridViewCellStyle iskStyle = new DataGridViewCellStyle(PriceColumn.DefaultCellStyle);
                iskStyle.Format = IskAmount.FormatString();
                PriceColumn.DefaultCellStyle = iskStyle;
                EscrowColumn.DefaultCellStyle = iskStyle;
                TotalValueColumn.DefaultCellStyle = iskStyle;
                RemainingValueColumn.DefaultCellStyle = iskStyle;
                DataGridViewCellStyle dayStyle = new DataGridViewCellStyle(DurationColumn.DefaultCellStyle);
                dayStyle.Format = "# Days;-# Days;# Days";
                DurationColumn.DefaultCellStyle = dayStyle;

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

                ordersGrid.DataSource = _ordersBindingSource;
                DateIssuedColumn.DataPropertyName = "Date";
                OwnerColumn.DataPropertyName = "Owner";
                ItemColumn.DataPropertyName = "Item";
                PriceColumn.DataPropertyName = "Price";
                StationColumn.DataPropertyName = "Station";
                SystemColumn.DataPropertyName = "System";
                RegionColumn.DataPropertyName = "Region";
                TypeColumn.DataPropertyName = "Type";
                TotalUnitsColumn.DataPropertyName = "TotalVol";
                QuantityColumn.DataPropertyName = "RemainingVol";
                EscrowColumn.DataPropertyName = "Escrow";
                StateColumn.DataPropertyName = "State";
                RangeColumn.DataPropertyName = "RangeText";
                DurationColumn.DataPropertyName = "Duration";
                TotalValueColumn.DataPropertyName = "TotalValue";
                RemainingValueColumn.DataPropertyName = "RemainingValue";

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

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

                EMMADataSet.OrderStatesDataTable allStates = OrderStates.GetAllStates();
                EMMADataSet.OrderStatesRow newState = allStates.NewOrderStatesRow();
                newState.StateID = 0;
                newState.Description = "All States";
                allStates.AddOrderStatesRow(newState);
                BindingSource stateSource = new BindingSource();
                stateSource.DataSource = allStates;
                stateSource.Sort = "Description";
                cmbStateFilter.DisplayMember = "Description";
                cmbStateFilter.ValueMember = "StateID";
                cmbStateFilter.DataSource = stateSource;
                cmbStateFilter.SelectedIndexChanged += new EventHandler(cmbStateFilter_SelectedIndexChanged);

                _recentStations = UserAccount.CurrentGroup.Settings.RecentStations;
                _recentStations.Sort();
                AutoCompleteStringCollection stations = new AutoCompleteStringCollection();
                stations.AddRange(_recentStations.ToArray());
                txtStation.AutoCompleteCustomSource = stations;
                txtStation.AutoCompleteSource = AutoCompleteSource.CustomSource;
                txtStation.AutoCompleteMode = AutoCompleteMode.Suggest;
                txtStation.Leave += new EventHandler(txtStation_Leave);
                txtStation.KeyDown += new KeyEventHandler(txtStation_KeyDown);
                txtStation.Tag = 0;
                txtStation.Text = "";

                cmbType.SelectedIndexChanged += new EventHandler(cmbType_SelectedIndexChanged);

                this.FormClosing += new FormClosingEventHandler(ViewOrders_FormClosing);

                DisplayOrders();
            }
            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 orders form", ex);
                }
                MessageBox.Show("Problem setting up orders view.\r\nCheck " + Globals.AppDataDir + "Logging\\ExceptionLog.txt" +
                    " for details.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void DisplayData()
        {
            try
            {
                //PublicCorp oldSelection = null;
                //if (sharesGrid.SelectedRows != null && sharesGrid.SelectedRows.Count > 0)
                //{
                //    oldSelection = (PublicCorp)sharesGrid.SelectedRows[0].DataBoundItem;
                //}

                _investments = PublicCorps.GetReportGroupInvestments(UserAccount.CurrentGroup.ID,
                    _bankMode);
                if (chkInvestedOnly.Checked && !_bankMode)
                {
                    _investments.ItemFilter = "SharesOwned > 0";
                }
                else
                {
                    _investments.ItemFilter = "";
                }

                DataGridViewCellStyle style = new DataGridViewCellStyle(ValueColumn.DefaultCellStyle);
                style.Format = IskAmount.FormatString();
                ValueColumn.DefaultCellStyle = style;

                sharesGrid.AutoGenerateColumns = false;
                CorpNameColumn.DataPropertyName = "Name";
                QuantityColumn.DataPropertyName = "SharesOwned";
                QuantityColumn.Visible = !_bankMode;
                if (!_bankMode)
                {
                    ValueColumn.DataPropertyName = "SharesOwnedValue";
                    ValueColumn.HeaderText = "Value";
                    AccountOwnerColumn.DataPropertyName = "";
                    AccountOwnerColumn.Visible = false;
                }
                else
                {
                    ValueColumn.DataPropertyName = "AmountInAccount";
                    ValueColumn.HeaderText = "Account Balance";
                    AccountOwnerColumn.DataPropertyName = "Owner";
                    AccountOwnerColumn.Visible = true;
                }

                DataGridViewColumn sortColumn = CorpNameColumn;
                ListSortDirection sortDirection = ListSortDirection.Ascending;
                if (sharesGrid.SortedColumn != null) { sortColumn = sharesGrid.SortedColumn; }
                if (sharesGrid.SortOrder == SortOrder.Descending)
                {
                    sortDirection = ListSortDirection.Descending;
                }

                if (_investments.ItemFilter.Length > 0)
                {
                    sharesGrid.DataSource = _investments.FiltredItems;
                }
                else
                {
                    sharesGrid.DataSource = _investments;
                }

                //if (oldSelection != null)
                //{
                //    for (int i = 0; i < sharesGrid.Rows.Count; i++)
                //    {
                //        if (((PublicCorp)sharesGrid.Rows[i].DataBoundItem).Equals(oldSelection))
                //        {
                //            sharesGrid.Rows[i].Selected = true;
                //        }
                //    }
                //}

                sharesGrid.Sort(sortColumn, sortDirection);

                btnCorpDetail.Enabled = false;
                btnDeleteCorp.Enabled = false;
                btnBuySell.Enabled = !_bankMode;

                if (sharesGrid.Rows.Count > 0)
                {
                    sharesGrid.Rows[0].Selected = true;
                    RowSelected(0);
                }
            }
            catch (Exception ex)
            {
                EMMAException emmaEx = ex as EMMAException;
                if (emmaEx == null)
                {
                    emmaEx = new EMMAException(ExceptionSeverity.Error, "Problem displaying current investments", ex);
                }
                MessageBox.Show(emmaEx.Message + ": " + ex.Message, "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }