private void InitializeManualCode()
        {
            FInitiallySelectedLedger = TLstTasks.InitiallySelectedLedger;

            cmbDefaultLedger.SetSelectedInt32(FInitiallySelectedLedger);

            //Warn of inactive values on posting
            FInactiveValuesWarningOnGLPosting = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GL_WARN_OF_INACTIVE_VALUES_ON_POSTING,
                                                                                true);
            chkInactiveValuesWarningOnGLPosting.Checked = FInactiveValuesWarningOnGLPosting;

            FShowMoneyAsCurrency   = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_CURRENCY_FORMAT_AS_CURRENCY, true);
            chkMoneyFormat.Checked = FShowMoneyAsCurrency;

            FShowDecimalsAsCurrency  = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_DECIMAL_FORMAT_AS_CURRENCY, true);
            chkDecimalFormat.Checked = FShowDecimalsAsCurrency;

            FShowThousands           = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_CURRENCY_SHOW_THOUSANDS, true);
            chkShowThousands.Checked = FShowThousands;

            // Examples
            txtMoneyExample.Context            = ".MFinance";
            txtMoneyExample.ControlMode        = TTxtNumericTextBox.TNumericTextBoxMode.Currency;
            txtMoneyExample.CurrencyCode       = "USD";
            txtMoneyExample.NumberValueDecimal = 12345.67m;

            txtExchangeRateExample.Context            = ".MFinance";
            txtExchangeRateExample.ControlMode        = TTxtNumericTextBox.TNumericTextBoxMode.Decimal;
            txtExchangeRateExample.NumberValueDecimal = 6.789m;

            FDatesMayLookLikeIntegers     = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);
            chkDatesMayBeIntegers.Checked = FDatesMayLookLikeIntegers;
        }
示例#2
0
 /// <summary>
 /// todoComment
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 public void Form_KeyDown(System.Object sender, System.Windows.Forms.KeyEventArgs e)
 {
     if (e.KeyCode == Keys.Escape)
     {
         if (FWindowExtensions.AContainerControlWantsEscape(sender) ||
             (TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_ESC_CLOSES_SCREEN, true) == false) ||
             (this.FWinForm.Name == "TFrmMainWindowNew"))
         {
             // Either the user default is NOT to use the ESC key to close screens
             // or there is a control on the form that needs to handle the escape key,
             // or we are the main window
             //  so we do nothing and the keyDown message will get passed to the control - which will do something if it needs to
         }
         else
         {
             // No control wants the escape key so we are free to handle the KeyDown message at the Form level
             e.Handled = true;
             ExecuteAction(eActionId.eClose);
         }
     }
     else if (e.KeyCode == Keys.F1)
     {
         e.Handled = true;
         ExecuteAction(eActionId.eHelp);
     }
 }
        /// <summary>
        /// load or reload the navigation
        /// </summary>
        public void LoadNavigationUI(bool ADontUseDefaultLedger = false)
        {
            // Force re-calculation of available Ledgers and correct setting of FCurrentLedger
            FLedgersAvailableToUser = null;

            XmlNode MainMenuNode   = BuildNavigationXml(ADontUseDefaultLedger);
            XmlNode DepartmentNode = MainMenuNode.FirstChild;

            lstFolders.MultiLedgerSite    = FMultiLedgerSite;
            lstFolders.CurrentLedger      = FCurrentLedger;
            lstFolders.ConferenceSelected = FConferenceSelected;

            lstFolders.ClearFolders();

            lstFolders.SubmoduleChanged += delegate(TTaskList ATaskList, XmlNode ATaskListNode, LinkLabel AItemClicked, object AOtherData)
            {
                OnSubmoduleChanged(ATaskList, ATaskListNode, AItemClicked);
            };
            lstFolders.LedgerChanged += delegate(int ALedgerNr, string ALedgerName)
            {
                OnLedgerChanged(ALedgerNr, ALedgerName);
            };

            TPnlModuleNavigation.SubSystemLinkStatus += delegate(int ALedgerNr, TPnlCollapsible APnlCollapsible)
            {
                UpdateSubsystemLinkStatus(ALedgerNr, APnlCollapsible);
            };

            TFrmGLEnableSubsystems.FinanceSubSystemLinkStatus += delegate()
            {
                UpdateFinanceSubsystemLinkStatus();
            };

            TLstTasks.Init(UserInfo.GUserInfo.UserID, HasAccessPermission, FTaxDeductiblePercentageEnabled);

            while (DepartmentNode != null)
            {
                lstFolders.AddFolder(DepartmentNode, UserInfo.GUserInfo.UserID, HasAccessPermission);

                DepartmentNode = DepartmentNode.NextSibling;
            }

            lstFolders.Dashboard = this.dsbContent;
            lstFolders.Statusbar = this.stbMain;

            SetTaskTileSize(TUserDefaults.GetInt16Default(TUserDefaults.MAINMENU_VIEWOPTIONS_TILESIZE, 2));

            SetTasksSingleClickExecution(TUserDefaults.GetBooleanDefault(TUserDefaults.MAINMENU_VIEWOPTIONS_SINGLECLICKEXECUTION, false));

            if (TUserDefaults.GetStringDefault(TUserDefaults.MAINMENU_VIEWOPTIONS_VIEWTASKS, VIEWTASKS_TILES) == VIEWTASKS_TILES)
            {
                ViewTasksAsTiles(this, null);
            }
            else
            {
                ViewTasksAsList(this, null);
            }

            lstFolders.SelectFirstAvailableFolder();
        }
示例#4
0
        private void InitializeManualCode()
        {
            FInitiallySelectedLedger = TLstTasks.InitiallySelectedLedger;

            cmbDefaultLedger.SetSelectedInt32(FInitiallySelectedLedger);

            FShowMoneyAsCurrency   = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_CURRENCY_FORMAT_AS_CURRENCY, true);
            chkMoneyFormat.Checked = FShowMoneyAsCurrency;

            FShowDecimalsAsCurrency  = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_DECIMAL_FORMAT_AS_CURRENCY, true);
            chkDecimalFormat.Checked = FShowDecimalsAsCurrency;

            FShowThousands           = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_CURRENCY_SHOW_THOUSANDS, true);
            chkShowThousands.Checked = FShowThousands;

            // Examples
            txtMoneyExample.Context            = ".MFinance";
            txtMoneyExample.ControlMode        = TTxtNumericTextBox.TNumericTextBoxMode.Currency;
            txtMoneyExample.CurrencyCode       = "USD";
            txtMoneyExample.NumberValueDecimal = 12345.67m;

            txtExchangeRateExample.Context            = ".MFinance";
            txtExchangeRateExample.ControlMode        = TTxtNumericTextBox.TNumericTextBoxMode.Decimal;
            txtExchangeRateExample.NumberValueDecimal = 6.789m;
        }
        private void InitializeManualCode()
        {
            tabGiftBatch.Selecting += new TabControlCancelEventHandler(TabSelectionChanging);
            this.tpgRecurringTransactions.Enabled = false;

            // read system and user defaults
            bool DonorZeroIsValid     = TSystemDefaults.GetBooleanDefault(SharedConstants.SYSDEFAULT_DONORZEROISVALID, false);
            bool RecipientZeroIsValid = TSystemDefaults.GetBooleanDefault(SharedConstants.SYSDEFAULT_RECIPIENTZEROISVALID, false);

            //If user is FINANCE-3 level then their user settings can override system level setting
            FDonorZeroIsValid     = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_DONOR_ZERO_IS_VALID, DonorZeroIsValid);
            FRecipientZeroIsValid = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_RECIPIENT_ZERO_IS_VALID, RecipientZeroIsValid);
            //Use the same setting as for posting
            FWarnOfInactiveValuesOnSubmitting = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_WARN_OF_INACTIVE_VALUES_ON_POSTING, true);
            FNewDonorWarning           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_NEW_DONOR_ALERT, true);
            mniNewDonorWarning.Checked = FNewDonorWarning;

            // only add this event if the user want a new donor warning (this will still work without the condition)
            if (FNewDonorWarning)
            {
                FPetraUtilsObject.DataSaved += new TDataSavedHandler(FPetraUtilsObject_DataSaved);
            }

            mniFilePrint.Enabled = true;

            // change the event that gets called when 'Save' is clicked (i.e. changed from generated code)
            tbbSave.Click     -= FileSave;
            mniFileSave.Click -= FileSave;
            tbbSave.Click     += FileSaveManual;
            mniFileSave.Click += FileSaveManual;

            tabGiftBatch.GotFocus += new EventHandler(tabGiftBatch_GotFocus);
        }
        private void InitializeManualCode()
        {
            // load the data
            Ict.Common.Data.TTypedDataTable TypedTable;
            TRemote.MCommon.DataReader.WebConnectors.GetData(ACorporateExchangeRateTable.GetTableDBName(), null, out TypedTable);
            FMainDS.ACorporateExchangeRate.Merge(TypedTable);

            FUseCurrencyFormatForDecimal = TUserDefaults.GetBooleanDefault(Ict.Common.StringHelper.FINANCE_DECIMAL_FORMAT_AS_CURRENCY, true);
        }
 private void RunOnceOnActivationManual()
 {
     chkDonationData.Checked = TUserDefaults.GetBooleanDefault("IntranetExportDonations", false);
     chkFieldData.Checked    = TUserDefaults.GetBooleanDefault("IntranetExportField", false);
     chkPersonData.Checked   = TUserDefaults.GetBooleanDefault("IntranetExportPerson", false);
     lblGiftsSince.Width     = 200;
     lblGiftsSince.Left      = 40;
     UpdateDonationsLabel();
 }
示例#8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="AExchangeRateDT">The corporate or daily exchange rate table</param>
        /// <param name="AImportMode">Determines whether corporate or daily exchange rates specified - either 'Daily' or 'Corporate'</param>
        /// <param name="AResultCollection">A validation collection to which errors will be added</param>
        /// <returns>The number of rows that were actually imported.  Rows that duplicate existing rows do not count.
        /// This is usually because this is an attempt to import again after a failed previous attempt.</returns>
        public static int ImportCurrencyExRates(TTypedDataTable AExchangeRateDT, string AImportMode, TVerificationResultCollection AResultCollection)
        {
            OpenFileDialog DialogBox = new OpenFileDialog();

            DialogBox.Title = Catalog.GetString("Import exchange rates from spreadsheet file");
            DialogBox.Filter = Catalog.GetString("Spreadsheet files (*.csv)|*.csv");

            if (DialogBox.ShowDialog() == DialogResult.OK)
            {
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");
                String impOptions = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);

                bool dateMayBeAnInteger = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);
                TDlgSelectCSVSeparator DlgSeparator = new TDlgSelectCSVSeparator(false);
                DlgSeparator.DateMayBeInteger = dateMayBeAnInteger;
                Boolean fileCanOpen = DlgSeparator.OpenCsvFile(DialogBox.FileName);

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

                DlgSeparator.DateFormat = dateFormatString;
                DlgSeparator.NumberFormat = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
                DlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(DlgSeparator.FileContent) ??
                                                 ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

                if (DlgSeparator.ShowDialog() == DialogResult.OK)
                {
                    // Save the settings that we specified
                    SaveOptions(DlgSeparator);

                    // Do the import and return the number of rows imported and any messages
                    return ImportCurrencyExRatesFromCSV(AExchangeRateDT,
                        DlgSeparator.FileContent,
                        DlgSeparator.SelectedSeparator,
                        DlgSeparator.NumberFormat,
                        DlgSeparator.DateFormat,
                        dateMayBeAnInteger,
                        AImportMode,
                        AResultCollection,
                        Path.GetFileNameWithoutExtension(DialogBox.FileName));
                }
                else
                {
                    // Save the options anyway
                    SaveOptions(DlgSeparator);
                }
            }

            return 0;
        }
示例#9
0
        /// <summary></summary>
        public void InitializeManualCode()
        {
            txtEmailBody.AcceptsReturn = true;

            LoadEmailDefaults();
            txtSenderAddress.Text          = TUserDefaults.GetStringDefault("SmtpFromAccount");
            txtDisplayName.Text            = TUserDefaults.GetStringDefault("SmtpDisplayName");
            txtReplyTo.Text                = TUserDefaults.GetStringDefault("SmtpReplyTo");
            txtCopyMessagesTo.Text         = TUserDefaults.GetStringDefault("SmtpCcTo");
            txtEmailBody.Text              = TUserDefaults.GetStringDefault("SmtpEmailBody");
            chkReportsAsAttachment.Checked = TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment");
        }
        private void InitializeManualCode()
        {
            FDonorZeroIsValidSystemDefault     = TSystemDefaults.GetBooleanDefault(SharedConstants.SYSDEFAULT_DONORZEROISVALID, false);
            FRecipientZeroIsValidSystemDefault = TSystemDefaults.GetBooleanDefault(SharedConstants.SYSDEFAULT_RECIPIENTZEROISVALID, false);

            FInitiallySelectedLedger = TLstTasks.InitiallySelectedLedger;

            //New Donor alert
            FNewDonorAlert           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_NEW_DONOR_ALERT, true);
            chkNewDonorAlert.Checked = FNewDonorAlert;

            //Donor zero is valid
            FDonorZeroIsValid           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_DONOR_ZERO_IS_VALID, FDonorZeroIsValidSystemDefault);
            chkDonorZeroIsValid.Checked = FDonorZeroIsValid;

            //Auto-copying fields
            FAutoCopyIncludeMailingCode           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_AUTO_COPY_INCLUDE_MAILING_CODE, false);
            chkAutoCopyIncludeMailingCode.Checked = FAutoCopyIncludeMailingCode;

            FAutoCopyIncludeComments           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_AUTO_COPY_INCLUDE_COMMENTS, false);
            chkAutoCopyIncludeComments.Checked = FAutoCopyIncludeComments;

            //Recipient zero is valid
            FRecipientZeroIsValid = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_RECIPIENT_ZERO_IS_VALID,
                                                                    FRecipientZeroIsValidSystemDefault);
            chkRecipientZeroIsValid.Checked = FRecipientZeroIsValid;

            //Allow auto-saving of form
            FAutoSave           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_AUTO_SAVE, false);
            chkAutoSave.Checked = FAutoSave;

            //Warn of inactive values on posting
            FWarnOfInactiveValuesOnPosting = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_WARN_OF_INACTIVE_VALUES_ON_POSTING,
                                                                             true);
            chkWarnOfInactiveValuesOnPosting.Checked = FWarnOfInactiveValuesOnPosting;

            //Only highest level finance users can change these settings
            if (!UserInfo.GUserInfo.IsInModule("FINANCE-3"))
            {
                chkDonorZeroIsValid.Enabled     = false;
                chkRecipientZeroIsValid.Enabled = false;
            }
            else
            {
                chkDonorZeroIsValid.CheckStateChanged     += new System.EventHandler(ConfirmDonorZeroChange);
                chkRecipientZeroIsValid.CheckStateChanged += new System.EventHandler(ConfirmRecipientZeroChange);
            }
        }
示例#11
0
        private void TFindOptionsForm_Load(System.Object sender, System.EventArgs e)
        {
            // Form initially shows itself collapsed
            this.Height = grpDisplayedSearchCriteria.Height +
                          pnlBtnOKCancelHelpLayout.Height + stbMain.Height + 22;

            FSaveChangedOptions = false;

            // The following Buttons are only for debugging...
            btnShowRightListItems.Visible = false;
            btnShowLeftListItems.Visible  = false;

            // The rearranging of Find Criteria isn't quite stable yet, so we don't show the Button that enables the rearranging...
            btnMore.Visible = false;

            // Define default order in which the items in the left and right columns should appear
            // This is used to determine the place where added fields should appear in the columns
            FCriteriaFieldsLeftDefaultOrder = new ArrayList(new String[]
                                                            { "PartnerName", "PersonalName",
                                                              "PreviousName", "Email",
                                                              "Address1", "Address2", "Address3", "City",
                                                              "PostCode", "County",
                                                              "Country", "MailingAddressOnly", "PhoneNumber" });

            FCriteriaFieldsRightDefaultOrder = new ArrayList(new String[]
                                                             { "PartnerClass", "PartnerKey",
                                                               "OMSSKey", "LocationKey", "PartnerStatus",
                                                               "PersonnelCriteria" });

            // Load items that should go into the left and right columns from User Defaults
            FCriteriaFieldsLeft =
                new ArrayList(TUserDefaults.GetStringDefault(TUserDefaults.PARTNER_FINDOPTIONS_CRITERIAFIELDSLEFT,
                                                             PARTNER_FINDOPTIONS_CRITERIAFIELDSLEFT_DEFAULT).Split(new Char[] { (';') }));
            FCriteriaFieldsRight =
                new ArrayList(TUserDefaults.GetStringDefault(TUserDefaults.PARTNER_FINDOPTIONS_CRITERIAFIELDSRIGHT,
                                                             PARTNER_FINDOPTIONS_CRITERIAFIELDSRIGHT_DEFAULT).Split(new Char[] { (';') }));
            RemoveInvalidCriteria();

            // Populate the three CheckedListBoxes and check the correct items
            SetupFindCriteriaLists();
            chkShowMatchButtons.Checked           = TUserDefaults.GetBooleanDefault(TUserDefaults.PARTNER_FINDOPTIONS_SHOWMATCHBUTTONS, true);
            chkExactPartnerKeyMatchSearch.Checked = TUserDefaults.GetBooleanDefault(TUserDefaults.PARTNER_FINDOPTIONS_EXACTPARTNERKEYMATCHSEARCH,
                                                                                    true);

            // Hook up FindCriteriaSelectionChanged that is fired by ucoPartnerFindCriteriaSetup
            ucoPartnerFindCriteriaSetup.FindCriteriaSelectionChanged += new FindCriteriaSelectionChangedHandler(
                this.UcoPartnerFindCriteriaSetup_FindCriteriaSelectionChanged);
        }
示例#12
0
        private void InitializeManualCode()
        {
            // load the data
            Ict.Common.Data.TTypedDataTable TypedTable;
            TRemote.MCommon.DataReader.WebConnectors.GetData(ACorporateExchangeRateTable.GetTableDBName(), null, out TypedTable);
            FMainDS.ACorporateExchangeRate.Merge(TypedTable);

            FUseCurrencyFormatForDecimal = TUserDefaults.GetBooleanDefault(Ict.Common.StringHelper.FINANCE_DECIMAL_FORMAT_AS_CURRENCY, true);

            FPetraUtilsObject.ApplySecurity(TSecurityChecks.SecurityPermissionsSetupScreensEditingAndSaving);

            if (FPetraUtilsObject.SecurityReadOnly)
            {
                mniImport.Enabled = false;
                tbbImport.Enabled = false;
            }
        }
示例#13
0
        /// <summary></summary>
        public void InitializeManualCode()
        {
            txtEmailBody.AcceptsReturn           = true;
            txtAccountPswd.UseSystemPasswordChar = true;

            LoadEmailDefaults();
            txtServerName.Text             = TUserDefaults.GetStringDefault("SmtpHost");
            txtPort.Text                   = TUserDefaults.GetInt16Default("SmtpPort").ToString();
            chkUseSsl.Checked              = TUserDefaults.GetBooleanDefault("SmtpUseSsl");
            txtAccountName.Text            = TUserDefaults.GetStringDefault("SmtpUser");
            txtAccountPswd.Text            = TUserDefaults.GetStringDefault("SmtpPassword");
            txtSenderAddress.Text          = TUserDefaults.GetStringDefault("SmtpFromAccount");
            txtDisplayName.Text            = TUserDefaults.GetStringDefault("SmtpDisplayName");
            txtReplyTo.Text                = TUserDefaults.GetStringDefault("SmtpReplyTo");
            txtCopyMessagesTo.Text         = TUserDefaults.GetStringDefault("SmtpCcTo");
            txtEmailBody.Text              = TUserDefaults.GetStringDefault("SmtpEmailBody");
            chkReportsAsAttachment.Checked = TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment");
        }
示例#14
0
        private void InitializeManualCode()
        {
            int DefaultLedger = TUserDefaults.GetInt32Default(TUserDefaults.FINANCE_DEFAULT_LEDGERNUMBER);

            FCurrentLedger = TLstTasks.CurrentLedger;

            if (DefaultLedger > 0)
            {
                cmbDefaultLedger.SetSelectedInt32(DefaultLedger);
            }
            else
            {
                cmbDefaultLedger.SetSelectedInt32(FCurrentLedger);
            }

            FNewDonorWarning           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_NEW_DONOR_WARNING, true);
            chkNewDonorWarning.Checked = FNewDonorWarning;
        }
示例#15
0
        /// <summary>
        /// Called by TFrmPetraUtils during the TFrmPetra_Load event
        /// </summary>
        public void TForm_Load()
        {
            // Are we saving/restoring the window position?  This option is stored in User Defaults.
            if (TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, true))
            {
                // Restore the window positions if we know them
                // (Note: Nant tests do not have a caller so we need to allow for this possibility)
                if ((FWinForm.Name == "TFrmMainWindowNew") || (FWinForm.Name == "TFrmPartnerEdit") ||
                    ((FCallerForm != null) && (FCallerForm.Name == "TFrmMainWindowNew")))
                {
                    // Either we are loading the main window or we have been opened by the main window
                    if (!FWindowPositionsLoaded)
                    {
                        LoadWindowPositionsFromFile();
                    }

                    RestoreBasicWindowPositionProperties();     // We restore additional properties 'on activation' above
                }
            }
        }
示例#16
0
        private void InitializeManualCode()
        {
            int DefaultLedger = TUserDefaults.GetInt32Default(TUserDefaults.FINANCE_DEFAULT_LEDGERNUMBER);

            FCurrentLedger = TLstTasks.CurrentLedger;

            if (DefaultLedger > 0)
            {
                cmbDefaultLedger.SetSelectedInt32(DefaultLedger);
            }
            else
            {
                cmbDefaultLedger.SetSelectedInt32(FCurrentLedger);
            }

            FNewDonorWarning           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_NEW_DONOR_WARNING, true);
            chkNewDonorWarning.Checked = FNewDonorWarning;

            FAutoSave           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_AUTO_SAVE_GIFT_SCREEN, false);
            chkAutoSave.Checked = FAutoSave;

            FShowMoneyAsCurrency   = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_CURRENCY_FORMAT_AS_CURRENCY, true);
            chkMoneyFormat.Checked = FShowMoneyAsCurrency;

            FShowDecimalsAsCurrency  = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_DECIMAL_FORMAT_AS_CURRENCY, true);
            chkDecimalFormat.Checked = FShowDecimalsAsCurrency;

            FShowThousands           = TUserDefaults.GetBooleanDefault(StringHelper.FINANCE_CURRENCY_SHOW_THOUSANDS, true);
            chkShowThousands.Checked = FShowThousands;

            // Examples
            txtMoneyExample.Context            = ".MFinance";
            txtMoneyExample.ControlMode        = TTxtNumericTextBox.TNumericTextBoxMode.Currency;
            txtMoneyExample.CurrencyCode       = "USD";
            txtMoneyExample.NumberValueDecimal = 12345.67m;

            txtExchangeRateExample.Context            = ".MFinance";
            txtExchangeRateExample.ControlMode        = TTxtNumericTextBox.TNumericTextBoxMode.Decimal;
            txtExchangeRateExample.NumberValueDecimal = 6.789m;
        }
示例#17
0
        private void InitializeManualCode()
        {
            tabGiftBatch.Selecting      += new TabControlCancelEventHandler(TabSelectionChanging);
            this.tpgTransactions.Enabled = false;

            // get user default
            FNewDonorWarning           = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_NEW_DONOR_WARNING, true);
            mniNewDonorWarning.Checked = FNewDonorWarning;

            // only add this event if the user want a new donor warning (this will still work without the condition)
            if (FNewDonorWarning)
            {
                FPetraUtilsObject.DataSaved += new TDataSavedHandler(FPetraUtilsObject_DataSaved);
            }

            mniPrintGiftBatchDetail.Enabled = true;

            // change the event that gets called when 'Save' is clicked (i.e. changed from generated code)
            tbbSave.Click     -= FileSave;
            mniFileSave.Click -= FileSave;
            tbbSave.Click     += FileSaveManual;
            mniFileSave.Click += FileSaveManual;
        }
示例#18
0
        /** used to allow subforms to initialise
         * Also, now that the form is shown we can set the splitter bar distances
         */
        public void LocalRunOnceOnActivation()
        {
            if (!FNoAutoHookupOfAllControls)
            {
                HookupAllControls();
            }

            // Are we saving/restoring the window position?  This option is stored in User Defaults.
            if (TUserDefaults.IsInitialised)
            {
                if (TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, true))
                {
                    // (Note: Nant tests do not have a caller so we need to allow for this possibility)
                    if ((FWinForm.Name == "TFrmMainWindowNew") || (FWinForm.Name == "TFrmPartnerEdit") ||
                        ((FCallerForm != null) && (FCallerForm.Name == "TFrmMainWindowNew")))
                    {
                        // Either we are loading the main window or we have been opened by the main window
                        // Now that the window has been activated we are ok to restore things like splitter distances
                        RestoreAdditionalWindowPositionProperties();
                    }
                }
            }
        }
        /// <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;
            bool           RefreshGUIAfterImport = false;
            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;
                }
            }

            bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);

            FdlgSeparator = new TDlgSelectCSVSeparator(false);
            FdlgSeparator.DateMayBeInteger = datesMayBeIntegers;

            if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
            {
                string 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;
                }

                FdlgSeparator.CSVData = importString;
            }
            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|Text Files (*.txt)|*.txt");

                // 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;
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                // unknown source!!
                return;
            }

            String impOptions       = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);
            String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");

            FdlgSeparator.DateFormat        = dateFormatString;
            FdlgSeparator.NumberFormat      = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
            FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ??
                                              ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

            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("DatesMayBeIntegers", datesMayBeIntegers);
                requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                requestParams.Add("NewLine", Environment.NewLine);
                requestParams.Add("LastTransactionNumber", ACurrentJournalRow.LastTransactionNumber);

                TVerificationResultCollection AMessages = new TVerificationResultCollection();

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

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

                ShowMessages(AMessages);
            }

            // 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);

            if (ok || RefreshGUIAfterImport)
            {
                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.LoadATransactionAndRelatedTablesForJournal(FLedgerNumber,
                                                                                                           ACurrentBatchRow.BatchNumber, ACurrentJournalRow.JournalNumber));
                FMainDS.AcceptChanges();
                FMyForm.Cursor = Cursors.Default;

                FMyForm.GetTransactionsControl().SelectRow(1);
            }
        }
示例#20
0
 /// <summary>
 /// Get the user default if the Menu Item "Wrap Column" is checked
 /// </summary>
 /// <returns></returns>
 public bool GetWrapOption()
 {
     return(TUserDefaults.GetBooleanDefault("RptSettingWrapColumn", true));
 }
示例#21
0
        /// <summary>
        /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter.
        /// </summary>
        /// <returns>Status string that should be shown to the user</returns>
        public static String AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine,
                                              TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter)
        {
            Int32  SuccessfulCount = 0;
            String NoEmailAddr     = "";
            String FailedAddresses = "";
            String SendReport      = "";

            //
            // I need to find the email addresses for the linked partners I'm sending to.
            DataTable LinkedPartners = null;

            LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter);
            LinkedPartners.DefaultView.Sort = "CostCentreCode";

            foreach (DataRowView rv in LinkedPartners.DefaultView)
            {
                DataRow LinkedPartner = rv.Row;

                if (LinkedPartner["EmailAddress"].ToString() != "")
                {
                    ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString());
                    FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]);
                    MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html);

                    if (ReportStream.Position < 1000)
                    {
                        continue; // Don't send an empty report
                    }

                    ReportStream.Position = 0;

                    TUC_EmailPreferences.LoadEmailDefaults();
                    TSmtpSender EmailSender = new TSmtpSender(
                        TUserDefaults.GetStringDefault("SmtpHost"),
                        TUserDefaults.GetInt16Default("SmtpPort"),
                        TUserDefaults.GetBooleanDefault("SmtpUseSsl"),
                        TUserDefaults.GetStringDefault("SmtpUser"),
                        TUserDefaults.GetStringDefault("SmtpPassword"),
                        "");
                    EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                    EmailSender.ReplyTo        = TUserDefaults.GetStringDefault("SmtpReplyTo");

                    if (!EmailSender.FInitOk)
                    {
                        return(String.Format(
                                   Catalog.GetString(
                                       "Failed to set up the email server.\n    Please check the settings in Preferences / Email.\n    Message returned : \"{0}\""),
                                   EmailSender.FErrorStatus));
                    }

                    String EmailBody = "";

                    if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment"))
                    {
                        EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                        EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".html");
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(ReportStream);
                        EmailBody = sr.ReadToEnd();
                    }

                    Boolean SentOk = EmailSender.SendEmail(
                        TUserDefaults.GetStringDefault("SmtpFromAccount"),
                        TUserDefaults.GetStringDefault("SmtpDisplayName"),
                        "*****@*****.**", //LinkedPartner["EmailAddress"]
                        ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"],
                        EmailBody);

                    if (SentOk)
                    {
                        SuccessfulCount++;
                    }
                    else // Email didn't send for some reason
                    {
                        SendReport += String.Format(
                            Catalog.GetString("\r\nFailed to send to {0}. Message returned: \"{1}\"."),
                            LinkedPartner["EmailAddress"],
                            EmailSender.FErrorStatus
                            );

                        FailedAddresses += ("\r\n    " + LinkedPartner["EmailAddress"]);
                    }
                }
                else // No Email Address for this Partner
                {
                    NoEmailAddr += ("\r\n    " + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]);
                }
            }

            if (SuccessfulCount > 0)
            {
                SendReport +=
                    String.Format(Catalog.GetString("\r\n{0} emailed to {1} addresses."), ReportEngine.FReportName, SuccessfulCount) + "\r\n\r\n";
            }

            if (NoEmailAddr != "")
            {
                SendReport += (Catalog.GetString("\r\nThese Partners have no email addresses:") + NoEmailAddr + "\r\n");
            }

            if (FailedAddresses != "")
            {
                SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n");
            }

            FormUtils.WriteToStatusBar("");
            return(SendReport);
        } // AutoEmailReports
示例#22
0
        /// <summary>
        /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter.
        /// </summary>
        /// <returns>Status string that should be shown to the user</returns>
        public static String AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine,
                                              TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter)
        {
            Int32  SuccessfulCount = 0;
            String NoEmailAddr     = "";
            String FailedAddresses = "";
            String SendReport      = "Auto Email\r\n";

            //
            // FastReport will use a temporary folder to store HTML files.
            // I need to ensure that the CurrectDirectory is somewhere writable:
            String prevCurrentDir = Directory.GetCurrentDirectory();


            //Get a path in the Public Documents folder
            String newDir = Path.Combine(Environment.GetFolderPath(
                                             Environment.SpecialFolder.CommonDocuments), "OpenPetraOrg");

            //Check it exists, and if not create it
            if (!Directory.Exists(newDir))
            {
                try
                {
                    Directory.CreateDirectory(newDir);
                }
                catch (Exception ex)
                {
                    //could not create the path so return useful debugging information:
                    SendReport += Catalog.GetString("\r\nError - could not create directory: " + newDir);
                    SendReport += Catalog.GetString("\r\n" + newDir);
                    SendReport += ex.Message;

                    return(SendReport);
                }
            }

            Directory.SetCurrentDirectory(newDir);

            //
            // I need to find the email addresses for the linked partners I'm sending to.
            DataTable LinkedPartners = null;

            LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter);
            LinkedPartners.DefaultView.Sort = "CostCentreCode";

            foreach (DataRowView rv in LinkedPartners.DefaultView)
            {
                DataRow LinkedPartner = rv.Row;

                if (LinkedPartner["EmailAddress"].ToString() != "")
                {
                    ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString());
                    FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]);
                    MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html);

                    // in OpenSource OpenPetra, we do not have and use the FastReport dlls
                    // if (ReportEngine.FfastReportInstance.ReportInfo.Description == "Empty")
                    // {
                    //    continue; // Don't send an empty report
                    // }

                    ReportStream.Position = 0;

                    // This gets email defaults from the user settings table
                    TUC_EmailPreferences.LoadEmailDefaults();

                    // This gets some of the settings from the server configuration.  We no longer get these items from local PC.
                    // SmtpUsername and SmtpPassword will usually be null
                    string smtpHost, smtpUsername, smtpPassword;
                    int    smtpPort;
                    bool   smtpUseSSL;
                    TRemote.MSysMan.Application.WebConnectors.GetServerSmtpSettings(out smtpHost,
                                                                                    out smtpPort,
                                                                                    out smtpUseSSL,
                                                                                    out smtpUsername,
                                                                                    out smtpPassword);

                    if ((smtpHost == string.Empty) || (smtpPort < 0))
                    {
                        return(Catalog.GetString(
                                   "Cannot send email because 'smtpHost' and/or 'smtpPort' are not configured in the OP server configuration file."));
                    }

                    TSmtpSender EmailSender = new TSmtpSender(smtpHost, smtpPort, smtpUseSSL, smtpUsername, smtpPassword, "");

                    EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                    EmailSender.ReplyTo        = TUserDefaults.GetStringDefault("SmtpReplyTo");

                    if (!EmailSender.FInitOk)
                    {
                        return(String.Format(
                                   Catalog.GetString(
                                       "Failed to set up the email server.\n    Please check the settings in Preferences / Email.\n    Message returned : \"{0}\""),
                                   EmailSender.FErrorStatus));
                    }

                    String EmailBody = "";

                    if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment"))
                    {
                        EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                        EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".html");
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(ReportStream);
                        EmailBody = sr.ReadToEnd();
                    }

                    Boolean SentOk = EmailSender.SendEmail(
                        TUserDefaults.GetStringDefault("SmtpFromAccount"),
                        TUserDefaults.GetStringDefault("SmtpDisplayName"),
                        LinkedPartner["EmailAddress"].ToString(),
                        ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"],
                        EmailBody);

                    if (SentOk)
                    {
                        SuccessfulCount++;
                    }
                    else // Email didn't send for some reason
                    {
                        SendReport += String.Format(
                            Catalog.GetString("\r\nFailed to send to {0}. Message returned: \"{1}\"."),
                            LinkedPartner["EmailAddress"],
                            EmailSender.FErrorStatus
                            );

                        FailedAddresses += ("\r\n    " + LinkedPartner["EmailAddress"]);
                    }
                }
                else // No Email Address for this Partner
                {
                    NoEmailAddr += ("\r\n    " + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]);
                }
            }

            if (SuccessfulCount > 0)
            {
                SendReport +=
                    String.Format(Catalog.GetString("\r\n{0} emailed to {1} addresses."), ReportEngine.FReportName, SuccessfulCount) + "\r\n\r\n";
            }
            else
            {
                SendReport += Catalog.GetString("\r\nError - no page had a linked email address.");
            }

            if (NoEmailAddr != "")
            {
                SendReport += (Catalog.GetString("\r\nThese Partners have no email addresses:") + NoEmailAddr + "\r\n");
            }

            if (FailedAddresses != "")
            {
                SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n");
            }

            FormUtils.WriteToStatusBar("");
            Directory.SetCurrentDirectory(prevCurrentDir);
            return(SendReport);
        } // AutoEmailReports
        private void InitializeManualCode()
        {
            DataTable CultureTable = new DataTable();

            CultureTable.Columns.Add("Value", typeof(string));
            CultureTable.Columns.Add("Display", typeof(string));

            foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
            {
                if (!ci.IsNeutralCulture)
                {
                    DataRow row = CultureTable.NewRow();
                    row[0] = ci.Name;
                    row[1] = ci.EnglishName;
                    CultureTable.Rows.Add(row);
                }
            }

            CultureTable.DefaultView.Sort = "Display";

            cmbCulture.DisplayMember = "Display";
            cmbCulture.ValueMember   = "Value";
            cmbCulture.DataSource    = CultureTable.DefaultView;

            // load languages from names of language sub directories
            string[] LanguageDirectories = Directory.GetDirectories(TAppSettingsManager.ApplicationDirectory);

            string LanguagesAvailable = "en-EN";

            foreach (String directory in LanguageDirectories)
            {
                if (File.Exists(directory + Path.DirectorySeparatorChar + "OpenPetra.resources.dll"))
                {
                    LanguagesAvailable = StringHelper.AddCSV(
                        LanguagesAvailable,
                        directory.Substring(
                            directory.LastIndexOf(Path.DirectorySeparatorChar) + 1));
                }
            }

            cmbLanguage.SetDataSourceStringList(LanguagesAvailable);

            // for the moment default to english, because translations are not fully supported, and the layout does not adjust
            string LanguageCode = "en-EN";
            string CultureCode  = CultureInfo.CurrentCulture.Name;

            TRemote.MSysMan.Maintenance.WebConnectors.GetLanguageAndCulture(ref LanguageCode, ref CultureCode);

            cmbCulture.SetSelectedString(CultureCode);
            cmbLanguage.SetSelectedString(LanguageCode);

            llbLaunchpadLink.Click += LaunchpadLinkClicked;

            // Get the number of recent partners that the user has set, if not found take 10 as default value.
            nudNumberOfPartners.Value   = TUserDefaults.GetInt16Default(MSysManConstants.USERDEFAULT_NUMBEROFRECENTPARTNERS, 10);
            nudNumberOfPartners.Maximum = 10;

            // Other preferences
            chkEscClosesScreen.Checked      = TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_ESC_CLOSES_SCREEN, true);
            chkSaveWindowProperties.Checked = TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, true);

            WasSaveWindowPropertiesInitiallyChecked = chkSaveWindowProperties.Checked;
        }
        /// <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;
            bool           RefreshGUIAfterImport = false;
            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;
            }

            try
            {
                FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.IMPORTING;

                bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.DateMayBeInteger = datesMayBeIntegers;

                if (AImportDataSource == TImportDataSourceEnum.FromClipboard)
                {
                    string 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;
                    }

                    FdlgSeparator.CSVData = importString;
                }
                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 Batch Files (*.csv)|*.csv|Text Files (*.txt)|*.txt");

                    // 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;
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    // unknown source!!
                    return;
                }

                String impOptions       = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");

                FdlgSeparator.DateFormat        = dateFormatString;
                FdlgSeparator.NumberFormat      = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
                FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ??
                                                  ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

                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("DatesMayBeIntegers", datesMayBeIntegers);
                    requestParams.Add("NumberFormat", FdlgSeparator.NumberFormat);
                    requestParams.Add("NewLine", Environment.NewLine);

                    TVerificationResultCollection AMessages = new TVerificationResultCollection();

                    Thread ImportThread = new Thread(() => ImportGLBatches(
                                                         requestParams,
                                                         FdlgSeparator.FileContent,
                                                         out AMessages,
                                                         out ok,
                                                         out RefreshGUIAfterImport));

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

                    if (TVerificationHelper.ResultsContainErrorCode(AMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                    {
                        TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                    }
                    else
                    {
                        ShowMessages(AMessages);
                    }
                }

                // 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);

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

                if (ok)
                {
                    FMyUserControl.ReloadBatches();
                    FMyForm.GetBatchControl().SelectRowInGrid(1);
                    FPetraUtilsObject.SetChangedFlag();
                    FMyForm.SaveChangesManual(FMyForm.FCurrentGLBatchAction);
                }
                else if (RefreshGUIAfterImport)
                {
                    // The import failed and the server needs us to refresh the GUI
                    FMyUserControl.ReloadBatches(true);
                    FMyForm.GetBatchControl().SelectRowInGrid(1);
                }
            }
            finally
            {
                FMyForm.FCurrentGLBatchAction = TGLBatchEnums.GLBatchAction.NONE;
            }
        }
示例#25
0
        /// <summary>
        /// Takes a report and a list of cost centres; it runs the report for each of the cost centres and emails the results to the address(es)
        /// associated with that cost centre. Used by Account Detail, Income Expense reports and HOSAs.
        /// </summary>
        /// <remarks>If ACostCentreFilter is an SQL clause selecting cost centres, the associated email address is the Primary E-Mail Address of
        /// every Partner linked to the cost centre. If ACostCentreFilter is "Foreign", the list is every cost centre in the a_email_destination
        /// table with a File Code of "HOSA".</remarks>
        /// <param name="FormUtils">The report selection form, to write to the status bar.</param>
        /// <param name="ReportEngine">FastReport wrapper object.</param>
        /// <param name="ACalc">The report parameters.</param>
        /// <param name="ALedgerNumber">The ledger number.</param>
        /// <param name="ACostCentreFilter">SQL clause to select the list of cost centres to run the report for, or "Foreign" </param>
        /// <returns>List of status strings that should be shown to the user.</returns>
        public static List <String> AutoEmailReports(TFrmPetraReportingUtils FormUtils, FastReportsWrapper ReportEngine,
                                                     TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter)
        {
            TSmtpSender EmailSender;
            Int32       SuccessfulCount = 0;
            var         NoEmailAddr     = new List <String>();
            var         FailedAddresses = new List <String>();
            var         SendReport      = new List <String>();

            // FastReport will use a temporary folder to store HTML files.
            // I need to ensure that the CurrectDirectory is somewhere writable:
            String prevCurrentDir = Directory.GetCurrentDirectory();


            //Get a path in the Public Documents folder
            String newDir = Path.Combine(Environment.GetFolderPath(
                                             Environment.SpecialFolder.CommonDocuments), "OpenPetraOrg");

            //Check it exists, and if not create it
            if (!Directory.Exists(newDir))
            {
                try
                {
                    Directory.CreateDirectory(newDir);
                }
                catch (Exception ex)
                {
                    //Could not create the path so return useful debugging information:
                    SendReport.Add(Catalog.GetString("Error - could not create directory: "));
                    SendReport.Add(newDir);
                    SendReport.Add(ex.Message);

                    return(SendReport);
                }
            }

            Directory.SetCurrentDirectory(newDir);

            // This gets email defaults from the user settings table
            //TUC_EmailPreferences.LoadEmailDefaults();

            try
            {
                EmailSender = new TSmtpSender();

                EmailSender.SetSender(TUserDefaults.GetStringDefault("SmtpFromAccount"), TUserDefaults.GetStringDefault("SmtpDisplayName"));
                EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                EmailSender.ReplyTo        = TUserDefaults.GetStringDefault("SmtpReplyTo");
            }
            catch (ESmtpSenderInitializeException e)
            {
                if (e.InnerException != null)
                {
                    // I'd write the full exception to the log file, but it still gets transferred to the client window status bar and is _really_ ugly.
                    //TLogging.Log("AutoEmailReports: " + e.InnerException.ToString());
                    TLogging.Log("AutoEmailReports: " + e.InnerException.Message);
                }

                SendReport.Add(e.Message);

                if (e.ErrorClass == TSmtpErrorClassEnum.secClient)
                {
                    SendReport.Add(Catalog.GetString("Check the Email tab in User Settings >> Preferences."));
                }

                return(SendReport);
            }

            // I need to find the email addresses for the linked partners I'm sending to.
            DataTable LinkedPartners = null;

            LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter);
            LinkedPartners.DefaultView.Sort = "CostCentreCode";
            String    myLedgerName   = "";
            DataTable CostCentreList = null;

            if (ACostCentreFilter == "Foreign")
            {
                myLedgerName   = TRemote.MFinance.Reporting.WebConnectors.GetLedgerName(ALedgerNumber);
                CostCentreList = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.CostCentreList,
                                                                               ALedgerNumber);
            }

            foreach (DataRowView rv in LinkedPartners.DefaultView)
            {
                DataRow LinkedPartner      = rv.Row;
                Boolean reportAsAttachment = TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment", true);

                if (LinkedPartner["EmailAddress"].ToString() != "")
                {
                    ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString());
                    FormUtils.WriteToStatusBar("Generate " + ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"]);
                    MemoryStream ReportStream = ReportEngine.ExportToStream(ACalc,
                                                                            reportAsAttachment ? FastReportsWrapper.ReportExportType.Pdf : FastReportsWrapper.ReportExportType.Html);

                    // in OpenSource OpenPetra, we do not have and use the FastReport dlls
                    // if (ReportEngine.FfastReportInstance.ReportInfo.Description == "Empty")
                    // {
                    //    continue; // Don't send an empty report
                    // }

                    ReportStream.Position = 0;

                    String EmailBody = "";

                    if (reportAsAttachment)
                    {
                        EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                        EmailSender.AttachFromStream(ReportStream, ReportEngine.FReportName + ".pdf");
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(ReportStream);
                        EmailBody = sr.ReadToEnd();
                    }

                    String subjectLine;

                    if (ACostCentreFilter == "Foreign")
                    {
                        String recipientLedgerName = "";
                        CostCentreList.DefaultView.RowFilter = "a_cost_centre_code_c='" + LinkedPartner["CostCentreCode"].ToString() + "'";

                        if (CostCentreList.DefaultView.Count > 0)
                        {
                            recipientLedgerName = CostCentreList.DefaultView[0].Row["a_cost_centre_name_c"].ToString();
                        }

                        subjectLine = "HOSA & RGS from " + myLedgerName + " to " + recipientLedgerName;
                    }
                    else
                    {
                        subjectLine = ReportEngine.FReportName + " Report for " + LinkedPartner["PartnerShortName"];
                    }

                    Boolean SentOk = EmailSender.SendEmail(
                        LinkedPartner["EmailAddress"].ToString(),
                        subjectLine,
                        EmailBody);

                    if (SentOk)
                    {
                        SuccessfulCount++;
                    }
                    else // Email didn't send for some reason
                    {
                        SendReport.Add(String.Format(
                                           Catalog.GetString("Failed to send to {0}. Message returned: \"{1}\"."),
                                           LinkedPartner["EmailAddress"],
                                           EmailSender.ErrorStatus
                                           ));

                        FailedAddresses.Add("    " + LinkedPartner["EmailAddress"]);
                    }
                }
                else // No Email Address for this Partner
                {
                    NoEmailAddr.Add("    " + String.Format("{0:D10}", LinkedPartner["PartnerKey"]) + " " + LinkedPartner["PartnerShortName"]);
                }
            }

            if (SuccessfulCount == 1)
            {
                SendReport.Add(
                    String.Format(Catalog.GetString("{0} emailed to {1} partner."), ReportEngine.FReportName, SuccessfulCount));
            }
            else if (SuccessfulCount > 1)
            {
                SendReport.Add(
                    String.Format(Catalog.GetString("{0} emailed to {1} partners."), ReportEngine.FReportName, SuccessfulCount));
            }
            else
            {
                SendReport.Add(Catalog.GetString(
                                   "Error – no cost centre in the report was linked to a Partner with a valid Primary E-mail Address."));
            }

            if (NoEmailAddr.Count > 0)
            {
                SendReport.Add(Catalog.GetString("These Partners have no Primary E-mail Address:"));
                SendReport.AddRange(NoEmailAddr);
            }

            if (FailedAddresses.Count > 0)
            {
                SendReport.Add(Catalog.GetString("Failed to send email to these addresses:"));
                SendReport.AddRange(FailedAddresses);
            }

            FormUtils.WriteToStatusBar("");
            Directory.SetCurrentDirectory(prevCurrentDir);
            EmailSender.Dispose();
            return(SendReport);
        } // AutoEmailReports
示例#26
0
        /// <summary>
        /// Checks the entire gift batch for inactive values and informs the user
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <param name="AAction"></param>
        /// <param name="AMainDS"></param>
        /// <param name="APetraUtilsObject"></param>
        /// <param name="AIsRecurringGift"></param>
        /// <returns></returns>
        public static bool CheckForInactiveFieldValues(Int32 ALedgerNumber,
                                                       GiftBatchAction AAction,
                                                       GiftBatchTDS AMainDS,
                                                       TFrmPetraEditUtils APetraUtilsObject,
                                                       Boolean AIsRecurringGift = false)
        {
            #region Validate Arguments

            if (AMainDS == null)
            {
                throw new EFinanceSystemInvalidLedgerNumberException(String.Format(Catalog.GetString(
                                                                                       "Function:{0} - The Gift Batch dataset is empty!"),
                                                                                   Utilities.GetMethodName(true)));
            }
            else if (AMainDS.AGiftBatch.Count == 0)
            {
                throw new ArgumentException(String.Format(Catalog.GetString(
                                                              "Function:{0} - The Gift Batch table contains no batches to validate!"),
                                                          Utilities.GetMethodName(true)));
            }

            #endregion Validate Arguments

            //TODO: Need to rewrite...

            bool RetVal = false;

            bool ChangesAtGiftBatchLevel  = false;
            bool ChangesAtGiftLevel       = false;
            bool ChangesAtGiftDetailLevel = false;

            string IndentifyRecurring = (AIsRecurringGift ? "ARecurring" : "A");
            Type   GiftBatchTableType = Type.GetType(IndentifyRecurring + "GiftBatchTable");


            bool WarnOfInactiveValuesOnPosting = TUserDefaults.GetBooleanDefault(TUserDefaults.FINANCE_GIFT_WARN_OF_INACTIVE_VALUES_ON_POSTING, true);

            if ((AAction == GiftBatchAction.POSTING) && !WarnOfInactiveValuesOnPosting)
            {
                return(true);
            }

            if (APetraUtilsObject.HasChanges)
            {
                GiftBatchTDS Changes = new GiftBatchTDS();

                //Batch level
                if (!AIsRecurringGift && (AMainDS.AGiftBatch.GetChangesTyped() != null))
                {
                    Changes.Merge(AMainDS.AGiftBatch.GetChangesTyped());
                    ChangesAtGiftBatchLevel = true;
                }
                else if (AIsRecurringGift && (AMainDS.ARecurringGiftBatch.GetChangesTyped() != null))
                {
                    Changes.Merge(AMainDS.ARecurringGiftBatch.GetChangesTyped());
                    ChangesAtGiftBatchLevel = true;
                }

                //Gift level
                if (!AIsRecurringGift && (AMainDS.AGift.GetChangesTyped() != null))
                {
                    Changes.Merge(AMainDS.AGift.GetChangesTyped());
                    ChangesAtGiftLevel = true;
                }
                else if (AIsRecurringGift && (AMainDS.ARecurringGift.GetChangesTyped() != null))
                {
                    Changes.Merge(AMainDS.ARecurringGift.GetChangesTyped());
                    ChangesAtGiftLevel = true;
                }

                //Detail level
                if (!AIsRecurringGift && (AMainDS.AGiftDetail.GetChangesTyped() != null))
                {
                    Changes.Merge(AMainDS.AGiftDetail.GetChangesTyped());
                    ChangesAtGiftDetailLevel = true;
                }
                else if (AIsRecurringGift && (AMainDS.ARecurringGiftDetail.GetChangesTyped() != null))
                {
                    Changes.Merge(AMainDS.ARecurringGiftDetail.GetChangesTyped());
                    ChangesAtGiftDetailLevel = true;
                }

                //Process changes
                if (ChangesAtGiftBatchLevel)
                {
                    //***Batch level
                    //TODO: Check for inactive Bank Cost Centre
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Bank Account
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Currency Code
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Method of Payment
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }
                }

                if (ChangesAtGiftLevel)
                {
                    //**Gift-level
                    //TODO: Check for inactive Donor
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Method of Payment
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Method of Giving
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }
                }

                if (ChangesAtGiftDetailLevel)
                {
                    //*Detail-level
                    //TODO: Check for inactive Recipient
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Key Ministry
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Cost Centre
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Account
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Tax Account
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive Motivation Group or Detail
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }

                    //TODO: Check for inactive MailingCode
                    if (!AIsRecurringGift)
                    {
                    }
                    else
                    {
                        //Recurring gift batch changes
                    }
                }
            }

            return(RetVal);
        }
示例#27
0
        /// <summary>
        /// The report will be sent to a list of email addresses derived from the Cost Centres in the supplied CostCentreFilter.
        /// </summary>
        /// <param name="ACalc"></param>
        /// <param name="ALedgerNumber"></param>
        /// <param name="ACostCentreFilter"></param>
        public void AutoEmailReports(TRptCalculator ACalc, Int32 ALedgerNumber, String ACostCentreFilter)
        {
            Int32  SuccessfulCount = 0;
            String NoEmailAddr     = "";
            String FailedAddresses = "";

            //
            // I need to find the email addresses for the linked partners I'm sending to.

            DataTable LinkedPartners = TRemote.MFinance.Setup.WebConnectors.GetLinkedPartners(ALedgerNumber, ACostCentreFilter);

            LinkedPartners.DefaultView.Sort = "CostCentreCode";

            foreach (DataRowView rv in LinkedPartners.DefaultView)
            {
                DataRow LinkedPartner = rv.Row;

                if (LinkedPartner["EmailAddress"].ToString() != "")
                {
                    ACalc.AddStringParameter("param_linked_partner_cc", LinkedPartner["CostCentreCode"].ToString());
                    FPetraUtilsObject.WriteToStatusBar("Generate " + FReportName + " Report for " + LinkedPartner["PartnerShortName"]);
                    MemoryStream ReportStream = FPetraUtilsObject.FFastReportsPlugin.ExportToStream(ACalc, FastReportsWrapper.ReportExportType.Html);
                    ReportStream.Position = 0;

                    TUC_EmailPreferences.LoadEmailDefaults();
                    TSmtpSender EmailSender;
                    try
                    {
                        EmailSender = new TSmtpSender(
                            TUserDefaults.GetStringDefault("SmtpHost"),
                            TUserDefaults.GetInt16Default("SmtpPort"),
                            TUserDefaults.GetBooleanDefault("SmtpUseSsl"),
                            TUserDefaults.GetStringDefault("SmtpUser"),
                            TUserDefaults.GetStringDefault("SmtpPassword"),
                            "");
                        EmailSender.CcEverythingTo = TUserDefaults.GetStringDefault("SmtpCcTo");
                        EmailSender.ReplyTo        = TUserDefaults.GetStringDefault("SmtpReplyTo");
                    }
                    catch (Exception)
                    {
                        MessageBox.Show(Catalog.GetString(
                                            "Failed to set up the email server.\nPlease check the settings in Preferences / Email."),
                                        Catalog.GetString("Auto-email to linked partners"));
                        return;
                    }

                    String EmailBody = "";

                    if (TUserDefaults.GetBooleanDefault("SmtpSendAsAttachment"))
                    {
                        EmailBody = TUserDefaults.GetStringDefault("SmtpEmailBody");
                        EmailSender.AttachFromStream(ReportStream, FReportName + ".html");
                    }
                    else
                    {
                        StreamReader sr = new StreamReader(ReportStream);
                        EmailBody = sr.ReadToEnd();
                    }

                    Boolean SentOk = EmailSender.SendEmail(
                        TUserDefaults.GetStringDefault("SmtpFromAccount"),
                        TUserDefaults.GetStringDefault("SmtpDisplayName"),
                        "*****@*****.**", //LinkedPartner["EmailAddress"]
                        FReportName + " Report for " + LinkedPartner["PartnerShortName"] + ", Address=" + LinkedPartner["EmailAddress"],
                        EmailBody);

                    if (SentOk)
                    {
                        SuccessfulCount++;
                    }
                    else // Email didn't send for some reason
                    {
                        FailedAddresses += ("\r\n" + LinkedPartner["EmailAddress"]);
                    }
                }
                else // No Email Address for this Partner
                {
                    NoEmailAddr += ("\r\n" + LinkedPartner["PartnerKey"] + " " + LinkedPartner["PartnerShortName"]);
                }
            }

            String SendReport = "";

            if (SuccessfulCount > 0)
            {
                SendReport += String.Format(Catalog.GetString("Reports emailed to {0} addresses."), SuccessfulCount) + "\r\n\r\n";
            }

            if (NoEmailAddr != "")
            {
                SendReport += (Catalog.GetString("These Partners have no email addresses:") + NoEmailAddr + "\r\n\r\n");
            }

            if (FailedAddresses != "")
            {
                SendReport += (Catalog.GetString("Failed to send email to these addresses:") + FailedAddresses + "\r\n\r\n");
            }

            MessageBox.Show(SendReport, Catalog.GetString("Auto-email to linked partners"));
            FPetraUtilsObject.WriteToStatusBar("");
        } // AutoEmailReports
示例#28
0
        /// <summary>
        /// Called by TFrmPetraUtils during the TFrmPetra_Closing event
        /// </summary>
        public void TForm_Closing()
        {
            // Deal with the window positions which are stored on the local file system
            string localAppDataPath = Path.Combine(
                TAppSettingsManager.GetLocalAppDataPath(),
                CommonFormsResourcestrings.StrFolderOrganisationName,
                System.Diagnostics.FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductName);
            string settingsFileName = String.Format(CommonFormsResourcestrings.StrScreenPositionsFileName, UserInfo.GUserInfo.UserID);
            string settingsPath     = Path.Combine(localAppDataPath, settingsFileName);

            if (TUserDefaults.GetBooleanDefault(TUserDefaults.NamedDefaults.USERDEFAULT_SAVE_WINDOW_POS_AND_SIZE, true))
            {
                // This is where we 'remember' the window position information
                if (FWinForm.Name == "TFrmMainWindowNew")
                {
                    // we are closing the main window
                    // Get our own window position properties
                    GetWindowPositionProperties();

                    // Now save all the properties for all windows we know about
                    try
                    {
                        if (!Directory.Exists(localAppDataPath))
                        {
                            Directory.CreateDirectory(localAppDataPath);
                        }

                        using (StreamWriter sw = new StreamWriter(settingsPath))
                        {
                            foreach (string key in FWindowPositions.Keys)
                            {
                                sw.WriteLine("{0}={1}", key, FWindowPositions[key]);
                            }

                            sw.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        TLogging.Log(String.Format("Exception occurred while saving the window position file '{0}': {1}", settingsPath,
                                                   ex.Message), TLoggingType.ToLogfile);
                    }
                }
                else if ((FWinForm.Name == "TFrmPartnerEdit") || (FWinForm.Name == "TFrmGiftBatch") || (FWinForm.Name == "TFrmGLBatch") ||
                         (FWinForm.Name == "TPartnerFindScreen"))
                {
                    // We always save the settings for these forms - they can be launched from the main window or from Partner/Find or several other ways
                    GetWindowPositionProperties();
                }
                else if ((FCallerForm != null) && (FCallerForm.Name == "TFrmMainWindowNew") && !FWinForm.Modal)
                {
                    // we were opened by the main window
                    GetWindowPositionProperties();
                }
            }
            else
            {
                // We are closing a screen and not saving window positions (or no longer saving them)
                FWindowPositions.Clear();
                FWindowPositionsLoaded = false;
            }
        }
示例#29
0
 /// <summary>
 /// Retrieves a boolean user default value from the TUserDefaults.
 /// </summary>
 /// <returns></returns>
 public static Boolean RetrieveUserDefaultBoolean(String AKey, Boolean ADefault)
 {
     return(TUserDefaults.GetBooleanDefault(AKey, ADefault));
 }
示例#30
0
        /// <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, GiftBatchTDS AMainDS)
        {
            bool           ImportOK = false;
            bool           RefreshGUIAfterImport = false;
            OpenFileDialog OFileDialog           = 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;
            }

            ALedgerRow LedgerRow             = (ALedgerRow)AMainDS.ALedger.Rows[0];
            int        CurrentTopBatchNumber = LedgerRow.LastGiftBatchNumber;

            try
            {
                FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.IMPORTING;

                bool datesMayBeIntegers = TUserDefaults.GetBooleanDefault(MCommonConstants.USERDEFAULT_IMPORTEDDATESMAYBEINTEGERS, false);
                FdlgSeparator = new TDlgSelectCSVSeparator(false);
                FdlgSeparator.DateMayBeInteger = datesMayBeIntegers;

                if (AImportSource == TGiftImportDataSourceEnum.FromClipboard)
                {
                    string 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;
                    }

                    FdlgSeparator.CSVData = ImportString;
                }
                else if (AImportSource == TGiftImportDataSourceEnum.FromFile)
                {
                    OFileDialog = new OpenFileDialog();

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

                    OFileDialog.Title  = Catalog.GetString("Import Batches from CSV File");
                    OFileDialog.Filter = Catalog.GetString("Gift Batch Files(*.csv)|*.csv|Text Files(*.txt)|*.txt");

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

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

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

                String impOptions       = TUserDefaults.GetStringDefault("Imp Options", ";" + TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN);
                String dateFormatString = TUserDefaults.GetStringDefault("Imp Date", "MDY");

                FdlgSeparator.DateFormat        = dateFormatString;
                FdlgSeparator.NumberFormat      = (impOptions.Length > 1) ? impOptions.Substring(1) : TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN;
                FdlgSeparator.SelectedSeparator = StringHelper.GetCSVSeparator(FdlgSeparator.FileContent) ??
                                                  ((impOptions.Length > 0) ? impOptions.Substring(0, 1) : ";");

                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("DatesMayBeIntegers", datesMayBeIntegers);
                    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,
                                                             FdlgSeparator.FileContent,
                                                             out AMessages,
                                                             out ImportOK,
                                                             out RefreshGUIAfterImport,
                                                             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)
                        {
                            if (TVerificationHelper.ResultsContainErrorCode(AMessages, PetraErrorCodes.ERR_DB_SERIALIZATION_EXCEPTION))
                            {
                                TConcurrentServerTransactions.ShowTransactionSerializationExceptionDialog();
                            }
                            else
                            {
                                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 occurrence of this error
                                    if (NeedRecipientLedgerNumber.Rows.Count - count > 0)
                                    {
                                        CheckboxText = string.Format(
                                            Catalog.GetString(
                                                "Do this for all further occurrences ({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;
                            }
                        }
                    }
                }

                // 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(OFileDialog);

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

                if (ImportOK)
                {
                    FMyUserControl.LoadBatchesForCurrentYear();
                    FMyForm.GetBatchControl().SelectRowInBatchGrid(1);

                    DataView allNewBatches = new DataView(AMainDS.AGiftBatch);

                    allNewBatches.RowFilter = String.Format("{0} > {1}",
                                                            AGiftBatchTable.GetBatchNumberDBName(),
                                                            CurrentTopBatchNumber);

                    foreach (DataRowView drv in allNewBatches)
                    {
                        drv.Row.SetModified();
                    }

                    FPetraUtilsObject.SetChangedFlag();
                    //Force initial inactive values check
                    FMyForm.SaveChangesManual(FMyForm.FCurrentGiftBatchAction);
                }
                else if (RefreshGUIAfterImport)
                {
                    FMyUserControl.LoadBatchesForCurrentYear();
                    FMyForm.GetBatchControl().SelectRowInBatchGrid(1);
                }
            }
            finally
            {
                FMyForm.FCurrentGiftBatchAction = Logic.TExtraGiftBatchChecks.GiftBatchAction.NONE;
            }
        }