Exemplo n.º 1
0
        /// <summary>
        /// this will delete the current database, and reset it with the data selected
        /// </summary>
        /// <param name="AParentForm"></param>
        public static void ImportAllData(Form AParentForm)
        {
            DialogResult r = MessageBox.Show(
                Catalog.GetString("WARNING: this will reset the database! Do you really want to delete the current database?"),
                Catalog.GetString("WARNING: this will reset the database!"),
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning,
                MessageBoxDefaultButton.Button2);

            if (r == DialogResult.Yes)
            {
                string zippedYml = TImportExportDialogs.ImportWithDialogYMLGz(Catalog.GetString("Please select the file to import from"));

                if (zippedYml != null)
                {
                    Thread t = new Thread(() => ResetDatabaseInThread(zippedYml));

                    using (TProgressDialog dialog = new TProgressDialog(t))
                    {
                        if (dialog.ShowDialog() == DialogResult.Cancel)
                        {
                            return;
                        }
                    }

                    if (WebConnectorResult)
                    {
                        // TODO: reset all caches? for comboboxes etc
                        MessageBox.Show(Catalog.GetString("Import of database was successful. Please restart your OpenPetra client"));
                    }
                    else
                    {
                        MessageBox.Show(Catalog.GetString("Failed import of database. Please check the Server.log file on the server"));
                    }
                }
            }
        }
        private void CreateGiftBatch(System.Object sender, EventArgs e)
        {
            // TODO: should we first ask? also when closing the window?
            SaveChanges();

            // load the transactions of the selected statement, and the matches
            Thread t = new Thread(() => CreateGiftBatchThread());

            using (TProgressDialog dialog = new TProgressDialog(t))
            {
                dialog.ShowDialog();
            }
        }
        /// <summary>
        /// Public method to export GL batches
        /// </summary>
        /// <returns>True if the Export succeeded and a file was created, false otherwise</returns>
        public bool ExportBatches()
        {
            if (txtFilename.Text == String.Empty)
            {
                MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."),
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }

            if (!Directory.Exists(Path.GetDirectoryName(txtFilename.Text)))
            {
                MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"),
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                txtFilename.Text = string.Empty;
                return false;
            }

            if (File.Exists(txtFilename.Text))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                        Catalog.GetString("Export Batches"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    return false;
                }

                try
                {
                    File.Delete(txtFilename.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(
                            Catalog.GetString(
                                "Failed to delete the file. Maybe it is already open in another application?  The system message was:{0}{1}"),
                            Environment.NewLine, ex.Message),
                        Catalog.GetString("Export GL Batches"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return false;
                }
            }

            if (rbtBatchNumberSelection.Checked)
            {
                if (!txtBatchNumberStart.NumberValueInt.HasValue)
                {
                    txtBatchNumberStart.NumberValueInt = 0;
                }

                if (!txtBatchNumberEnd.NumberValueInt.HasValue)
                {
                    txtBatchNumberEnd.NumberValueInt = 999999;
                }
            }
            else
            {
                if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate()))
                {
                    return false;
                }
            }

            String numberFormat = ConvertNumberFormat(cmbNumberFormat);
            String delimiter = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

            if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == ".")))
            {
                MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."),
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }

            // Save the defaults
            SaveUserDefaults();

            String dateFormatString = cmbDateFormat.GetSelectedString();

            // might be called from the main navigation window (FMainDS is null), or from the GL Batch screen (reusing MainDS)
            if (FMainDS == null)
            {
                FMainDS = new Ict.Petra.Shared.MFinance.GL.Data.GLBatchTDS();
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatch(FLedgerNumber, -1, -1));
            }

            Int32 ALedgerNumber = 0;

            ArrayList batches = new ArrayList();

            foreach (ABatchRow batch in FMainDS.ABatch.Rows)
            {
                // check conditions for exporting this batch
                // Batch Status
                bool exportThisBatch = batch.BatchStatus.Equals(MFinanceConstants.BATCH_POSTED)
                                       || (chkIncludeUnposted.Checked && batch.BatchStatus.Equals(MFinanceConstants.BATCH_UNPOSTED));

                if (rbtBatchNumberSelection.Checked)
                {
                    exportThisBatch &= (batch.BatchNumber >= txtBatchNumberStart.NumberValueInt);
                    exportThisBatch &= (batch.BatchNumber <= txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    exportThisBatch &= (batch.DateEffective >= dtpDateFrom.Date);
                    exportThisBatch &= (batch.DateEffective <= dtpDateTo.Date);
                }

                if (exportThisBatch)
                {
                    batches.Add(batch.BatchNumber);
                }

                ALedgerNumber = batch.LedgerNumber;
            }

            if (batches.Count == 0)
            {
                MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"),
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }

            // Do the actual export work
            try
            {
                Hashtable requestParams = new Hashtable();
                requestParams.Add("ALedgerNumber", ALedgerNumber);
                requestParams.Add("Delimiter", delimiter);
                requestParams.Add("DateFormatString", dateFormatString);
                requestParams.Add("Summary", rbtSummary.Checked);
                requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
                requestParams.Add("BaseCurrency", FMainDS.ALedger[0].BaseCurrency);
                requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
                requestParams.Add("bDontSummarize", chkDontSummarize.Checked);
                requestParams.Add("DontSummarizeAccount", cmbDontSummarizeAccount.GetSelectedString());
                requestParams.Add("DateForSummary", dtpDateSummary.Date);
                requestParams.Add("NumberFormat", numberFormat);

                String exportString = null;
                Thread ExportThread = new Thread(() => ExportAllGLBatchData(batches, requestParams, out exportString));
                using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
                {
                    ExportDialog.ShowDialog();
                }

                // Now we have the string we can write it to the file
                StreamWriter sw1 = new StreamWriter(txtFilename.Text);
                sw1.Write(exportString);
                sw1.Close();
            }
            catch (Exception ex)
            {
                TLogging.Log("GLBatchExport.ManualCode: " + ex.ToString());
                MessageBox.Show(ex.Message,
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                return false;
            }

            // Offer the client the chance to open the file in Excel or whatever
            if (MessageBox.Show(Catalog.GetString("Your data was exported successfully! Would you like to open the file in your default application?"),
                    Catalog.GetString("GL Batch Export"),
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Information,
                    MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                ProcessStartInfo si = new ProcessStartInfo(txtFilename.Text);
                si.UseShellExecute = true;
                si.Verb = "open";

                Process p = new Process();
                p.StartInfo = si;
                p.Start();
            }

            return true;
        }
        /// <summary>
        /// Main method to post a specified batch
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch row to post</param>
        /// <returns>True if the batch was successfully posted</returns>
        public bool PostBatch(AGiftBatchRow ACurrentBatchRow)
        {
            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return false;
            }

            FSelectedBatchNumber = ACurrentBatchRow.BatchNumber;
            TVerificationResultCollection Verifications;

            try
            {
                FMyForm.Cursor = Cursors.WaitCursor;

                FMyForm.EnsureGiftDataPresent(FLedgerNumber, FSelectedBatchNumber);

                GiftBatchTDSAGiftDetailTable BatchGiftDetails = new GiftBatchTDSAGiftDetailTable();

                foreach (GiftBatchTDSAGiftDetailRow Row in FMainDS.AGiftDetail.Rows)
                {
                    if (Row.BatchNumber == FSelectedBatchNumber)
                    {
                        BatchGiftDetails.Rows.Add((object[])Row.ItemArray.Clone());
                    }
                }

                // there are no gifts in this batch!
                if (BatchGiftDetails.Rows.Count == 0)
                {
                    FMyForm.Cursor = Cursors.Default;
                    MessageBox.Show(Catalog.GetString("Batch is empty!"), Catalog.GetString("Posting failed"),
                        MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return false;
                }

                bool CancelledDueToExWorkerOrAnonDonor;

                // save first, then post
                if (!FMyForm.SaveChangesForPosting(BatchGiftDetails, out CancelledDueToExWorkerOrAnonDonor))
                {
                    FMyForm.Cursor = Cursors.Default;

                    if (!CancelledDueToExWorkerOrAnonDonor)
                    {
                        // saving failed, therefore do not try to post
                        MessageBox.Show(Catalog.GetString("The batch was not posted due to problems during saving; ") + Environment.NewLine +
                            Catalog.GetString("Please first save the batch, and then post it!"));
                    }

                    return false;
                }
            }
            finally
            {
                FMyForm.Cursor = Cursors.Default;
            }

            //Check for missing international exchange rate
            bool IsTransactionInIntlCurrency = false;

            if (FMyForm.InternationalCurrencyExchangeRate(ACurrentBatchRow, out IsTransactionInIntlCurrency, true) == 0)
            {
                return false;
            }

            //Check for inactive KeyMinistries
            DataTable GiftsWithInactiveKeyMinistries;

            if (TRemote.MFinance.Gift.WebConnectors.InactiveKeyMinistriesFoundInBatch(FLedgerNumber, FSelectedBatchNumber,
                    out GiftsWithInactiveKeyMinistries))
            {
                string listOfRow = "Gift   Detail   Recipient        KeyMinistry" + Environment.NewLine;
                listOfRow += "------------------------------------------------";

                foreach (DataRow dr in GiftsWithInactiveKeyMinistries.Rows)
                {
                    listOfRow += String.Format("{0}{1:0000}    {2:00}    {3:00000000000}    {4}",
                        Environment.NewLine,
                        dr[0],
                        dr[1],
                        dr[2],
                        dr[3]);
                }

                string msg = String.Format(Catalog.GetString("Cannot post Batch {0} as inactive Key Ministries found in gifts:{1}{1}{2}"),
                    FSelectedBatchNumber,
                    Environment.NewLine,
                    listOfRow);

                MessageBox.Show(msg, Catalog.GetString("Inactive Key Ministries Found"));

                return false;
            }

            // ask if the user really wants to post the batch
            if (MessageBox.Show(String.Format(Catalog.GetString("Do you really want to post gift batch {0}?"),
                        FSelectedBatchNumber),
                    Catalog.GetString("Confirm posting of Gift Batch"),
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                return false;
            }

            Verifications = new TVerificationResultCollection();

            try
            {
                FPostingInProgress = true;

                Thread postingThread = new Thread(() => PostGiftBatch(out Verifications));

                using (TProgressDialog dialog = new TProgressDialog(postingThread))
                {
                    dialog.ShowDialog();
                }

                if (!TVerificationHelper.IsNullOrOnlyNonCritical(Verifications))
                {
                    string ErrorMessages = String.Empty;

                    foreach (TVerificationResult verif in Verifications)
                    {
                        ErrorMessages += "[" + verif.ResultContext + "] " +
                                         verif.ResultTextCaption + ": " +
                                         verif.ResultText + Environment.NewLine;
                    }

                    System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Posting failed"));
                }
                else
                {
                    MessageBox.Show(Catalog.GetString("The batch has been posted successfully!"));

                    return true;
                }
            }
            catch
            {
                //Do nothing
            }
            finally
            {
                FPostingInProgress = false;
            }

            return false;
        }
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// </summary>
        public void ImportBatches(TGiftImportDataSourceEnum AImportSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to post
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                        "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                dialog.FileName = TUserDefaults.GetStringDefault("Imp Filename",
                    TClientSettings.GetExportPath() + Path.DirectorySeparatorChar + "import.csv");

                dialog.Title = Catalog.GetString("Import Batches from CSV File");
                dialog.Filter = Catalog.GetString("Gift Batches files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Gift Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();
                    GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable();

                    Thread ImportThread = new Thread(() => ImportGiftBatches(
                            requestParams,
                            importString,
                            out AMessages,
                            out ok,
                            out NeedRecipientLedgerNumber));

                    using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                    {
                        ImportDialog.ShowDialog();
                    }

                    // If NeedRecipientLedgerNumber contains data then AMessages will only ever contain
                    // one message alerting the user that no data has been imported.
                    // We do not want to show this as we will be displaying another more detailed message.
                    if (NeedRecipientLedgerNumber.Rows.Count == 0)
                    {
                        ShowMessages(AMessages);
                    }

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    if (NeedRecipientLedgerNumber.Rows.Count > 0)
                    {
                        bool OfferToRunImportAgain = true;
                        bool DoNotShowMessageBoxEverytime = false;
                        TFrmExtendedMessageBox.TResult Result = TFrmExtendedMessageBox.TResult.embrUndefined;
                        int count = 1;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            if (!DoNotShowMessageBoxEverytime)
                            {
                                string CheckboxText = string.Empty;

                                // only show checkbox if there is at least one more occurance of this error
                                if (NeedRecipientLedgerNumber.Rows.Count - count > 0)
                                {
                                    CheckboxText = string.Format(
                                        Catalog.GetString("Do this for all further occurances ({0})?"), NeedRecipientLedgerNumber.Rows.Count - count);
                                }

                                TFrmExtendedMessageBox extendedMessageBox = new TFrmExtendedMessageBox(FPetraUtilsObject.GetForm());

                                extendedMessageBox.ShowDialog(string.Format(
                                        Catalog.GetString(
                                            "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."),
                                        Row.RecipientDescription, Row.RecipientKey) +
                                    "\n\r\n\r\n\r" +
                                    Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                    Catalog.GetString("Import Errors"),
                                    CheckboxText,
                                    TFrmExtendedMessageBox.TButtons.embbYesNo, TFrmExtendedMessageBox.TIcon.embiWarning);
                                Result = extendedMessageBox.GetResult(out DoNotShowMessageBoxEverytime);
                            }

                            if (Result == TFrmExtendedMessageBox.TResult.embrYes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                OfferToRunImportAgain = false;

                                if (DoNotShowMessageBoxEverytime)
                                {
                                    break;
                                }
                            }

                            count++;
                        }

                        // if the user has clicked yes to assigning Gift Destinations then offer to restart the import
                        if (OfferToRunImportAgain
                            && (MessageBox.Show(Catalog.GetString("Would you like to import this Gift Batch again?"),
                                    Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2)
                                == DialogResult.Yes))
                        {
                            Repeat = true;
                        }
                    }
                }
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Gift Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                SaveUserDefaults(dialog, impOptions);
                FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }
        }
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// </summary>
        /// <returns>True if the Export succeeded and a file was created, false otherwise</returns>
        public bool ExportBatches(bool AWithInteractionOnSuccess = true)
        {
            if (txtFilename.Text == String.Empty)
            {
                MessageBox.Show(Catalog.GetString("Please choose a location for the Export File."),
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }

            if (!Directory.Exists(Path.GetDirectoryName(txtFilename.Text)))
            {
                MessageBox.Show(Catalog.GetString("Please select an existing directory for this file!"),
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                txtFilename.Text = string.Empty;
                return false;
            }

            if (File.Exists(txtFilename.Text))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                        Catalog.GetString("Export Gifts"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    return false;
                }

                try
                {
                    File.Delete(txtFilename.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(String.Format(
                            Catalog.GetString(
                                "Failed to delete the file. Maybe it is already open in another application?  The system message was:{0}{1}"),
                            Environment.NewLine, ex.Message),
                        Catalog.GetString("Export Gift Batches"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return false;
                }
            }

            if (rbtBatchNumberSelection.Checked)
            {
                if (!txtBatchNumberStart.NumberValueInt.HasValue)
                {
                    txtBatchNumberStart.NumberValueInt = 0;
                }

                if (!txtBatchNumberEnd.NumberValueInt.HasValue)
                {
                    txtBatchNumberEnd.NumberValueInt = 999999;
                }
            }
            else
            {
                if ((dtpDateFrom.Text == "") || (dtpDateTo.Text == ""))
                {
                    MessageBox.Show(Catalog.GetString("Start and end dates must be provided."),
                        Catalog.GetString("Error"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return false;
                }

                if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate()))  // If ValidDate fails, it displays a helpful message.
                {
                    return false;
                }
            }

            String numberFormat = ConvertNumberFormat(cmbNumberFormat);
            String delimiter = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

            if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == ".")))
            {
                MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."),
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }

            try
            {
                Hashtable requestParams = new Hashtable();
                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", delimiter);
                requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
                requestParams.Add("Summary", rbtSummary.Checked);
                requestParams.Add("IncludeUnposted", chkIncludeUnposted.Checked);
                requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
                requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
                requestParams.Add("RecipientNumber", Convert.ToInt64(txtDetailRecipientKey.Text));
                requestParams.Add("FieldNumber", Convert.ToInt64(txtDetailFieldKey.Text));
                requestParams.Add("DateForSummary", dtpDateSummary.Date);
                requestParams.Add("NumberFormat", numberFormat);
                requestParams.Add("ExtraColumns", chkExtraColumns.Checked);

                if (rbtBatchNumberSelection.Checked)
                {
                    requestParams.Add("BatchNumberStart", txtBatchNumberStart.NumberValueInt);
                    requestParams.Add("BatchNumberEnd", txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    requestParams.Add("BatchDateFrom", dtpDateFrom.Date);
                    requestParams.Add("BatchDateTo", dtpDateTo.Date);
                }

                TVerificationResultCollection AMessages = new TVerificationResultCollection();
                String exportString = null;
                Int32 BatchCount = 0;

                Thread ExportThread = new Thread(() => ExportAllGiftBatchData(
                        requestParams,
                        out exportString,
                        out AMessages,
                        out BatchCount));

                using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
                {
                    ExportDialog.ShowDialog();
                }

                if ((AMessages != null)
                    && (AMessages.Count > 0))
                {
                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        return false;
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                    }
                }

                SaveUserDefaults();

                //Process BatchCount value
                if (BatchCount == 0)
                {
                    MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"),
                        Catalog.GetString("Export"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Exclamation);
                    return false;
                }
                else if (BatchCount == -1)
                {
                    MessageBox.Show(Catalog.GetString("Gift batch export cancelled"),
                        Catalog.GetString("Export"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    return false;
                }
                else if (BatchCount == -2)
                {
                    MessageBox.Show(Catalog.GetString("Gift batch export failed"),
                        Catalog.GetString("Export"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
                    return false;
                }

                StreamWriter sw1 = new StreamWriter(txtFilename.Text,
                    false,
                    Encoding.GetEncoding(TAppSettingsManager.GetInt32("ExportGiftBatchEncoding", 1252)));
                sw1.Write(exportString);
                sw1.Close();
            }
            catch (Exception ex)
            {
                TLogging.Log("GiftBatchExport.ManualCode: " + ex.ToString());
                MessageBox.Show(ex.Message,
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                return false;
            }

            if (AWithInteractionOnSuccess)
            {
                if (MessageBox.Show(Catalog.GetString(
                            "Gift Batches Exported successfully. Would you like to open the file in your default application?"),
                        Catalog.GetString("Gift Batch Export"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Information,
                        MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    ProcessStartInfo si = new ProcessStartInfo(txtFilename.Text);
                    si.UseShellExecute = true;
                    si.Verb = "open";

                    Process p = new Process();
                    p.StartInfo = si;
                    p.Start();
                }
            }

            return true;
        }
        private void TrainingLastMonth(object sender, EventArgs e)
        {
            Thread t = new Thread(() => TrainBankStatementsLastMonth());

            using (TProgressDialog dialog = new TProgressDialog(t))
            {
                if (dialog.ShowDialog() == DialogResult.Cancel)
                {
                    MessageBox.Show("Das Trainieren wurde abgebrochen");
                }

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    MessageBox.Show("Das Trainieren war erfolgreich");
                }
            }
        }
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// </summary>
        private void ExportBatches(object sender, EventArgs e)
        {
            if (rbtBatchNumberSelection.Checked)
            {
                if (!txtBatchNumberStart.NumberValueInt.HasValue)
                {
                    txtBatchNumberStart.NumberValueInt = 0;
                }

                if (!txtBatchNumberEnd.NumberValueInt.HasValue)
                {
                    txtBatchNumberEnd.NumberValueInt = 999999;
                }
            }
            else
            {
                if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate()))
                {
                    return;
                }
            }

            if (File.Exists(txtFilename.Text))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                        Catalog.GetString("Export Batches"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            StreamWriter sw1 = null;
            try
            {
                sw1 = new StreamWriter(txtFilename.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,
                    Catalog.GetString("Failed to open file"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            String dateFormatString = cmbDateFormat.GetSelectedString();

            // might be called from the main navigation window (FMainDS is null), or from the GL Batch screen (reusing MainDS)
            if (FMainDS == null)
            {
                FMainDS = new Ict.Petra.Shared.MFinance.GL.Data.GLBatchTDS();
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatch(FLedgerNumber, -1, -1));
            }

            Int32 ALedgerNumber = 0;

            ArrayList batches = new ArrayList();

            foreach (ABatchRow batch in FMainDS.ABatch.Rows)
            {
                // check conditions for exporting this batch
                // Batch Status
                bool exportThisBatch = batch.BatchStatus.Equals(MFinanceConstants.BATCH_POSTED)
                                       || (chkIncludeUnposted.Checked && batch.BatchStatus.Equals(MFinanceConstants.BATCH_UNPOSTED));

                if (rbtBatchNumberSelection.Checked)
                {
                    exportThisBatch &= (batch.BatchNumber >= txtBatchNumberStart.NumberValueInt);
                    exportThisBatch &= (batch.BatchNumber <= txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    exportThisBatch &= (batch.DateEffective >= dtpDateFrom.Date);
                    exportThisBatch &= (batch.DateEffective <= dtpDateTo.Date);
                }

                if (exportThisBatch)
                {
                    batches.Add(batch.BatchNumber);
                }

                ALedgerNumber = batch.LedgerNumber;
            }

            if (batches.Count == 0)
            {
                MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"),
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            Hashtable requestParams = new Hashtable();
            requestParams.Add("ALedgerNumber", ALedgerNumber);
            requestParams.Add("Delimiter", ConvertDelimiter(cmbDelimiter.GetSelectedString(), false));
            requestParams.Add("DateFormatString", dateFormatString);
            requestParams.Add("Summary", rbtSummary.Checked);
            requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
            requestParams.Add("BaseCurrency", FMainDS.ALedger[0].BaseCurrency);
            requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
            requestParams.Add("bDontSummarize", chkDontSummarize.Checked);
            requestParams.Add("DontSummarizeAccount", cmbDontSummarizeAccount.GetSelectedString());
            requestParams.Add("DateForSummary", dtpDateSummary.Date);
            requestParams.Add("NumberFormat", ConvertNumberFormat(cmbNumberFormat));

            String exportString = null;

            Thread ExportThread = new Thread(() => ExportAllGLBatchData(ref batches, requestParams, out exportString));
            using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
            {
                ExportDialog.ShowDialog();
            }

            sw1.Write(exportString);
            sw1.Close();

            MessageBox.Show(Catalog.GetString("Your data was exported successfully!"),
                Catalog.GetString("Success"),
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);

            SaveUserDefaults();
        }
        /// <summary>
        /// asks the user to open a csv file and imports the contents according to the config file
        /// </summary>
        /// <param name="AStatementKey">this returns the first key of a statement that was imported. depending on the implementation, several statements can be created from one file</param>
        /// <param name="ALedgerNumber">the current ledger number</param>
        /// <param name="ABankAccountCode">the bank account against which the statement should be stored</param>
        /// <returns></returns>
        public bool ImportBankStatement(out Int32 AStatementKey, Int32 ALedgerNumber, string ABankAccountCode)
        {
            AStatementKey = -1;

            // each time the button btnImportNewStatement is clicked, do a split and move action
            SplitFilesAndMove();
            ArchiveFilesLastMonth(ALedgerNumber);

            OpenFileDialog DialogOpen = new OpenFileDialog();

            DialogOpen.Filter = Catalog.GetString("bank statement CAMT (*.xml)|*.xml");

            if (TAppSettingsManager.HasValue("BankimportPath" + ALedgerNumber.ToString()))
            {
                DialogOpen.InitialDirectory = TAppSettingsManager.GetValue("BankimportPath" + ALedgerNumber.ToString());
            }
            else
            {
                DialogOpen.RestoreDirectory = true;
            }

            DialogOpen.Multiselect = true;
            DialogOpen.Title = Catalog.GetString("Please select the bank statement to import");

            if (DialogOpen.ShowDialog() != DialogResult.OK)
            {
                return false;
            }

            BankImportTDS MainDS = new BankImportTDS();

            // import several files at once
            foreach (string BankStatementFilename in DialogOpen.FileNames)
            {
                if (!ImportFromFile(BankStatementFilename,
                        ABankAccountCode,
                        ref MainDS))
                {
                    return false;
                }
            }

            if (MainDS.AEpStatement.Count > 0)
            {
                foreach (AEpStatementRow stmt in MainDS.AEpStatement.Rows)
                {
                    MainDS.AEpTransaction.DefaultView.RowFilter =
                        String.Format("{0}={1}",
                            AEpTransactionTable.GetStatementKeyDBName(),
                            stmt.StatementKey);

                    stmt.LedgerNumber = ALedgerNumber;
                }

                Thread t = new Thread(() => ProcessStatementsOnServer(MainDS));

                using (TProgressDialog dialog = new TProgressDialog(t))
                {
                    if (dialog.ShowDialog() == DialogResult.Cancel)
                    {
                        return false;
                    }
                    else
                    {
                        AStatementKey = FStatementKey;
                        return FStatementKey != -1;
                    }
                }
            }

            return false;
        }
        /// <summary>
        /// this supports the transaction export files from Petra 2.x.
        /// Lines do NOT start with T for transaction
        /// </summary>
        public void ImportTransactions(ABatchRow ACurrentBatchRow, AJournalRow ACurrentJournalRow, TImportDataSourceEnum AImportDataSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges && !FMyForm.SaveChanges())
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save your changes before Importing new transactions"), Catalog.GetString(
                        "Import GL Transactions"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if ((ACurrentBatchRow == null)
                || (ACurrentJournalRow == null)
                || (ACurrentJournalRow.JournalStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                MessageBox.Show(Catalog.GetString("Please select an unposted journal to import transactions."),
                    Catalog.GetString("Import GL Transactions"));
                return;
            }

            if (ACurrentJournalRow.LastTransactionNumber > 0)
            {
                if (MessageBox.Show(Catalog.GetString(
                            "The current journal already contains some transactions.  Do you really want to add more transactions to this journal?"),
                        Catalog.GetString("Import GL Transactions"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return;
                }
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportDataSource == TImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath = TUserDefaults.GetStringDefault("Imp Filename",
                    exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("GL Transactions files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Transaction Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                TVerificationResultCollection AMessages = new TVerificationResultCollection();

                Thread ImportThread = new Thread(() => ImportGLTransactions(requestParams,
                        importString,
                        ACurrentBatchRow.BatchNumber,
                        ACurrentJournalRow.JournalNumber,
                        out AMessages,
                        out ok));

                using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                {
                    ImportDialog.ShowDialog();
                }

                // It is important to save user defaults here, even if there were errors
                //   because in that case the user will want to import the same file again after fixing it.
                SaveUserDefaults(dialog, impOptions);
                ShowMessages(AMessages);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Transactions Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                // Update the client side with new information from the server
                FMyForm.Cursor = Cursors.WaitCursor;
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadABatchAJournal(FLedgerNumber, ACurrentBatchRow.BatchNumber));
                FMainDS.Merge(TRemote.MFinance.GL.WebConnectors.LoadATransactionATransAnalAttrib(FLedgerNumber,
                        ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber));
                FMainDS.AcceptChanges();
                FMyForm.Cursor = Cursors.Default;

                FMyForm.GetTransactionsControl().SelectRow(1);
            }
        }
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// The code handles importing from file or clipboard
        /// </summary>
        public void ImportBatches(TImportDataSourceEnum AImportDataSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                        "Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportDataSource == TImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                string exportPath = TClientSettings.GetExportPath();
                string fullPath = TUserDefaults.GetStringDefault("Imp Filename",
                    exportPath + Path.DirectorySeparatorChar + "import.csv");
                TImportExportDialogs.SetOpenFileDialogFilePathAndName(dialog, fullPath, exportPath);

                dialog.Title = Catalog.GetString("Import Batches from CSV File");
                dialog.Filter = Catalog.GetString("GL Batches files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                // This call fixes Windows7 Open File Dialogs.  It must be the line before ShowDialog()
                TWin7FileOpenSaveDialog.PrepareDialog(Path.GetFileName(fullPath));

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Batch Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return;
                    }

                    importString = File.ReadAllText(dialog.FileName, Encoding.Default);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);


                TVerificationResultCollection AMessages = new TVerificationResultCollection();

                Thread ImportThread = new Thread(() => ImportGLBatches(
                        requestParams,
                        importString,
                        out AMessages,
                        out ok));

                using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                {
                    ImportDialog.ShowDialog();
                }

                // We save the defaults even if ok is false - because the client will probably want to try and import
                //   the same file again after correcting any errors
                SaveUserDefaults(dialog, impOptions);
                ShowMessages(AMessages);
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Batch Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                FMyUserControl.ReloadBatches();
                FPetraUtilsObject.DisableSaveButton();
            }
        }
Exemplo n.º 12
0
        /// delete ledger
        public static void DeleteLedger(Form AMainWindow, Int32 ALedgerNumber)
        {
            string LedgerNameAndNumber = TFinanceControls.GetLedgerNumberAndName(ALedgerNumber);

            if (MessageBox.Show(Catalog.GetString("Please save a backup of your database first!!!") + Environment.NewLine +
                    string.Format(Catalog.GetString("Do you REALLY want to delete ledger '{0}'?"),
                        LedgerNameAndNumber),
                    Catalog.GetString("Delete Ledger"),
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3
                    ) == DialogResult.Yes)
            {
                // ledger cannot be deleted if there are any transactions existing for it
                if (TRemote.MFinance.Setup.WebConnectors.ContainsTransactions(ALedgerNumber))
                {
                    MessageBox.Show(
                        string.Format(Catalog.GetString("There are still transactions associated with Ledger '{0}'. \r\n\r\nNothing has been done."),
                            LedgerNameAndNumber),
                        Catalog.GetString("Deletion not possible"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
                else
                {
                    Thread t = new Thread(() => ProcessDeletion(AMainWindow, ALedgerNumber, LedgerNameAndNumber));

                    using (TProgressDialog dialog = new TProgressDialog(t))
                    {
                        dialog.AllowCancellation = false;
                        dialog.ShowDialog();
                    }

                    // reload list of Ledger names
                    TDataCache.TMFinance.RefreshCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerNameList);

                    // reload navigation

                    // Setting the "CurrentLedger" to -1 isn't strictly needed, but it eradicates the Ledger
                    // we have presently deleted to make sure the Main Menu isn't working any further with a
                    // Ledger that doesn't exist anymore.
                    PropertyInfo CurrentLedgerProperty = AMainWindow.GetType().GetProperty("CurrentLedger");
                    CurrentLedgerProperty.SetValue(AMainWindow, -1, null);

                    MethodInfo method = AMainWindow.GetType().GetMethod("LoadNavigationUI");

                    if (method != null)
                    {
                        method.Invoke(AMainWindow, new object[] { false });
                        method = AMainWindow.GetType().GetMethod("SelectFinanceFolder");
                        method.Invoke(AMainWindow, new object[] { });
                    }
                }
            }
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            new TLogging("../../log/TestRemotingClient.log");

            try
            {
                new TAppSettingsManager("../../etc/Client.config");

                TLogging.DebugLevel = Convert.ToInt32(TAppSettingsManager.GetValue("Client.DebugLevel", "0"));

                new TClientSettings();

                // initialize the client
                new TRemoteTest();

                // need to call this as well to make the progress dialog work
                new TRemote();

                // allow self signed ssl certificate for test purposes
                ServicePointManager.ServerCertificateValidationCallback = delegate {
                    return true;
                };

                THttpConnector.InitConnection(TAppSettingsManager.GetValue("OpenPetra.HTTPServer"));

                TClientInfo.InitializeUnit();

                Catalog.Init("en-GB", "en-GB");

                SortedList <string, object>Parameters = new SortedList <string, object>();
                Parameters.Add("username", "demo");
                Parameters.Add("password", "demo");
                Parameters.Add("version", TFileVersionInfo.GetApplicationVersion().ToString());

                List <object>ResultList = THttpConnector.CallWebConnector("SessionManager", "LoginClient", Parameters, "list");
                eLoginEnum Result = (eLoginEnum)ResultList[0];

                if (Result != eLoginEnum.eLoginSucceeded)
                {
                    // failed login
                    return;
                }

                IMyUIConnector MyUIConnector = TRemoteTest.MyService.SubNamespace.MyUIConnector();
                TRemoteTest.TMyService.TMySubNamespace test = TRemoteTest.MyService.SubNamespace;

                while (true)
                {
                    try
                    {
                        TLogging.Log("before call");
                        TLogging.Log(TRemoteTest.MyService.HelloWorld("Hello World"));
                        TLogging.Log("after call");
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("problem with MyService HelloWorld: " + Environment.NewLine + e.ToString());
                    }

                    try
                    {
                        DateTime DateTomorrow;
                        TLogging.Log("should show today's date: " + TRemoteTest.MyService.TestDateTime(DateTime.Today,
                                out DateTomorrow).ToShortDateString());
                        TLogging.Log("should show tomorrow's date: " + DateTomorrow.ToShortDateString());
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("problem with TestDateTime: " + Environment.NewLine + e.ToString());
                    }

                    try
                    {
                        TLogging.Log(test.HelloSubWorld("Hello SubWorld"));
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("problem with sub namespace HelloSubWorld: " + Environment.NewLine + e.ToString());
                    }

                    try
                    {
                        TLogging.Log(MyUIConnector.HelloWorldUIConnector());
                    }
                    catch (Exception e)
                    {
                        TLogging.Log("problem with HelloWorldUIConnector: " + Environment.NewLine + e.ToString());
                    }

                    // start long running job
                    Thread t = new Thread(() => TRemoteTest.MyService.LongRunningJob());

                    using (TProgressDialog dialog = new TProgressDialog(t))
                    {
                        if (dialog.ShowDialog() == DialogResult.Cancel)
                        {
                            return;
                        }
                    }

                    Console.WriteLine("Press ENTER to say Hello World again... ");
                    Console.WriteLine("Press CTRL-C to exit ...");
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                Console.ReadLine();
            }
        }
        /// <summary>
        /// export all partners in selected extract
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool ExportPartnersInExtract(System.Object sender, EventArgs e)
        {
            Boolean Result = false;

            if (!WarnIfNotSingleSelection(Catalog.GetString("Export Partners in Extract"))
                && (GetSelectedDetailRow() != null))
            {
                String FileName = TImportExportDialogs.GetExportFilename(Catalog.GetString("Save Partners into File"));

                if (FileName.Length > 0)
                {
                    bool ExportFamiliesPersons = false;

                    bool ContainsFamily = TRemote.MPartner.ImportExport.WebConnectors.CheckExtractContainsFamily(GetSelectedDetailRow().ExtractId);

                    if (ContainsFamily)
                    {
                        if (MessageBox.Show(
                                Catalog.GetString("When exporting a FAMILY record do you want to also export all associated PERSON records?"),
                                Catalog.GetString("Export Partners"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            ExportFamiliesPersons = true;
                        }
                    }

                    this.Cursor = Cursors.WaitCursor;

                    if (FileName.EndsWith("ext"))
                    {
                        string Doc = string.Empty;

                        // run in thread so we can have Progress Dialog
                        Thread t = new Thread(() => ExportToFile(ExportFamiliesPersons, ref Doc));

                        using (TProgressDialog dialog = new TProgressDialog(t))
                        {
                            dialog.ShowDialog();
                        }

                        // null if the user cancelled the operation
                        if (Doc == null)
                        {
                            MessageBox.Show(Catalog.GetString("Export cancelled."), Catalog.GetString(
                                    "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.Cursor = Cursors.Default;
                            return false;
                        }

                        Result = TImportExportDialogs.ExportTofile(Doc, FileName);

                        if (!Result)
                        {
                            MessageBox.Show(Catalog.GetString("Export of Partners in Extract failed!"), Catalog.GetString(
                                    "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            MessageBox.Show(Catalog.GetString("Export of Partners in Extract finished"), Catalog.GetString(
                                    "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        // XmlDocument doc = new XmlDocument();
                        MessageBox.Show(Catalog.GetString("Export with this format is not yet supported!"), Catalog.GetString(
                                "Export Partners"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        // doc.LoadXml(TRemote.MPartner.ImportExport.WebConnectors.ExportExtractPartners(GetSelectedDetailRow().ExtractId, false));
                        // Result = TImportExportDialogs.ExportTofile(doc, FileName);
                    }

                    this.Cursor = Cursors.Default;
                }

                return Result;
            }

            return false;
        }
        /// <summary>
        /// this is useful for the situation, where we are using OpenPetra only for the bankimport,
        /// but need to post the gift batches in the old Petra 2.x database
        /// </summary>
        private void ExportGiftBatch(bool AWithInteractionOnSuccess = true)
        {
            // TODO: should we first ask? also when closing the window?
            SaveChanges();

            // load the transactions of the selected statement, and the matches
            Thread t = new Thread(() => ExportGiftBatchThread(AWithInteractionOnSuccess));

            using (TProgressDialog dialog = new TProgressDialog(t))
            {
                dialog.ShowDialog();
            }
        }
Exemplo n.º 16
0
        /// delete the complete conference including all conference data
        public static void DeleteConference(Form AMainWindow, Int64 AConferenceKey, string AConferenceName)
        {
            if (MessageBox.Show(Catalog.GetString("Please save a backup of your database first!!!") + Environment.NewLine +
                    string.Format(Catalog.GetString("Do you REALLY want to delete conference '{0}'?"),
                        AConferenceName),
                    Catalog.GetString("Delete Conference"),
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2
                    ) == DialogResult.Yes)
            {
                Thread t = new Thread(() => ProcessDeletion(AMainWindow, AConferenceKey, AConferenceName));

                using (TProgressDialog dialog = new TProgressDialog(t))
                {
                    dialog.ShowDialog();
                }

                if (AConferenceKey == TUserDefaults.GetInt64Default("LASTCONFERENCEWORKEDWITH"))
                {
                    // update user defaults table
                    TUserDefaults.SetDefault(TUserDefaults.CONFERENCE_LASTCONFERENCEWORKEDWITH, 0);

                    // reload navigation
                    PropertyInfo CurrentConferenceProperty = AMainWindow.GetType().GetProperty("SelectedConferenceKey");
                    CurrentConferenceProperty.SetValue(AMainWindow, 0, null);

                    MethodInfo method = AMainWindow.GetType().GetMethod("LoadNavigationUI");

                    if (method != null)
                    {
                        method.Invoke(AMainWindow, new object[] { false });
                        method = AMainWindow.GetType().GetMethod("SelectConferenceFolder");
                        method.Invoke(AMainWindow, new object[] { });
                    }
                }
            }
        }
        /// <summary>
        /// select the bank statement that should be loaded
        /// </summary>
        /// <param name="AStatementKey"></param>
        private void SelectBankStatement(Int32 AStatementKey)
        {
            CurrentlySelectedMatch = null;
            CurrentStatement = null;

            // merge the cost centres and the motivation details from the cacheable tables
            FMainDS.ACostCentre.Merge(TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList, FLedgerNumber));
            FMainDS.AMotivationDetail.Merge(TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.MotivationList, FLedgerNumber));
            FMainDS.ACostCentre.AcceptChanges();
            FMainDS.AMotivationDetail.AcceptChanges();

            // load the transactions of the selected statement, and the matches
            Thread t = new Thread(() => GetBankStatementTransactionsAndMatches(AStatementKey));

            using (TProgressDialog dialog = new TProgressDialog(t))
            {
                if (dialog.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }
            }

            while (FMainDS.AEpStatement.Rows.Count != 1)
            {
                // wait for the merging of the dataset to finish in the thread
                Thread.Sleep(300);
            }

            // an old version of the CSV import plugin did not set the potential gift typecode
            foreach (AEpTransactionRow r in FMainDS.AEpTransaction.Rows)
            {
                if (r.IsTransactionTypeCodeNull() && (r.TransactionAmount > 0))
                {
                    r.TransactionTypeCode = MFinanceConstants.BANK_STMT_POTENTIAL_GIFT;
                }
            }

            CurrentStatement = (AEpStatementRow)FMainDS.AEpStatement[0];

            FTransactionView = FMainDS.AEpTransaction.DefaultView;
            FTransactionView.AllowNew = false;
            FTransactionView.Sort = AEpTransactionTable.GetOrderDBName() + " ASC";
            grdAllTransactions.DataSource = new DevAge.ComponentModel.BoundDataView(FTransactionView);

            TFinanceControls.InitialiseMotivationGroupList(ref cmbMotivationGroup, FLedgerNumber, true);
            TFinanceControls.InitialiseMotivationDetailList(ref cmbMotivationDetail, FLedgerNumber, true);
            TFinanceControls.InitialiseCostCentreList(ref cmbGLCostCentre, FLedgerNumber, true, false, true, true);
            TFinanceControls.InitialiseAccountList(ref cmbGLAccount, FLedgerNumber, true, false, true, false);

            FMatchView = FMainDS.AEpMatch.DefaultView;
            FMatchView.AllowNew = false;
            grdGiftDetails.DataSource = new DevAge.ComponentModel.BoundDataView(FMatchView);

            TFinanceControls.InitialiseAccountList(ref cmbBankAccount, FLedgerNumber, true, false, true, true);

            if (CurrentStatement != null)
            {
                FMainDS.AEpStatement.DefaultView.RowFilter = String.Format("{0}={1}",
                    AEpStatementTable.GetStatementKeyDBName(),
                    CurrentStatement.StatementKey);
                cmbBankAccount.SetSelectedString(CurrentStatement.BankAccountCode);
                txtBankStatement.Text = CurrentStatement.Filename;
                dtpBankStatementDate.Date = CurrentStatement.Date;
                FMainDS.AEpStatement.DefaultView.RowFilter = string.Empty;
            }

            TransactionFilterChanged(null, null);
            grdAllTransactions.SelectRowInGrid(1);
            grdAllTransactions.AutoResizeGrid();
        }
        /// <summary>
        /// this supports the batch export files from Petra 2.x.
        /// Each line starts with a type specifier, B for batch, J for journal, T for transaction
        /// </summary>
        public void ExportBatches(bool AWithInteractionOnSuccess = true)
        {
            if (File.Exists(txtFilename.Text))
            {
                if (MessageBox.Show(Catalog.GetString("The file already exists. Is it OK to overwrite it?"),
                        Catalog.GetString("Export Gifts"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            StreamWriter sw1 = null;

            try
            {
                sw1 = new StreamWriter(txtFilename.Text,
                    false,
                    Encoding.GetEncoding(TAppSettingsManager.GetInt32("ExportGiftBatchEncoding", 1252)));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,
                    Catalog.GetString("Failed to open file"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            try
            {
                if (rbtBatchNumberSelection.Checked)
                {
                    if (!txtBatchNumberStart.NumberValueInt.HasValue)
                    {
                        txtBatchNumberStart.NumberValueInt = 0;
                    }

                    if (!txtBatchNumberEnd.NumberValueInt.HasValue)
                    {
                        txtBatchNumberEnd.NumberValueInt = 999999;
                    }
                }
                else
                {
                    if ((dtpDateFrom.Text == "") || (dtpDateTo.Text == ""))
                    {
                        MessageBox.Show(Catalog.GetString("Start and end dates must be provided."),
                            Catalog.GetString("Error"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        return;
                    }

                    if ((!dtpDateFrom.ValidDate()) || (!dtpDateTo.ValidDate()))  // If ValidDate fails, it displays a helpful message.
                    {
                        return;
                    }
                }

                String numberFormat = ConvertNumberFormat(cmbNumberFormat);
                String delimiter = ConvertDelimiter(cmbDelimiter.GetSelectedString(), false);

                if (((numberFormat == "European") && (delimiter == ",")) || ((numberFormat == "American") && (delimiter == ".")))
                {
                    MessageBox.Show(Catalog.GetString("Numeric Decimal cannot be the same as the delimiter."),
                        Catalog.GetString("Error"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return;
                }

                Hashtable requestParams = new Hashtable();
                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", delimiter);
                requestParams.Add("DateFormatString", cmbDateFormat.GetSelectedString());
                requestParams.Add("Summary", rbtSummary.Checked);
                requestParams.Add("IncludeUnposted", chkIncludeUnposted.Checked);
                requestParams.Add("bUseBaseCurrency", rbtBaseCurrency.Checked);
                requestParams.Add("TransactionsOnly", chkTransactionsOnly.Checked);
                requestParams.Add("RecipientNumber", Convert.ToInt64(txtDetailRecipientKey.Text));
                requestParams.Add("FieldNumber", Convert.ToInt64(txtDetailFieldKey.Text));
                requestParams.Add("DateForSummary", dtpDateSummary.Date);
                requestParams.Add("NumberFormat", numberFormat);
                requestParams.Add("ExtraColumns", chkExtraColumns.Checked);

                if (rbtBatchNumberSelection.Checked)
                {
                    requestParams.Add("BatchNumberStart", txtBatchNumberStart.NumberValueInt);
                    requestParams.Add("BatchNumberEnd", txtBatchNumberEnd.NumberValueInt);
                }
                else
                {
                    requestParams.Add("BatchDateFrom", dtpDateFrom.Date);
                    requestParams.Add("BatchDateTo", dtpDateTo.Date);
                }

                TVerificationResultCollection AMessages = new TVerificationResultCollection();
                String exportString = null;
                Int32 BatchCount = 0;

                Thread ExportThread = new Thread(() => ExportAllGiftBatchData(
                        requestParams,
                        out exportString,
                        out AMessages,
                        out BatchCount));

                using (TProgressDialog ExportDialog = new TProgressDialog(ExportThread))
                {
                    ExportDialog.ShowDialog();
                }

                if ((AMessages != null)
                    && (AMessages.Count > 0))
                {
                    if (!TVerificationHelper.IsNullOrOnlyNonCritical(AMessages))
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Error"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        MessageBox.Show(AMessages.BuildVerificationResultString(), Catalog.GetString("Warnings"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                    }
                }

                if (BatchCount == 0)
                {
                    MessageBox.Show(Catalog.GetString("There are no batches matching your criteria"),
                        Catalog.GetString("Error"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return;
                }

                sw1.Write(exportString);
                sw1.Close();

                SaveUserDefaults();

                if (AWithInteractionOnSuccess)
                {
                    MessageBox.Show(Catalog.GetString("Gift Batches Exported successfully."),
                        Catalog.GetString("Gift Batch Export"),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                TLogging.Log("GiftBatchExport.ManualCode: " + ex.ToString());
                MessageBox.Show(ex.Message,
                    Catalog.GetString("Error"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
            finally
            {
                sw1.Close();
            }
        }
        // starts the merge process
        private void BtnOK_Click(Object Sender, EventArgs e)
        {
            FFromPartnerKey = Convert.ToInt64(txtMergeFrom.Text);
            FToPartnerKey = Convert.ToInt64(txtMergeTo.Text);

            if (CheckPartnersCanBeMerged()
                && (MessageBox.Show(Catalog.GetString("WARNING: A Partner Merge operation cannot be undone and the From-Partner will be no longer " +
                            "accessible after the Partner Merge operation!") + "\n\n" + Catalog.GetString("Are you sure you want to continue?"),
                        Catalog.GetString("Merge Partners"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes))
            {
                bool[] Categories = new bool[20];

                for (int i = 1; i < 20; i++)
                {
                    Categories[i] = true;
                }

                FSiteKeys = null;
                FLocationKeys = null;
                FMainBankingDetailsKey = -1;
                bool DifferentFamilies = false;

                // open a dialog to select which To Partner's addresses should be merged
                if (GetSelectedAddresses() == false)
                {
                    MessageBox.Show(Catalog.GetString("Merge cancelled."));
                    return;
                }

                // open a dialog to select which bank account should be set to MAIN (if necessary)
                if (GetMainBankAccount() == false)
                {
                    MessageBox.Show(Catalog.GetString("Merge cancelled."));
                    return;
                }

                //
                if ((((FFromPartnerClass == TPartnerClass.FAMILY) && (FToPartnerClass == TPartnerClass.FAMILY))
                     || (FFromPartnerClass == TPartnerClass.PERSON))
                    && (GiftDestinationToMerge(out Categories[0]) == false))
                {
                    MessageBox.Show(Catalog.GetString("Merge cancelled."));
                    return;
                }

                Thread t =
                    new Thread(() => MergeTwoPartners(Categories, ref DifferentFamilies));

                using (TProgressDialog dialog = new TProgressDialog(t))
                {
                    if ((dialog.ShowDialog() == DialogResult.Cancel) && (WebConnectorResult == true))
                    {
                        MessageBox.Show(Catalog.GetString("Merge cancelled."));
                        return;
                    }
                    else if (!WebConnectorResult)   // if merge is unsuccessful
                    {
                        MessageBox.Show(Catalog.GetString("Merge failed. Please check the Server.log file on the server"));
                        dialog.Close();
                        return;
                    }
                }

                if (DifferentFamilies)
                {
                    MessageBox.Show(String.Format(Catalog.GetString("Partners were in different families.")) + "\n\n" +
                        Catalog.GetString("FAMILY relations of the From Partner are not taken over to the To Partner!") + "\n\n" +
                        Catalog.GetString("Please check the family relations of the To Partner after completion."),
                        Catalog.GetString("Merge Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                MessageBox.Show(String.Format(Catalog.GetString("Merge of Partner {0} into {1} complete."), FFromPartnerKey, FToPartnerKey) +
                    "\n\n" + Catalog.GetString("If necessary, edit the merged Partner to correct any information that may not have been " +
                        "merged and correct information that may have been overwritten.") + "\n\n" +
                    Catalog.GetString("Tip: You can use the 'Work with Last Partner' command in the Partner module and the " +
                        "'Work with Last Person' command in the Personnel module to view and edit the merged Partner."),
                    Catalog.GetString("Merge Partners"), MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }
        /// <summary>
        /// Import a transactions file or a clipboard equivalent
        /// </summary>
        /// <param name="ACurrentBatchRow">The batch to import to</param>
        /// <param name="AImportSource">The import source - eg File or Clipboard</param>
        /// <returns>True if the import was successful</returns>
        public bool ImportTransactions(AGiftBatchRow ACurrentBatchRow, TGiftImportDataSourceEnum AImportSource)
        {
            bool ok = false;
            String importString;
            String impOptions;
            OpenFileDialog dialog = null;

            if (FPetraUtilsObject.HasChanges)
            {
                // saving failed, therefore do not try to import
                MessageBox.Show(Catalog.GetString("Please save before calling this function!"), Catalog.GetString(
                        "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if ((ACurrentBatchRow == null) || (ACurrentBatchRow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                MessageBox.Show(Catalog.GetString("Please select an unposted batch to import transactions."), Catalog.GetString(
                        "Gift Import"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (ACurrentBatchRow.LastGiftNumber > 0)
            {
                if (MessageBox.Show(Catalog.GetString(
                            "The current batch already contains some gift transactions.  Do you really want to add more transactions to this batch?"),
                        Catalog.GetString("Gift Transaction Import"),
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button2) == DialogResult.No)
                {
                    return false;
                }
            }

            FdlgSeparator = new TDlgSelectCSVSeparator(false);

            if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
            {
                importString = Clipboard.GetText(TextDataFormat.UnicodeText);

                if ((importString == null) || (importString.Length == 0))
                {
                    MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"),
                        Catalog.GetString("Failure"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }

                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";American");
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.SelectedSeparator = "\t";
                FdlgSeparator.CSVData = importString;
                FdlgSeparator.DateFormat = dateFormatString;

                if (impOptions.Length > 1)
                {
                    FdlgSeparator.NumberFormat = impOptions.Substring(1);
                }
            }
            else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
            {
                dialog = new OpenFileDialog();

                dialog.FileName = TUserDefaults.GetStringDefault("Imp Filename",
                    TClientSettings.GetExportPath() + Path.DirectorySeparatorChar + "import.csv");

                dialog.Title = Catalog.GetString("Import Transactions from CSV File");
                dialog.Filter = Catalog.GetString("Gift Transactions files (*.csv)|*.csv");
                impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    Boolean fileCanOpen = FdlgSeparator.OpenCsvFile(dialog.FileName);

                    if (!fileCanOpen)
                    {
                        MessageBox.Show(Catalog.GetString("Unable to open file."),
                            Catalog.GetString("Gift Import"),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Stop);
                        return false;
                    }

                    importString = File.ReadAllText(dialog.FileName);

                    String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                    FdlgSeparator.DateFormat = dateFormatString;

                    if (impOptions.Length > 1)
                    {
                        FdlgSeparator.NumberFormat = impOptions.Substring(1);
                    }

                    FdlgSeparator.SelectedSeparator = impOptions.Substring(0, 1);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                // unknown source!!  The following need a value...
                impOptions = String.Empty;
                importString = String.Empty;
            }

            if (FdlgSeparator.ShowDialog() == DialogResult.OK)
            {
                Hashtable requestParams = new Hashtable();

                requestParams.Add("ALedgerNumber", FLedgerNumber);
                requestParams.Add("Delimiter", FdlgSeparator.SelectedSeparator);
                requestParams.Add("DateFormatString", FdlgSeparator.DateFormat);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);

                bool Repeat = true;

                while (Repeat)
                {
                    Repeat = false;

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();
                    GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber = new GiftBatchTDSAGiftDetailTable();

                    Thread ImportThread = new Thread(() => ImportGiftTransactions(
                            requestParams,
                            importString,
                            ACurrentBatchRow.BatchNumber,
                            out AMessages,
                            out ok,
                            out NeedRecipientLedgerNumber));

                    using (TProgressDialog ImportDialog = new TProgressDialog(ImportThread))
                    {
                        ImportDialog.ShowDialog();
                    }

                    ShowMessages(AMessages);

                    // if the import contains gifts with Motivation Group 'GIFT' and that have a Family recipient with no Gift Destination
                    // then the import will have failed and we need to alert the user
                    if (NeedRecipientLedgerNumber.Rows.Count > 0)
                    {
                        bool OfferToRunImportAgain = true;

                        // for each gift in which the recipient needs a Git Destination
                        foreach (GiftBatchTDSAGiftDetailRow Row in NeedRecipientLedgerNumber.Rows)
                        {
                            if (MessageBox.Show(string.Format(
                                        Catalog.GetString(
                                            "Gift Import has been cancelled as the recipient '{0}' ({1}) has no Gift Destination assigned."),
                                        Row.RecipientDescription, Row.RecipientKey) +
                                    "\n\n" +
                                    Catalog.GetString("Do you want to assign a Gift Destination to this partner now?"),
                                    Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                                == DialogResult.Yes)
                            {
                                // allow the user to assign a Gift Destingation
                                TFrmGiftDestination GiftDestinationForm = new TFrmGiftDestination(FPetraUtilsObject.GetForm(), Row.RecipientKey);
                                GiftDestinationForm.ShowDialog();
                            }
                            else
                            {
                                OfferToRunImportAgain = false;
                            }
                        }

                        // if the user has clicked yes to assigning Gift Destinations then offer to restart the import
                        if (OfferToRunImportAgain
                            && (MessageBox.Show(Catalog.GetString("Would you like to import these Gift Transactions again?"),
                                    Catalog.GetString("Gift Import"), MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button1)
                                == DialogResult.Yes))
                        {
                            Repeat = true;
                        }
                    }
                }
            }

            if (ok)
            {
                MessageBox.Show(Catalog.GetString("Your data was imported successfully!"),
                    Catalog.GetString("Gift Import"),
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                SaveUserDefaults(dialog, impOptions);
                //FMyUserControl.LoadBatchesForCurrentYear();
                FPetraUtilsObject.DisableSaveButton();
            }

            return ok;
        }
Exemplo n.º 21
0
        /// <summary>
        /// this will delete the current database, and reset it with the data selected
        /// </summary>
        /// <param name="AParentForm"></param>
        public static void RestoreDatabase(Form AParentForm)
        {
            string StrImportCancelledMsg = Catalog.GetString("Restoring of database got cancelled; no existing data has been deleted or modified!");
            string StrImportCancelledTitle = Catalog.GetString("Restore Cancelled");

            DialogResult r = MessageBox.Show(
                Catalog.GetString(
                    "WARNING: This will THROW AWAY ALL CURRENT DATA that is held in the database (including the users and passwords!) and replace it with the data that was previously backed up and which you chose to restore!\r\n\r\nDo you REALLY want to restore that data?"),
                Catalog.GetString("WARNING: Replace All Data With Previously Backed Up Data?"),
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning,
                MessageBoxDefaultButton.Button2);

            if (r == DialogResult.Yes)
            {
                string zippedYml = TImportExportDialogs.ImportWithDialogYMLGz(Catalog.GetString("Select Backup File to Restore From"));

                if (zippedYml != null)
                {
                    Thread ResetDBThread = new Thread(() => ResetDatabaseInThread(zippedYml));

                    using (TProgressDialog dialog = new TProgressDialog(ResetDBThread))
                    {
                        if (dialog.ShowDialog() == DialogResult.Cancel)
                        {
                            MessageBox.Show(StrImportCancelledMsg, StrImportCancelledTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);

                            return;
                        }
                    }

                    // Ensure that WebConnectorResult got set in Method 'ResetDatabaseInThread' before we get to the if statement below...
                    ResetDBThread.Join();

                    if (WebConnectorResult)
                    {
                        // TODO: reset all caches? for comboboxes etc
                        MessageBox.Show(Catalog.GetString(
                                "The data was successfully restored.\r\n\r\nPlease restart your OpenPetra Client immediately!"),
                            Catalog.GetString("Restore Successful"),
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(Catalog.GetString("The restoring of the data FAILED. No existing data has been deleted or modified!\r\n\r\n"
                                +
                                "Please check the Server.log file on the server for errors!"), Catalog.GetString("Restore Failed"),
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show(StrImportCancelledMsg, StrImportCancelledTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void StartCheck(Object Sender, EventArgs e)
        {
            // run in thread so we can have Progress Dialog
            Thread t = new Thread(() => TRemote.MPartner.Mailroom.WebConnectors.FindAddressDuplicates(ref FDuplicateLocations, chkNumber.Checked));

            using (TProgressDialog dialog = new TProgressDialog(t))
            {
                dialog.ShowDialog();
            }

            DataView myDataView = FDuplicateLocations.DefaultView;
            myDataView.Sort = "SiteKeyA ASC, LocationKeyA ASC, SiteKeyB ASC, LocationKeyB ASC";
            myDataView.AllowNew = false;
            grdResults.DataSource = new DevAge.ComponentModel.BoundDataView(myDataView);
            grdResults.AutoResizeGrid();

            UpdateRecordNumberDisplay();

            if (FDuplicateLocations.Rows.Count > 0)
            {
                btnMergeAddresses.Enabled = true;
                btnPrintReport.Enabled = true;
                mniFilePrint.Enabled = true;
                grdResults.SelectRowInGrid(1);
            }
            else
            {
                btnMergeAddresses.Enabled = false;
                btnPrintReport.Enabled = false;
                mniFilePrint.Enabled = false;
            }
        }