예제 #1
0
        /// <summary>
        /// Checks whether the date is today or in the future. Null values are accepted.
        /// </summary>
        /// <param name="ADate">Date to check.</param>
        /// <param name="ADescription">Name of the date value.</param>
        /// <param name="AResultContext">Context of verification (can be null).</param>
        /// <param name="AResultColumn">Which <see cref="System.Data.DataColumn" /> failed (can be null).</param>
        /// <param name="AResultControl">Which <see cref="System.Windows.Forms.Control" /> is involved (can be null).</param>
        /// <returns>Null if the date <paramref name="ADate" /> is today or in the future,
        /// otherwise a verification result with a message that uses <paramref name="ADescription" />.
        /// </returns>
        public static TVerificationResult IsCurrentOrFutureDate(DateTime?ADate, String ADescription,
                                                                object AResultContext = null, System.Data.DataColumn AResultColumn = null, System.Windows.Forms.Control AResultControl = null)
        {
            TVerificationResult ReturnValue;
            DateTime            TheDate = TSaveConvert.ObjectToDate(ADate);
            String Description          = THelper.NiceValueDescription(ADescription);

            if (!ADate.HasValue)
            {
                return(null);
            }

            // Check
            if (TheDate >= DateTime.Today)
            {
                //MessageBox.Show('Date >= Today');
                ReturnValue = null;
            }
            else
            {
                if (TheDate != DateTime.MinValue)
                {
                    ReturnValue = new TVerificationResult(AResultContext,
                                                          ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_NOPASTDATE, CommonResourcestrings.StrInvalidDateEntered + Environment.NewLine +
                                                                                  StrDateMustNotBePastDate, new string[] { Description }));

                    if (AResultColumn != null)
                    {
                        ReturnValue = new TScreenVerificationResult(ReturnValue, AResultColumn, AResultControl);
                    }
                }
                else
                {
                    ReturnValue = null;
                }
            }

            return(ReturnValue);
        }
예제 #2
0
        /// <summary>
        /// Checks whether a strings' length is lesser or equal to the specified amount of characters.  Null values are accepted.
        /// </summary>
        /// <param name="AValue">The string to check.</param>
        /// <param name="APermittedStringLength">The permitted amount of characters.</param>
        /// <param name="ADescription">Description what the value is about (for the
        /// error message).</param>
        /// <param name="AResultContext">Context of verification (can be null).</param>
        /// <param name="AResultColumn">Which <see cref="System.Data.DataColumn" /> failed (can be null).</param>
        /// <param name="AResultControl">Which <see cref="System.Windows.Forms.Control" /> is involved (can be null).</param>
        /// <returns>Null if <paramref name="AValue" /> is not null and not <see cref="String.Empty" />,
        /// otherwise a <see cref="TVerificationResult" /> is returned that
        /// contains details about the problem, with a message that uses <paramref name="ADescription" />.</returns>
        public static TVerificationResult StringLengthLesserOrEqual(string AValue, int APermittedStringLength, string ADescription,
                                                                    object AResultContext = null, System.Data.DataColumn AResultColumn = null, System.Windows.Forms.Control AResultControl = null)
        {
            TVerificationResult ReturnValue = null;
            String Description = THelper.NiceValueDescription(ADescription);

            // Check
            if ((AValue != null) &&
                (AValue.Length > APermittedStringLength))
            {
                ReturnValue = new TVerificationResult(AResultContext,
                                                      ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_STRINGTOOLONG, CommonResourcestrings.StrInvalidStringEntered + Environment.NewLine +
                                                                              StrStringTooLong, new string[] { Description, APermittedStringLength.ToString(), AValue.Length.ToString() }));

                if (AResultColumn != null)
                {
                    ReturnValue = new TScreenVerificationResult(ReturnValue, AResultColumn, AResultControl);
                }
            }

            return(ReturnValue);
        }
예제 #3
0
        /// <summary>
        /// Checks whether a strings is null or <see cref="String.Empty" />.  Null values are accepted.
        /// </summary>
        /// <param name="AValue">The string to check.</param>
        /// <param name="ADescription">Description what the value is about (for the
        /// error message).</param>
        /// <param name="AResultContext">Context of verification (can be null).</param>
        /// <param name="AResultColumn">Which <see cref="System.Data.DataColumn" /> failed (can be null).</param>
        /// <returns>Null if <paramref name="AValue" /> is not null and not <see cref="String.Empty" />,
        /// otherwise a <see cref="TVerificationResult" /> is returned that
        /// contains details about the problem, with a message that uses <paramref name="ADescription" />.</returns>
        public static TVerificationResult StringMustNotBeEmpty(string AValue, string ADescription,
                                                               object AResultContext = null, System.Data.DataColumn AResultColumn = null)
        {
            TVerificationResult ReturnValue = null;
            String Description = THelper.NiceValueDescription(ADescription);

            // Check
            if ((AValue == null) ||
                (AValue == String.Empty))
            {
                ReturnValue = new TVerificationResult(AResultContext,
                                                      ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_NOEMPTYSTRING, CommonResourcestrings.StrInvalidStringEntered + Environment.NewLine +
                                                                              StrStringMustNotBeEmpty, new string[] { Description }));

                if (AResultColumn != null)
                {
                    ReturnValue = new TScreenVerificationResult(ReturnValue, AResultColumn);
                }
            }

            return(ReturnValue);
        }
예제 #4
0
        /// <summary>
        /// Checks whether an International Postal Type is valid. Null values are accepted.
        /// </summary>
        /// <param name="AInternatPostalTypeCode">The International Postal Type to check.</param>
        /// <param name="ADescription">Description what the value is about (for the
        /// error message).</param>
        /// <param name="AResultContext">Context of verification (can be null).</param>
        /// <param name="AResultColumn">Which <see cref="System.Data.DataColumn" /> failed (can be null).</param>
        /// <param name="AResultControl">Which <see cref="System.Windows.Forms.Control" /> is involved (can be null).</param>
        /// <returns>Null if <paramref name="AInternatPostalTypeCode" /> is null,
        /// otherwise a <see cref="TVerificationResult" /> is returned that
        /// contains details about the problem, with a message that uses <paramref name="ADescription" />.</returns>
        public static TVerificationResult IsValidInternationalPostalCode(string AInternatPostalTypeCode,
            string ADescription = "", object AResultContext = null, System.Data.DataColumn AResultColumn = null,
            System.Windows.Forms.Control AResultControl = null)
        {
            TVerificationResult ReturnValue = null;

            Ict.Common.Data.TTypedDataTable IntPostalDT;

            if (AInternatPostalTypeCode != null)
            {
                if (AInternatPostalTypeCode != String.Empty)
                {
                    TSharedValidationHelper.GetData(PInternationalPostalTypeTable.GetTableDBName(), null, out IntPostalDT);

                    if (IntPostalDT.Rows.Find(new object[] { AInternatPostalTypeCode }) == null)
                    {
                        ReturnValue = new TVerificationResult(AResultContext,
                            ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_INVALIDINTERNATIONALPOSTALCODE));

                        if (AResultColumn != null)
                        {
                            ReturnValue = new TScreenVerificationResult(ReturnValue, AResultColumn, AResultControl);
                        }
                    }
                }
                else
                {
                    ReturnValue = new TVerificationResult(AResultContext,
                        ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_INVALIDINTERNATIONALPOSTALCODE));

                    if (AResultColumn != null)
                    {
                        ReturnValue = new TScreenVerificationResult(ReturnValue, AResultColumn, AResultControl);
                    }
                }
            }

            return ReturnValue;
        }
예제 #5
0
        private void ReadControlsManual(TRptCalculator ACalc, TReportActionEnum AReportAction)
        {
            // validation: start date and end date must be provided.
            if (chkUseDate.Checked)
            {
                if (!dtpFromDate.Date.HasValue || !dtpToDate.Date.HasValue || !dtpFromDate.ValidDate(false) || !dtpToDate.ValidDate(false))
                {
                    TVerificationResult VerificationResult = new TVerificationResult(
                        Catalog.GetString("We need a valid start and end date."),
                        Catalog.GetString("Please select a valid start date and a valid end date."),
                        TResultSeverity.Resv_Critical);

                    FPetraUtilsObject.AddVerificationResult(VerificationResult);
                }
                // validation: start date should be less than end date.
                else if (dtpFromDate.Date.Value > dtpToDate.Date.Value)
                {
                    TVerificationResult VerificationResult = new TVerificationResult(
                        Catalog.GetString("Invalid date range"),
                        Catalog.GetString("The end date must be after the start date."),
                        TResultSeverity.Resv_Critical);

                    FPetraUtilsObject.AddVerificationResult(VerificationResult);
                }
            }

            // validation: If "only these anniversaries" is checked, the txt box should not be empty.
            if (chkAnniversaries.Checked)
            {
                if (txtAnniversaries.Text == "")
                {
                    FPetraUtilsObject.AddVerificationResult(new TVerificationResult(
                                                                Catalog.GetString("Empty anniversaries list"),
                                                                Catalog.GetString("Use a comma-separated list like '10,18,21,30,40'"),
                                                                TResultSeverity.Resv_Critical
                                                                ));
                }
            }
        }
예제 #6
0
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="e"></param>
        /// <param name="AVerificationResultCollection"></param>
        /// <param name="AVerificationResult"></param>
        /// <returns></returns>
        public static Boolean VerifyPartnerLocationData(DataColumnChangeEventArgs e,
                                                        TVerificationResultCollection AVerificationResultCollection,
                                                        out TVerificationResult AVerificationResult)
        {
            Boolean ReturnValue;

            AVerificationResult = null;

            // MessageBox.Show('Verifying DataRow...');
            if ((e.Column.ColumnName == PPartnerLocationTable.GetDateEffectiveDBName()) ||
                (e.Column.ColumnName == PPartnerLocationTable.GetDateGoodUntilDBName()))
            {
                VerifyDates(e, AVerificationResultCollection, out AVerificationResult);
            }

            if (e.Column.Ordinal == ((PPartnerLocationTable)e.Column.Table).ColumnEmailAddress.Ordinal)
            {
                VerifyEmailAddress(e, out AVerificationResult);
            }

            if (e.Column.Ordinal == ((PPartnerLocationTable)e.Column.Table).ColumnLocationType.Ordinal)
            {
                VerifyLocationType(e, out AVerificationResult);
            }

            // any verification errors?
            if (AVerificationResult == null)
            {
                ReturnValue = true;
            }
            else
            {
                ReturnValue = false;

                // MessageBox.Show('VerifyPartnerLocationData: There was an error!');
            }

            return(ReturnValue);
        }
예제 #7
0
        /// <summary>
        /// Validates SUser Details
        /// </summary>
        /// <param name="AContext">Context that describes where the data validation failed.</param>
        /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param>
        /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if
        /// data validation errors occur.</param>
        /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that
        /// display data that is about to be validated.</param>
        public static void ValidateSUserDetails(object AContext, SUserRow ARow,
                                                ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult     VerificationResult = null;

            // Don't validate deleted DataRows
            if (ARow.RowState == DataRowState.Deleted)
            {
                return;
            }

            ValidationColumn = ARow.Table.Columns[SUserTable.ColumnPasswordHashId];
            AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData);

            // PasswordHash must not be empty.
            if ((ARow.RowState != DataRowState.Unchanged) && string.IsNullOrEmpty(ARow.PasswordHash))
            {
                VerificationResult = new TScreenVerificationResult(new TVerificationResult(AContext,
                                                                                           ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_MISSING_PASSWORD, new string[] { ARow.UserId })),
                                                                   ValidationColumn, ValidationControlsData.ValidationControl);

                // Handle addition to/removal from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }

            // If this is a first password (no salt) check that the password is valid.
            if ((ARow.RowState != DataRowState.Unchanged) && string.IsNullOrEmpty(ARow.PasswordSalt) && !string.IsNullOrEmpty(ARow.PasswordHash))
            {
                VerificationResult = null;

                if (!CheckPasswordQuality(ARow.PasswordHash, out VerificationResult))
                {
                    VerificationResult = new TScreenVerificationResult(VerificationResult, ValidationColumn, ValidationControlsData.ValidationControl);
                    AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
                }
            }
        }
        private void ReadControlsManual(TRptCalculator ACalc, TReportActionEnum AReportAction)
        {
            if (txtMinAmount.NumberValueInt > txtMaxAmount.NumberValueInt)
            {
                TVerificationResult VerificationResult = new TVerificationResult(
                    Catalog.GetString("Gift Limit wrong."),
                    Catalog.GetString("Minimum Amount can't be greater than Maximum Amount."),
                    TResultSeverity.Resv_Critical);
                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }

            ACalc.AddParameter("param_ledger_number_i", FLedgerNumber);
            ACalc.AddParameter("param_donorkey", txtDonor.Text);
            ACalc.AddParameter("param_extract_name", txtExtract.Text);

            //TODO: Calendar vs Financial Date Handling - Confirm that these should not be ledger dates, i.e. allowing for >12 periods and non-calendar period boundaries
            DateTime FromDateThisYear     = new DateTime(DateTime.Today.Year, 1, 1);
            DateTime ToDatePreviousYear   = new DateTime(DateTime.Today.Year - 1, 12, 31);
            DateTime FromDatePreviousYear = new DateTime(DateTime.Today.Year - 1, 1, 1);

            ACalc.AddParameter("param_to_date_this_year", DateTime.Today);
            ACalc.AddParameter("param_from_date_this_year", FromDateThisYear);
            ACalc.AddParameter("param_to_date_previous_year", ToDatePreviousYear);
            ACalc.AddParameter("param_from_date_previous_year", FromDatePreviousYear);

            ACalc.AddParameter("DonorAddress", "");

            int MaxColumns = ACalc.GetParameters().Get("MaxDisplayColumns").ToInt();

            for (int Counter = 0; Counter <= MaxColumns; ++Counter)
            {
                String ColumnName = ACalc.GetParameters().Get("param_calculation", Counter, 0).ToString();

                if (ColumnName == "Gift Amount")
                {
                    ACalc.AddParameter("param_gift_amount_column", Counter);
                }
            }
        }
        private void ValidateDataDetailsManual(ABatchRow ARow)
        {
            if ((ARow == null) || (ARow.BatchStatus != MFinanceConstants.BATCH_UNPOSTED))
            {
                return;
            }

            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            ParseHashTotal(ARow);

            TSharedFinanceValidation_GL.ValidateGLBatchManual(this,
                                                              ARow,
                                                              ref VerificationResultCollection,
                                                              FValidationControlsDict,
                                                              FStartDateCurrentPeriod,
                                                              FEndDateLastForwardingPeriod);

            //TODO: remove this once database definition is set for Batch Description to be NOT NULL
            // Description is mandatory then make sure it is set
            if (txtDetailBatchDescription.Text.Length == 0)
            {
                DataColumn          ValidationColumn;
                TVerificationResult VerificationResult = null;
                object ValidationContext;

                ValidationColumn  = ARow.Table.Columns[ABatchTable.ColumnBatchDescriptionId];
                ValidationContext = String.Format("Batch number {0}",
                                                  ARow.BatchNumber);

                VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow.BatchDescription,
                                                                        "Description of " + ValidationContext,
                                                                        this, ValidationColumn, null);

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn, true);
            }
        }
        private void ValidateDataDetailsManual(PDataLabelRow ARow)
        {
            // For this validation we have to validate the UsedBy data here in the manual code.
            // This is because it is not backed directly by a row in a data table.
            // Nor is the control associated with a column in any data table
            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;
            DataColumn          ValidationColumn;
            TVerificationResult VerificationResult = null;

            // Personnel context is bound to be valid because it has no UsedBy UI
            if ((CurrentContext == Context.Partner) || (CurrentContext == Context.Application))
            {
                // The added column at the end of the table, which is a concatenated string of checkedListBox entries, must not be empty
                ValidationColumn   = ARow.Table.Columns[UsedByColumnOrdinal];
                VerificationResult = TStringChecks.StringMustNotBeEmpty(ARow[UsedByColumnOrdinal].ToString(),
                                                                        GUIUsedBy,
                                                                        this, ValidationColumn, clbUsedBy);

                if (VerificationResult != null)
                {
                    if (CurrentContext == Context.Partner)
                    {
                        VerificationResult.OverrideResultText(Catalog.GetString("You must check at least one box in the list of Partner classes."));
                    }
                    else if (CurrentContext == Context.Application)
                    {
                        VerificationResult.OverrideResultText(Catalog.GetString("You must check at least one box in the list of Application types."));
                    }
                }

                // Handle addition to/removal from TVerificationResultCollection.
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn, false);
            }

            // Now call the central validation routine for the other verification tasks
            TSharedValidation_CacheableDataTables.ValidateLocalDataFieldSetup(this, ARow, ref VerificationResultCollection,
                                                                              FPetraUtilsObject.ValidationControlsDict);
        }
예제 #11
0
        private void ReadControlsVerify(TRptCalculator ACalc, TReportActionEnum AReportAction)
        {
            // make sure that for each group one radio button is selected
            TFrmPetraReportingUtils.VerifyRadioButtonSelection(rgrRecipientSelection, FPetraUtilsObject);
            TFrmPetraReportingUtils.VerifyRadioButtonSelection(rgrDonorSelection, FPetraUtilsObject);
            TFrmPetraReportingUtils.VerifyRadioButtonSelection(rgrSorting, FPetraUtilsObject);
            TFrmPetraReportingUtils.VerifyRadioButtonSelection(rgrFormatCurrency, FPetraUtilsObject);

            if (!dtpEndDate.ValidDate(false) ||
                !dtpStartDate.ValidDate(false))
            {
                TVerificationResult VerificationResult = new TVerificationResult(
                    Catalog.GetString("Date format problem"),
                    Catalog.GetString("Please check the date entry."),
                    TResultSeverity.Resv_Critical);
                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }
            else
            {
                if (dtpStartDate.Date > dtpEndDate.Date)
                {
                    TVerificationResult VerificationResult = new TVerificationResult(
                        Catalog.GetString("From date is later than to date."),
                        Catalog.GetString("Please change from date or to date."),
                        TResultSeverity.Resv_Critical);
                    FPetraUtilsObject.AddVerificationResult(VerificationResult);
                }
            }

            if (!ucoMotivationCriteria.IsAnyMotivationDetailSelected())
            {
                TVerificationResult VerificationResult = new TVerificationResult(
                    Catalog.GetString("No Motivation Detail selected"),
                    Catalog.GetString("Please select at least one Motivation Detail."),
                    TResultSeverity.Resv_Critical);
                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }
        }
        private void ValidateDataManual(PmGeneralApplicationRow ARow)
        {
            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult     VerificationResult = null;

            TSharedPersonnelValidation_Personnel.ValidateGeneralApplicationManual(this, ARow, true, ref VerificationResultCollection,
                                                                                  FValidationControlsDict);

            TSharedPersonnelValidation_Personnel.ValidateEventApplicationManual(this,
                                                                                FMainDS.PmShortTermApplication[0],
                                                                                ref VerificationResultCollection,
                                                                                FValidationControlsDict);

            if (FDelegateCheckEventApplicationDuplicate != null)
            {
                // Same 'Event' must only exist for one application per person
                ValidationColumn = FMainDS.PmShortTermApplication[0].Table.Columns[PmShortTermApplicationTable.ColumnStConfirmedOptionId];

                if (FValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    if (FDelegateCheckEventApplicationDuplicate(ARow.ApplicationKey, ARow.RegistrationOffice,
                                                                FMainDS.PmShortTermApplication[0].StConfirmedOption))
                    {
                        VerificationResult = new TScreenVerificationResult(new TVerificationResult(this,
                                                                                                   ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_APPLICATION_DUPLICATE_EVENT,
                                                                                                                           new string[] { FMainDS.PmShortTermApplication[0].StConfirmedOption.ToString() })),
                                                                           ValidationColumn, ValidationControlsData.ValidationControl);

                        // Handle addition to/removal from TVerificationResultCollection.
                        // Only add/remove verification result if duplicate found as same field has already been
                        // handled in TSharedPersonnelValidation_Personnel.ValidateEventApplicationManual
                        VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn);
                    }
                }
            }
        }
예제 #13
0
 private void ReadControlsVerify(TRptCalculator ACalc, TReportActionEnum AReportAction)
 {
     if (!dtpEndDate.ValidDate(false) ||
         !dtpStartDate.ValidDate(false))
     {
         TVerificationResult VerificationResult = new TVerificationResult(
             Catalog.GetString("Date format problem"),
             Catalog.GetString("Please check the date entry."),
             TResultSeverity.Resv_Critical);
         FPetraUtilsObject.AddVerificationResult(VerificationResult);
     }
     else
     {
         if (dtpStartDate.Date > dtpEndDate.Date)
         {
             TVerificationResult VerificationResult = new TVerificationResult(
                 Catalog.GetString("From date is later than to date."),
                 Catalog.GetString("Please change from date or to date."),
                 TResultSeverity.Resv_Critical);
             FPetraUtilsObject.AddVerificationResult(VerificationResult);
         }
     }
 }
예제 #14
0
        private void ValidateDataDetailsManual(SSystemDefaultsRow ARow)
        {
            if (FShowingSysAdminCodes)
            {
                return;
            }

            TVerificationResultCollection verificationResults = FPetraUtilsObject.VerificationResultCollection;
            DataColumn          validationColumn   = ARow.Table.Columns[SSystemDefaultsTable.ColumnDefaultValueId];
            TVerificationResult verificationResult = null;

            // First we need to validate that there were no errors setting up the controls for this row
            if (!FControlsDataTable.Validate(ARow.DefaultValue, validationColumn, this, verificationResults))
            {
                // No point in carrying on with other validations because the controls are all messed up
                return;
            }

            // Individual rows can be validated to check that settings code values are ok.
            if (string.Compare(ARow.DefaultCode, SharedConstants.SYSDEFAULT_LOCALISEDCOUNTYLABEL, true) == 0)
            {
                Control[] validationControl = pnlValues.Controls.Find("cValue_0", true);

                if (validationControl.Length > 0)
                {
                    verificationResult = TStringChecks.StringMustNotBeEmpty(ARow.DefaultValue, "",
                                                                            this, validationColumn, validationControl[0]);

                    if (verificationResult != null)
                    {
                        verificationResult.OverrideResultText(CommonResourcestrings.StrSettingCannotBeEmpty);
                    }
                }

                verificationResults.Auto_Add_Or_AddOrRemove(this, verificationResult, validationColumn);
            }
        }
예제 #15
0
        /// <summary>
        /// Checks whether the date is not undefined. DateTime.MinValue is seen as undefined by this Method.
        /// Null values are accepted.
        /// </summary>
        /// <param name="ADate">The date to check.</param>
        /// <param name="ADescription">The name of the date value.</param>
        /// <param name="AResultContext">Context of verification (can be null).</param>
        /// <param name="AResultColumn">Which <see cref="System.Data.DataColumn" /> failed (can be null).</param>
        /// <param name="AResultControl">Which <see cref="System.Windows.Forms.Control" /> is involved (can be null).</param>
        /// <remarks>Usage in the Data Validation Framework: rather than using this Method, use Method
        /// 'TSharedValidationControlHelper.IsNotInvalidDate' for checking the validity of dates as the latter can deal not only with
        /// empty dates, but dates that are invalid in other respects (e.g. exceeding a valid date range)!!!</remarks>
        /// <returns>Null if validation succeeded, otherwise a <see cref="TVerificationResult" /> is
        /// returned that contains details about the problem.</returns>
        public static TVerificationResult IsNotCorporateDateTime(DateTime?ADate, String ADescription,
                                                                 object AResultContext = null, System.Data.DataColumn AResultColumn = null,
                                                                 System.Windows.Forms.Control AResultControl = null)
        {
            TVerificationResult ReturnValue;
            DateTime            TheDate = TSaveConvert.ObjectToDate(ADate);
            DateTime            FirstOfMonth;
            String Description = THelper.NiceValueDescription(ADescription);

            if (!ADate.HasValue)
            {
                return(null);
            }

            FirstOfMonth = new DateTime(TheDate.Year, TheDate.Month, 1);

            // Checks
            if (TheDate == FirstOfMonth)
            {
                //MessageBox.Show('Date <> DateTime.MinValue');
                ReturnValue = null;
            }
            else
            {
                ReturnValue = new TVerificationResult(AResultContext,
                                                      ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_INVALIDDATE,
                                                                              CommonResourcestrings.StrInvalidDateEntered + Environment.NewLine +
                                                                              StrDateMustNotBeLaterThanFirstDayOfMonth, new string[] { Description }));

                if (AResultColumn != null)
                {
                    ReturnValue = new TScreenVerificationResult(ReturnValue, AResultColumn, AResultControl);
                }
            }

            return(ReturnValue);
        }
예제 #16
0
        private void ReadControlsVerify(TRptCalculator ACalc, TReportActionEnum AReportAction)
        {
            if (!dtpEndDate.ValidDate(false) ||
                !dtpStartDate.ValidDate(false))
            {
                TVerificationResult VerificationResult = new TVerificationResult(
                    Catalog.GetString("No valid date."),
                    Catalog.GetString("Please enter a valid date."),
                    TResultSeverity.Resv_Critical);
                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }
            else
            {
                if (dtpStartDate.Date > dtpEndDate.Date)
                {
                    TVerificationResult VerificationResult = new TVerificationResult(
                        Catalog.GetString("From date is later than to date."),
                        Catalog.GetString("Please change from date or to date."),
                        TResultSeverity.Resv_Critical);
                    FPetraUtilsObject.AddVerificationResult(VerificationResult);
                }
            }

            if (rbtMiddleDonor.Checked)
            {
                int From = Convert.ToInt32(txtPercentage.Text);
                int To   = Convert.ToInt32(txtToPercentage.Text);

                if (To > From)
                {
                    // From must be biggern than to
                    String TmpString = txtPercentage.Text;
                    txtPercentage.Text   = txtToPercentage.Text;
                    txtToPercentage.Text = TmpString;
                }
            }
        }
        private void ReadControlsManual(TRptCalculator ACalc, TReportActionEnum AReportAction)
        {
            ACalc.AddParameter("ControlSource", "", ReportingConsts.HEADERCOLUMN);
            ACalc.AddParameter("param_ledger_number_i", FLedgerNumber);

            ACalc.AddParameter("param_all_partners", rbtAllPartners.Checked);
            ACalc.AddParameter("param_extract", rbtExtract.Checked);

            if (rbtExtract.Checked)
            {
                ACalc.AddParameter("param_extract_name", txtExtract.Text);
            }

            if ((AReportAction == TReportActionEnum.raGenerate) &&
                rbtExtract.Checked &&
                (txtExtract.Text.Length == 0))
            {
                TVerificationResult VerificationResult = new TVerificationResult(
                    Catalog.GetString("No recipient selected."),
                    Catalog.GetString("Please select a recipient."),
                    TResultSeverity.Resv_Critical);

                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }

            int MaxColumns = ACalc.GetParameters().Get("MaxDisplayColumns").ToInt();

            for (int Counter = 0; Counter <= MaxColumns; ++Counter)
            {
                String ColumnName = ACalc.GetParameters().Get("param_calculation", Counter, 0).ToString();

                if (ColumnName == "Total Given")
                {
                    ACalc.AddParameter("param_gift_amount_column", Counter);
                }
            }
        }
        public void TestContains()
        {
            TVerificationResult           res1;
            TScreenVerificationResult     res2;
            TVerificationResultCollection coll = new TVerificationResultCollection();

            // Contains(IResultInterface)
            res1 = new TVerificationResult(null, "test1", TResultSeverity.Resv_Noncritical);
            Assert.IsFalse(coll.Contains(res1), "should not contain res1");
            coll.Add(res1);
            Assert.IsTrue(coll.Contains(res1), "should contain res1");

            // Contains(string AResultContext)
            res1 = new TVerificationResult("testcontext", "testresulttext", "testcaption", "testresultcode", TResultSeverity.Resv_Noncritical);
            Assert.IsFalse(coll.Contains("testcontext"), "should not contain testcontext");
            coll.Add(res1);
            Assert.IsTrue(coll.Contains("testcontext"), "should contain testcontext (by string)");

            // Contains(DataColumn)
            DataColumn col = new DataColumn("test", typeof(int));

            Assert.IsFalse(coll.Contains(col), "should not contain col");
            res2 = new TScreenVerificationResult(null, col, "test1", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res2);
            Assert.IsTrue(coll.Contains(col), "should contain col");

            // Contains(DataTable)
            DataTable  tab  = new DataTable("test");
            DataColumn col2 = new DataColumn("test2", typeof(string));

            tab.Columns.Add(col2);
            Assert.IsFalse(coll.Contains(tab), "should not contain tab");
            res2 = new TScreenVerificationResult(null, col2, "test1", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res2);
            Assert.IsTrue(coll.Contains(tab), "should contain tab");
        }
        private void ValidateDataDetailsManual(ARecurringJournalRow ARow)
        {
            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            // Description is mandatory then make sure it is set
            if (ARow.ExchangeRateToBase <= 0)
            {
                DataColumn          ValidationColumn;
                TVerificationResult VerificationResult = null;
                object ValidationContext;

                ValidationColumn  = ARow.Table.Columns[ARecurringJournalTable.ColumnExchangeRateToBaseId];
                ValidationContext = String.Format("Recurring Batch no.: {0}, Journal no.: {1}",
                                                  ARow.BatchNumber,
                                                  ARow.JournalNumber);

                VerificationResult = TNumericalChecks.IsNegativeOrZeroDecimal(ARow.ExchangeRateToBase,
                                                                              "Exchange rate of " + ValidationContext,
                                                                              this, ValidationColumn, null);

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn, true);
            }
        }
        // The main validation method for the controls on this tab page
        private void ValidateDataManual(ALedgerRow ARow)
        {
            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult     VerificationResult = null;

            // make sure that Financial Year Start Date is no later than 28th of a month
            // (this field is not part of a_ledger but will be stored in period 1 of a_accounting_period)
            if (rbtMonthly.Checked)
            {
                // make sure that Financial Year Start Date is not empty
                // (this field is not part of a_ledger but will be stored in period 1 of a_accounting_period)
                if (dtpFinancialYearStartDate.Date == null)
                {
                    VerificationResult = new TScreenVerificationResult(
                        TDateChecks.IsNotUndefinedDateTime(
                            dtpFinancialYearStartDate.Date,
                            lblFinancialYearStartDate.Text.Trim(':'),
                            true,
                            this),
                        null,
                        dtpFinancialYearStartDate);
                }
                else if (dtpFinancialYearStartDate.Date.Value.Day > 28)
                {
                    VerificationResult = new TScreenVerificationResult(
                        this,
                        new DataColumn(),
                        ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_PERIOD_START_DAY_AFTER_28).ErrorMessageText,
                        PetraErrorCodes.ERR_PERIOD_START_DAY_AFTER_28,
                        dtpFinancialYearStartDate,
                        TResultSeverity.Resv_Critical);
                }
                else
                {
                    VerificationResult = null;
                }

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, null);
            }

            // check that there no suspense accounts for this ledger if box is unticked
            ValidationColumn = ARow.Table.Columns[ALedgerTable.ColumnSuspenseAccountFlagId];

            if (FValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (!ARow.SuspenseAccountFlag)
                {
                    if (TRemote.MFinance.Common.ServerLookups.WebConnectors.HasSuspenseAccounts(FLedgerNumber))
                    {
                        VerificationResult = new TScreenVerificationResult(new TVerificationResult(this,
                                                                                                   ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_NO_SUSPENSE_ACCOUNTS_ALLOWED)),
                                                                           ValidationColumn, ValidationControlsData.ValidationControl);
                    }
                    else
                    {
                        VerificationResult = null;
                    }

                    // Handle addition/removal to/from TVerificationResultCollection
                    VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn);
                }
            }

            // check that the number of forwarding periods is not less than the already used ones
            ValidationColumn = ARow.Table.Columns[ALedgerTable.ColumnNumberFwdPostingPeriodsId];

            if (FValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (ARow.NumberFwdPostingPeriods < FMainForm.CurrentForwardPostingPeriods)
                {
                    VerificationResult = new TScreenVerificationResult(new TVerificationResult(this,
                                                                                               ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_NUMBER_FWD_PERIODS_TOO_SMALL,
                                                                                                                       new string[] { FMainForm.CurrentForwardPostingPeriods.ToString(), FMainForm.CurrentForwardPostingPeriods.ToString() })),
                                                                       ValidationColumn, ValidationControlsData.ValidationControl);
                }
                else
                {
                    VerificationResult = null;
                }

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn);
            }

            // check that current period is not greater than number of ledger periods
            ValidationColumn = ARow.Table.Columns[ALedgerTable.ColumnNumberOfAccountingPeriodsId];

            if (FValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                if (ARow.CurrentPeriod > ARow.NumberOfAccountingPeriods)
                {
                    VerificationResult = new TScreenVerificationResult(new TVerificationResult(this,
                                                                                               ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_CURRENT_PERIOD_TOO_LATE)),
                                                                       ValidationColumn, ValidationControlsData.ValidationControl);
                }
                else
                {
                    VerificationResult = null;
                }

                // Handle addition/removal to/from TVerificationResultCollection
                VerificationResultCollection.Auto_Add_Or_AddOrRemove(this, VerificationResult, ValidationColumn);
            }
        }
예제 #21
0
        /// <summary>
        /// Checks whether the date is within a specified date range. Null values are accepted.
        /// </summary>
        /// <remarks>This Method is capable of returning varying<see cref="TVerificationResult" /> objects! The objects
        /// returned are determined by the values specified for <paramref name="ALowerRangeCheckType" /> and
        ///  <paramref name="AUpperRangeCheckType" />!</remarks>
        /// <param name="ADate">Date to check.</param>
        /// <param name="ALowerDateRangeEnd">Lower end of the valid Date Range.</param>
        /// <param name="AUpperDateRangeEnd">Upper end of the valid Date Range.</param>
        /// <param name="ADescription">Name of the date value.</param>
        /// <param name="ALowerRangeCheckType">Type of Date Check: lower end of the valid Date Range (defaults to <see cref="TDateBetweenDatesCheckType.dbdctUnspecific" />).</param>
        /// <param name="AUpperRangeCheckType">Type of Date Check: upper end of the valid Date Range (defaults to <see cref="TDateBetweenDatesCheckType.dbdctUnspecific" />).</param>
        /// <param name="AResultContext">Context of verification (can be null).</param>
        /// <param name="AResultColumn">Which <see cref="System.Data.DataColumn" /> failed (can be null).</param>
        /// <returns>Null if the date <paramref name="ADate" /> is between the lower and the upper end of the Date Range specified
        /// (lower and upper end dates are included), otherwise a verification result with a message that uses
        /// <paramref name="ADescription" />.
        /// </returns>
        public static TVerificationResult IsDateBetweenDates(DateTime?ADate, DateTime?ALowerDateRangeEnd, DateTime?AUpperDateRangeEnd,
                                                             String ADescription,
                                                             TDateBetweenDatesCheckType ALowerRangeCheckType = TDateBetweenDatesCheckType.dbdctUnspecific,
                                                             TDateBetweenDatesCheckType AUpperRangeCheckType = TDateBetweenDatesCheckType.dbdctUnspecific,
                                                             object AResultContext = null, System.Data.DataColumn AResultColumn = null)
        {
            TVerificationResult ReturnValue           = null;
            DateTime            TheDate               = TSaveConvert.ObjectToDate(ADate);
            DateTime            LowerDateRangeEndDate = TSaveConvert.ObjectToDate(ALowerDateRangeEnd);
            DateTime            UpperDateRangeEndDate = TSaveConvert.ObjectToDate(AUpperDateRangeEnd);
            String Description = THelper.NiceValueDescription(ADescription);

            if ((!ADate.HasValue) ||
                (!ALowerDateRangeEnd.HasValue) ||
                (!AUpperDateRangeEnd.HasValue))
            {
                return(null);
            }

            // Check
            if ((TheDate < LowerDateRangeEndDate) ||
                (TheDate > UpperDateRangeEndDate))
            {
                if ((ALowerRangeCheckType == TDateBetweenDatesCheckType.dbdctUnspecific) &&
                    (AUpperRangeCheckType == TDateBetweenDatesCheckType.dbdctUnspecific))
                {
                    ReturnValue = GetUnspecificDateRangeCheckVerificationResult(LowerDateRangeEndDate,
                                                                                UpperDateRangeEndDate,
                                                                                Description,
                                                                                AResultContext);
                }
                else if (TheDate < LowerDateRangeEndDate)
                {
                    if (ALowerRangeCheckType == TDateBetweenDatesCheckType.dbdctNoPastDate)
                    {
                        ReturnValue = new TVerificationResult(AResultContext,
                                                              ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_NOPASTDATE, CommonResourcestrings.StrInvalidDateEntered +
                                                                                      Environment.NewLine +
                                                                                      StrDateMustNotBePastDate, new string[] { Description }));
                    }
                    else if (ALowerRangeCheckType == TDateBetweenDatesCheckType.dbdctUnrealisticDate)
                    {
                        ReturnValue = new TVerificationResult(AResultContext,
                                                              ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_UNREALISTICDATE_ERROR, CommonResourcestrings.StrInvalidDateEntered +
                                                                                      Environment.NewLine +
                                                                                      StrDateNotSensible, new string[] { Description }));
                    }
                    else
                    {
                        ReturnValue = GetUnspecificDateRangeCheckVerificationResult(LowerDateRangeEndDate,
                                                                                    UpperDateRangeEndDate,
                                                                                    Description,
                                                                                    AResultContext);
                    }
                }
                else if (TheDate > UpperDateRangeEndDate)
                {
                    if (AUpperRangeCheckType == TDateBetweenDatesCheckType.dbdctNoFutureDate)
                    {
                        ReturnValue = new TVerificationResult(AResultContext,
                                                              ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_NOFUTUREDATE, CommonResourcestrings.StrInvalidDateEntered +
                                                                                      Environment.NewLine +
                                                                                      StrDateMustNotBeFutureDate, new string[] { Description }));
                    }
                    else if (AUpperRangeCheckType == TDateBetweenDatesCheckType.dbdctUnrealisticDate)
                    {
                        ReturnValue = new TVerificationResult(AResultContext,
                                                              ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_UNREALISTICDATE_ERROR, CommonResourcestrings.StrInvalidDateEntered +
                                                                                      Environment.NewLine +
                                                                                      StrDateNotSensible, new string[] { Description }));
                    }
                    else
                    {
                        ReturnValue = GetUnspecificDateRangeCheckVerificationResult(LowerDateRangeEndDate,
                                                                                    UpperDateRangeEndDate,
                                                                                    Description,
                                                                                    AResultContext);
                    }
                }

                if (AResultColumn != null)
                {
                    ReturnValue = new TScreenVerificationResult(ReturnValue, AResultColumn);
                }
            }
            else
            {
                ReturnValue = null;
            }

            return(ReturnValue);
        }
예제 #22
0
        /// <summary>
        /// Handles validation of a duplicate or non-duplicate record entered in the GUI
        /// </summary>
        /// <param name="AHostContext">Context that describes where the data validation occurs (usually specified as 'this').</param>
        /// <param name="AConstraintExceptionOccurred">Set to True if a constraint exception occurred when saving the data or False otherwise</param>
        /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if
        /// data validation errors occur.</param>
        /// <param name="APrimaryKeyColumn">The data column that will be used to identify the error (usually the first of the primary key columns)</param>
        /// <param name="APrimaryKeyControl">The control corresponding to the Primary Key column</param>
        /// <param name="APrimaryKeys">The array of primary key data columns that define the unique constraint being validated</param>
        public static void ValidateNonDuplicateRecord(object AHostContext,
                                                      bool AConstraintExceptionOccurred,
                                                      TVerificationResultCollection AVerificationResultCollection,
                                                      System.Data.DataColumn APrimaryKeyColumn,
                                                      System.Windows.Forms.Control APrimaryKeyControl,
                                                      System.Data.DataColumn[] APrimaryKeys)
        {
            TVerificationResult verificationResult = null;
            string resultText = String.Empty;

            if (AConstraintExceptionOccurred)
            {
                // Work out what the current user input values are for the primary keys
                ErrCodeInfo errInfo = ErrorCodes.GetErrorInfo(CommonErrorCodes.ERR_DUPLICATE_RECORD);
                resultText = errInfo.ErrorMessageText;

                string hintText  = String.Empty;
                bool   bFoundOne = false;

                foreach (System.Data.DataColumn column in APrimaryKeys)
                {
                    // Look at each primary key name and find its control.  It is quite common for one key (eg Ledger number) to not have a control.
                    System.Windows.Forms.Label   label;
                    System.Windows.Forms.Control control;
                    string controlText = String.Empty;

                    if (GetControlsForPrimaryKey(column, (System.Windows.Forms.Control)AHostContext, out label, out control))
                    {
                        bFoundOne   = true;
                        hintText   += Environment.NewLine;
                        hintText   += label.Text.Replace("&", String.Empty);
                        controlText = GetDisplayTextForControl(control);

                        if (controlText != String.Empty)
                        {
                            // Note from Alan:  I may not have implemented getting control text for all control types
                            // If you find a missing type, please add it to GetDisplayTextForControl()
                            // In the meantime we have to ignore empty text and just display the label text...
                            if (!hintText.EndsWith(":"))
                            {
                                hintText += ":";
                            }

                            hintText += " ";
                            hintText += controlText;
                        }
                    }
                }

                if (!bFoundOne)
                {
                    // See Alan's note above.  This will occur on a form that has no control type that has GetDisplayTextForControl()
                    hintText += Environment.NewLine;
                    hintText += Environment.NewLine;
                    hintText +=
                        String.Format(Catalog.GetString(
                                          "No hint text is available for the following screen:{0}{1}.{0}Please inform the OpenPetra team if you see this message."),
                                      Environment.NewLine, AHostContext.ToString());
                }

                resultText += hintText;
            }

            verificationResult = TGuiChecks.ValidateNonDuplicateRecord(AHostContext,
                                                                       AConstraintExceptionOccurred,
                                                                       resultText,
                                                                       APrimaryKeyColumn,
                                                                       APrimaryKeyControl);

            // Add or remove the error from the collection
            AVerificationResultCollection.AddOrRemove(verificationResult, APrimaryKeyColumn);
        }
        private void ReadControlsManual(TRptCalculator ACalc, TReportActionEnum AReportAction)
        {
            if ((AReportAction == TReportActionEnum.raGenerate) &&
                (rbtPartner.Checked && (txtDonor.Text == "0000000000")))
            {
                TVerificationResult VerificationResult = new TVerificationResult(
                    Catalog.GetString("No donor selected."),
                    Catalog.GetString("Please select a donor."),
                    TResultSeverity.Resv_Critical);

                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }

            if ((AReportAction == TReportActionEnum.raGenerate) &&
                rbtExtract.Checked &&
                (txtExtract.Text == ""))
            {
                TVerificationResult VerificationMessage = new TVerificationResult(
                    Catalog.GetString("Enter an extract name"),
                    Catalog.GetString("No extract name entered!"), TResultSeverity.Resv_Critical);
                FPetraUtilsObject.AddVerificationResult(VerificationMessage);
            }

            if ((AReportAction == TReportActionEnum.raGenerate) &&
                (txtMinAmount.NumberValueInt > txtMaxAmount.NumberValueInt))
            {
                TVerificationResult VerificationResult = new TVerificationResult(
                    Catalog.GetString("Gift Limit wrong."),
                    Catalog.GetString("Minimum Amount can't be greater than Maximum Amount."),
                    TResultSeverity.Resv_Critical);
                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }

            if ((AReportAction == TReportActionEnum.raGenerate) &&
                (cmbReportType.SelectedItem.ToString() == "Complete") &&
                (dtpFromDate.Date > dtpToDate.Date))
            {
                TVerificationResult VerificationResult = new TVerificationResult(
                    Catalog.GetString("From date is later than to date."),
                    Catalog.GetString("Please change from date or to date."),
                    TResultSeverity.Resv_Critical);
                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }

            ACalc.AddParameter("param_ledger_number_i", FLedgerNumber);
            ACalc.AddParameter("param_donorkey", txtDonor.Text);
            ACalc.AddParameter("param_extract_name", txtExtract.Text);

            DateTime FromDateThisYear     = new DateTime(DateTime.Today.Year, 1, 1);
            DateTime ToDatePreviousYear   = new DateTime(DateTime.Today.Year - 1, 12, 31);
            DateTime FromDatePreviousYear = new DateTime(DateTime.Today.Year - 1, 1, 1);

            ACalc.AddParameter("param_end_date_this_year", DateTime.Today);
            ACalc.AddParameter("param_start_date_this_year", FromDateThisYear);
            ACalc.AddParameter("param_end_date_previous_year", ToDatePreviousYear);
            ACalc.AddParameter("param_start_date_previous_year", FromDatePreviousYear);

            if (cmbReportType.SelectedItem.ToString() == "Totals")
            {
                DateTime FromDate = new DateTime(DateTime.Today.Year - 3, 1, 1);
                ACalc.RemoveParameter("param_from_date");
                ACalc.RemoveParameter("param_to_date");
                ACalc.AddParameter("param_from_date", FromDate);
                ACalc.AddParameter("param_to_date", DateTime.Today);

                ACalc.AddParameter("Month0", 1);
                ACalc.AddParameter("Month1", 2);
                ACalc.AddParameter("Year0", DateTime.Today.Year);
                ACalc.AddParameter("Year1", DateTime.Today.Year - 1);
                ACalc.AddParameter("Year2", DateTime.Today.Year - 2);
                ACalc.AddParameter("Year3", DateTime.Today.Year - 3);

                int ColumnCounter = 0;
                ACalc.AddParameter("param_calculation", "Month", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)3.0, ColumnCounter);
                ++ColumnCounter;
                ACalc.AddParameter("param_calculation", "Year-0", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)2.0, ColumnCounter);
                ++ColumnCounter;
                ACalc.AddParameter("param_calculation", "Count-0", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)0.8, ColumnCounter);
                ++ColumnCounter;
                ACalc.AddParameter("param_calculation", "Year-1", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)2.0, ColumnCounter);
                ++ColumnCounter;
                ACalc.AddParameter("param_calculation", "Count-1", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)0.8, ColumnCounter);
                ++ColumnCounter;
                ACalc.AddParameter("param_calculation", "Year-2", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)2.0, ColumnCounter);
                ++ColumnCounter;
                ACalc.AddParameter("param_calculation", "Count-2", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)0.8, ColumnCounter);
                ++ColumnCounter;
                ACalc.AddParameter("param_calculation", "Year-3", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)2.0, ColumnCounter);
                ++ColumnCounter;
                ACalc.AddParameter("param_calculation", "Count-3", ColumnCounter);
                ACalc.AddParameter("ColumnWidth", (float)0.8, ColumnCounter);
                ++ColumnCounter;
                ACalc.SetMaxDisplayColumns(ColumnCounter);
            }
            else
            {
                int MaxColumns = ACalc.GetParameters().Get("MaxDisplayColumns").ToInt();

                for (int Counter = 0; Counter <= MaxColumns; ++Counter)
                {
                    String ColumnName = ACalc.GetParameters().Get("param_calculation", Counter, 0).ToString();

                    if (ColumnName == "Gift Amount")
                    {
                        ACalc.AddParameter("param_gift_amount_column", Counter);
                    }
                }
            }
        }
        /// <summary>
        /// Reads the selected values from the controls,
        /// and stores them into the parameter system of FCalculator
        ///
        /// </summary>
        /// <param name="ACalculator"></param>
        /// <param name="AReportAction"></param>
        /// <returns>void</returns>
        public void ReadControls(TRptCalculator ACalculator, TReportActionEnum AReportAction)
        {
            if (rbtSelectedCostCentres.Checked &&
                (clbCostCentres.GetCheckedStringList().Length == 0) &&
                (AReportAction == TReportActionEnum.raGenerate))
            {
                TVerificationResult VerificationResult = new TVerificationResult(Catalog.GetString("Selected Cost Centres"),
                                                                                 Catalog.GetString("No cost centre was selected!"),
                                                                                 TResultSeverity.Resv_Critical);
                FPetraUtilsObject.AddVerificationResult(VerificationResult);
            }

            /* cost centre options */
            if (rbtAccountLevel.Checked)
            {
                ACalculator.AddParameter("param_costcentreoptions", "AccountLevel");
            }
            else if (rbtAllCostCentres.Checked)
            {
                ACalculator.AddParameter("param_costcentreoptions", "AllCostCentres");
            }
            else if (rbtAllActiveCostCentres.Checked)
            {
                ACalculator.AddParameter("param_costcentreoptions", "AllActiveCostCentres");
            }
            else if (rbtSelectedCostCentres.Checked)
            {
                ACalculator.AddParameter("param_costcentreoptions", "SelectedCostCentres");
            }

            ACalculator.AddParameter("param_paginate", chkPaginate.Checked);
            ACalculator.AddParameter("param_auto_email", chkAutoEmail.Checked);

            String CostCentreListTitle;

            if (rbtAllCostCentres.Checked || rbtAllActiveCostCentres.Checked)
            {
                CostCentreListTitle = clbCostCentres.GetAllStringList();
            }
            else
            {
                CostCentreListTitle = clbCostCentres.GetCheckedStringList();
            }

            ACalculator.AddStringParameter("param_cost_centre_codes", CostCentreListTitle);
            CostCentreListTitle = CostCentreListTitle.Replace("\"", "");

            if (CostCentreListTitle.Length > 25)
            {
                CostCentreListTitle = "Selected Cost Centres";
            }

            ACalculator.AddParameter("param_cost_centre_list_title", CostCentreListTitle);

            ACalculator.AddParameter("param_cost_centre_summary", chkCostCentreBreakdown.Checked);
            ACalculator.AddParameter("param_cost_centre_breakdown", chkCostCentreBreakdown.Checked);
            ACalculator.AddParameter("ExcludeInactiveCostCentres", chkExcludeInactiveCostCentres.Checked);

            /* Level of Detail */
            if (this.rbtDetail.Checked)
            {
                ACalculator.AddParameter("param_depth", "detail");
            }
            else if (this.rbtStandard.Checked)
            {
                ACalculator.AddParameter("param_depth", "standard");
            }
            else
            {
                ACalculator.AddParameter("param_depth", "summary");
            }
        }
        private void ReadControlsManual(TRptCalculator ACalc, TReportActionEnum AReportAction)
        {
            String paramFields = clbFields.GetCheckedStringList(true);

            if (AReportAction == TReportActionEnum.raGenerate)
            {
                if (rbtSelectedFields.Checked && (paramFields.Length == 0))
                {
                    TVerificationResult VerificationMessage = new TVerificationResult(
                        Catalog.GetString("Please select at least one field."),
                        Catalog.GetString("No fields selected!"), TResultSeverity.Resv_Critical);
                    FPetraUtilsObject.AddVerificationResult(VerificationMessage);
                }

                if (rbtAllFields.Checked)
                {
                    paramFields = clbFields.GetAllStringList(true);
                }

                if (!dtpFromDate.ValidDate() || !dtpToDate.ValidDate())
                {
                    TVerificationResult VerificationResult = new TVerificationResult(
                        Catalog.GetString("Date format problem"),
                        Catalog.GetString("Please check the date entry."),
                        TResultSeverity.Resv_Critical);
                    FPetraUtilsObject.AddVerificationResult(VerificationResult);
                }

                if (dtpFromDate.Date > dtpToDate.Date)
                {
                    TVerificationResult VerificationResult = new TVerificationResult(
                        Catalog.GetString("From date is later than to date."),
                        Catalog.GetString("Please change from date or to date."),
                        TResultSeverity.Resv_Critical);
                    FPetraUtilsObject.AddVerificationResult(VerificationResult);
                }
            }

            paramFields = paramFields.Replace("\"", "'");           // single quotes for SQL field names.
            ACalc.AddParameter("param_clbFields", paramFields);


            ACalc.AddParameter("param_ledger_number_i", FLedgerNumber);
            //
            // I need to get the name of the current ledger..

            DataTable LedgerNameTable = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerNameList);
            DataView  LedgerView      = new DataView(LedgerNameTable);

            LedgerView.RowFilter = "LedgerNumber=" + FLedgerNumber;
            String LedgerName = "";

            if (LedgerView.Count > 0)
            {
                LedgerName = LedgerView[0].Row["LedgerName"].ToString();
            }

            ACalc.AddStringParameter("param_ledger_name", LedgerName);
            ALedgerTable LedgerDetailsTable = (ALedgerTable)TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerDetails);
            ALedgerRow   Row          = LedgerDetailsTable[0];
            Int32        LedgerYear   = Row.CurrentFinancialYear;
            Int32        NumPeriods   = Row.NumberOfAccountingPeriods;
            String       CurrencyName = (cmbCurrency.SelectedItem.ToString() == "Base") ? Row.BaseCurrency : Row.IntlCurrency;

            ACalc.AddStringParameter("param_currency_name", CurrencyName);

            ACalc.AddParameter("param_year0", DateTime.Today.Year);
            ACalc.AddParameter("param_year1", DateTime.Today.Year - 1);
            ACalc.AddParameter("param_year2", DateTime.Today.Year - 2);
            ACalc.AddParameter("param_year3", DateTime.Today.Year - 3);
        } // Read Controls Manual
예제 #26
0
        /// <summary>
        /// Checks whether the submitted IBAN (International Bank Account Number) is valid.
        ///
        /// The IBAN is an ISO standard (ISO 13616) designed to ensure that account details are given in a
        /// standard format (bank plus account). IBAN was introduced to provide an international standard
        /// for payee account details and to make details more easy to check. IBAN is a standardised
        /// international format for entering account details which consists of the country code (bank which
        /// maintains the account), the local bank code (eg. in the UK this is the sortcode), the (payee)
        /// account number and a two check digits. Please note that IBANs do not start with "IBAN " and do not
        /// contain spaces when stored in computer systems.
        /// Here is an example of an IBAN: DE89370400440532013000
        ///     DE = ISO 3166-1 country code
        ///         (NOTE: The country code used in an IBAN can deviate from the country code used in a BIC!
        ///     89 = two check digits
        ///     37040044 = sortcode
        ///     0532013000 = account number.
        /// IBANs are only issued by the bank where the account it is issued for is held.
        ///
        /// </summary>
        /// <param name="AIban">String that should be checked</param>
        /// <param name="AResult"></param>
        /// <returns>True if AIban is a valid Iban or an empty String or nil, False if it is
        /// not valid.
        /// </returns>
        public static bool CheckIBAN(System.String AIban, out TVerificationResult AResult)
        {
            AResult = null;

            int    IbanLength;
            string IbanCountryCode;
            int    IbanCheckDigits;
            int    Index       = -1;
            bool   ReturnValue = true;

            // this list was up-to-date as of Jan 2014 (http://www.swift.com/dsp/resources/documents/IBAN_Registry.pdf)
            string[, ] COUNTRY_DATA =
            {
                { "AD", "Andorra",                "24" },
                { "AE", "United Arab Emirates",   "23" },
                { "AL", "Albania",                "28" },
                { "AT", "Austria",                "20" },
                { "AZ", "Azerbaijan",             "28" },
                { "BA", "Bosnia and Herzegovina", "20" },
                { "BE", "Belgium",                "16" },
                { "BG", "Bulgaria",               "22" },
                { "BH", "Bahrain",                "22" },
                { "BR", "Brazil",                 "29" },
                { "CH", "Switzerland",            "21" },
                { "CR", "Costa Rica",             "21" },
                { "CY", "Cyprus",                 "28" },
                { "CZ", "Czech Republic",         "24" },
                { "DE", "Germany",                "22" },
                { "DK", "Denmark",                "18" },
                { "DO", "Dominican Republic",     "28" },
                { "EE", "Estonia",                "20" },
                { "ES", "Spain",                  "24" },
                { "FI", "Finland",                "18" },
                { "FO", "Faroe Islands",          "18" },
                { "FR", "France",                 "27" },
                { "GE", "Georgia",                "22" },
                { "GI", "Gibraltar",              "23" },
                { "GB", "United Kingdom",         "22" },
                { "GL", "Greenland",              "18" },
                { "GR", "Greece",                 "27" },
                { "GT", "Guatemala",              "28" },
                { "HR", "Croatia",                "21" },
                { "HU", "Hungary",                "28" },
                { "IE", "Republic of Ireland",    "22" },
                { "IL", "Israel",                 "23" },
                { "IS", "Iceland",                "26" },
                { "IT", "Italy",                  "27" },
                { "JO", "Jordan",                 "30" },
                { "KU", "Kuwait",                 "30" },
                { "KZ", "Kazakhstan",             "20" },
                { "LB", "Lebanon",                "28" },
                { "LI", "Lichtenstein",           "21" },
                { "LU", "Luxembourg",             "20" },
                { "LV", "Latvia",                 "21" },
                { "LT", "Lithuania",              "20" },
                { "MC", "Monaco",                 "27" },
                { "MD", "Moldova",                "24" },
                { "ME", "Montenegro",             "22" },
                { "MK", "Macedonia",              "19" },
                { "MR", "Mauritania",             "27" },
                { "MT", "Malta",                  "31" },
                { "MU", "Mauritius",              "30" },
                { "NL", "The Netherlands",        "18" },
                { "NO", "Norway",                 "15" },
                { "PK", "Pakistan",               "24" },
                { "PL", "Poland",                 "28" },
                { "PS", "Palestine",              "29" },
                { "PT", "Portugal",               "25" },
                { "QA", "Qatar",                  "29" },
                { "RO", "Romania",                "24" },
                { "RS", "Serbia",                 "22" },
                { "SA", "Saudi Arabia",           "24" },
                { "SE", "Sweden",                 "24" },
                { "SI", "Slovenia",               "19" },
                { "SK", "Slovak Republic",        "24" },
                { "SM", "San Marino",             "27" },
                { "TN", "Tunisia",                "24" },
                { "TR", "Turkey",                 "26" },
                { "VG", "Virgin Islands",         "24" }
            };

            // remove all spaces
            AIban = AIban.Replace(" ", "");

            // make string uppercase for ease
            AIban = AIban.ToUpper();

            // get length
            IbanLength = AIban.Length;

            // check length (must be less or equal to 34 characters)
            if (IbanLength > 34)
            {
                AResult = new TVerificationResult(
                    "CommonRoutines.CheckIBAN",
                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_IBAN_TOO_LONG));

                return(false);
            }

            // check first and second character to be A-Z
            if ((IbanLength < 2) || !Regex.IsMatch(AIban.Substring(0, 2), @"^[A-Z]+$"))
            {
                AResult = new TVerificationResult(
                    "CommonRoutines.CheckIBAN",
                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_IBAN_NOTBEGINWITHTWOLETTERS));

                return(false);
            }
            else
            {
                IbanCountryCode = AIban.Substring(0, 2);
            }

            // check third and fourth character to form a number
            if ((IbanLength < 4) || !Regex.IsMatch(AIban.Substring(2, 2), @"^[0-9]+$"))
            {
                AResult = new TVerificationResult(
                    "CommonRoutines.CheckIBAN",
                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_IBAN_THIRDANDFORTHNOTDIGITS));

                return(false);
            }
            else
            {
                IbanCheckDigits = Convert.ToInt32(AIban.Substring(2, 2));
            }

            // verify check digits (must be within range 02-98)
            if ((IbanCheckDigits < 2) || (IbanCheckDigits == 99))
            {
                AResult = new TVerificationResult(
                    "CommonRoutines.CheckIBAN",
                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_IBAN_CHECKDIGITSAREWRONG));

                return(false);
            }

            // find the index of the country code (if it exists)
            for (int i = 0; i < COUNTRY_DATA.GetLength(0); i++)
            {
                if (COUNTRY_DATA[i, 0] == IbanCountryCode)
                {
                    Index = i;
                    break;
                }
            }

            if (Index == -1)
            {
                AResult = new TVerificationResult(
                    "CommonRoutines.CheckIBAN",
                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_IBAN_COUNTRYNOTDEFINIED, IbanCountryCode));

                ReturnValue = false;
            }

            // check the length of the IBAN for defined countries
            if ((Index != -1) && (Convert.ToInt32(COUNTRY_DATA[Index, 2]) != IbanLength))
            {
                AResult = new TVerificationResult(
                    "CommonRoutines.CheckIBAN",
                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_IBAN_WRONGLENGTH, new string[4]
                {
                    COUNTRY_DATA[Index, 1], COUNTRY_DATA[Index, 0], COUNTRY_DATA[Index, 2].ToString(), IbanLength.ToString()
                }));

                return(false);
            }

            /* calculate and check the checksum */

            // put country and check digits to the end
            AIban = AIban.Substring(4) + AIban.Substring(0, 4);

            //replace each letter by numerical equivalent
            AIban = Regex.Replace(AIban, @"\D", x => ((int)x.Value[0] - 55).ToString());

            int Remainder = 0;

            // Interpret the IBAN as a decimal integer and compute the remainder of that number on division by 97
            while (AIban.Length >= 7)
            {
                Remainder = Convert.ToInt32(AIban.Substring(0, 7)) % 97;
                AIban     = Remainder.ToString() + AIban.Substring(7);
            }

            if (AIban.Length > 0)
            {
                Remainder = Convert.ToInt32(AIban) % 97;
            }

            // checksum only valid if Remainder = 1
            if (Remainder != 1)
            {
                AResult = new TVerificationResult(
                    "CommonRoutines.CheckIBAN",
                    ErrorCodes.GetErrorInfo(PetraErrorCodes.ERR_IBAN_CHECKSUMMISMATCH));

                ReturnValue = false;
            }

            return(ReturnValue);
        }
        public void TestBuildScreenVerificationResultList()
        {
            TVerificationResult           res0, res1, res2, res3, res4, res5, res6, res7, res8, res9, res10;
            TVerificationResultCollection coll = new TVerificationResultCollection();

            res0 = new TVerificationResult(null, "test0", TResultSeverity.Resv_Noncritical);
            coll.Add(res0);
            res1 = new TVerificationResult(null, "test1", TResultSeverity.Resv_Info);
            coll.Add(res1);
            TextBox tb1 = new TextBox();

            res2 = new TVerificationResult(tb1, "test2", TResultSeverity.Resv_Critical);
            coll.Add(res2);
            res3 = new TVerificationResult(tb1, "test3", TResultSeverity.Resv_Noncritical);
            coll.Add(res3);
            DataColumn col = new DataColumn("test", typeof(int));

            res4 = new TScreenVerificationResult(null, col, "test4", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res4);
            DataTable  tab  = new DataTable("test");
            DataColumn col2 = new DataColumn("test2", typeof(string));

            tab.Columns.Add(col2);
            DataColumn col3 = new DataColumn("test3", typeof(string));

            tab.Columns.Add(col3);
            res5 = new TScreenVerificationResult(null, col2, "test5", null, TResultSeverity.Resv_Status);
            coll.Add(res5);
            res6 = new TScreenVerificationResult(null, col, "test6", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res6);
            res7 = new TScreenVerificationResult(null, col3, "test7", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res7);
            res8 = new TScreenVerificationResult("test8", col3, "test8", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res8);

            string  ErrorMessages;
            Control FirstControl;

            coll.BuildScreenVerificationResultList(null, out ErrorMessages, out FirstControl, true);

            Console.WriteLine(ErrorMessages);
            Console.WriteLine(ErrorMessages.Replace("\n", "\\n").Replace("\r", "\\r"));

            string expectedErrorMessages =
                "test4\r\n\r\ntest5\r\n\r\ntest6\r\n\r\ntest7\r\n\r\n";

            Assert.AreEqual(expectedErrorMessages, ErrorMessages, "only show errors of unspecified resultcontext and of TVerificationScreenResult");

            coll.BuildScreenVerificationResultList("test8", out ErrorMessages, out FirstControl, true);

            Console.WriteLine(ErrorMessages);
            Console.WriteLine(ErrorMessages.Replace("\n", "\\n").Replace("\r", "\\r"));

            expectedErrorMessages =
                "test8\r\n\r\n";
            Assert.AreEqual(expectedErrorMessages, ErrorMessages, "only show errors of resultcontext test1 and of TVerificationScreenResult");

            // test first control, but with updatefirstcontrol false
            TextBox tb2 = new TextBox();

            res9 = new TScreenVerificationResult(null, null, "test9", tb2, TResultSeverity.Resv_Critical);
            coll.Add(res9);
            TextBox tb3 = new TextBox();

            res10 = new TScreenVerificationResult(null, null, "test10", tb3, TResultSeverity.Resv_Critical);
            coll.Add(res10);
            coll.BuildScreenVerificationResultList(null, out ErrorMessages, out FirstControl, false);

            Console.WriteLine(ErrorMessages);
            Console.WriteLine(ErrorMessages.Replace("\n", "\\n").Replace("\r", "\\r"));

            expectedErrorMessages =
                "test4\r\n\r\ntest5\r\n\r\ntest6\r\n\r\ntest7\r\n\r\ntest9\r\n\r\ntest10\r\n\r\n";
            Assert.AreEqual(expectedErrorMessages, ErrorMessages, "added test9 and test10");
            Assert.AreEqual(tb2, FirstControl, "expect to return tb2 as first control");
            Assert.AreEqual(null, coll.FirstErrorControl, "expect to not select tb2 as first control");

            // test updatefirstcontrol true
            coll.BuildScreenVerificationResultList(null, out ErrorMessages, out FirstControl, true);
            Assert.AreEqual(tb2, FirstControl, "expect to return tb2 as first control");
            Assert.AreEqual(tb2, coll.FirstErrorControl, "expect to select tb2 as first control");

            // remove res9, so that first control is tb3, but call with updatefirstcontrol false
            coll.Remove(res9);
            coll.BuildScreenVerificationResultList(null, out ErrorMessages, out FirstControl, false);
            Assert.AreEqual(tb3, FirstControl, "expect to return tb3 as first control");
            Assert.AreEqual(tb2, coll.FirstErrorControl, "expect tb2 to be still selected as first control");

            // test other overload of BuildScreenVerificationResult, ignorewarnings etc
            object FirstErrorContext;

            // test ignorewarnings true
            coll.BuildScreenVerificationResultList(out ErrorMessages, out FirstControl, out FirstErrorContext, true, null, true);

            Assert.AreEqual(null, FirstErrorContext, "FirstErrorContext is null");

            Console.WriteLine(ErrorMessages);
            Console.WriteLine(ErrorMessages.Replace("\n", "\\n").Replace("\r", "\\r"));

            expectedErrorMessages = "test1\r\n\r\ntest2\r\n\r\ntest5\r\n\r\ntest10\r\n\r\n";
            Assert.AreEqual(expectedErrorMessages, ErrorMessages, "ignore warnings (ie. noncritical). Include TVerificationResults");

            // test ignorewarnings false
            coll.BuildScreenVerificationResultList(out ErrorMessages, out FirstControl, out FirstErrorContext, true, null, false);

            Console.WriteLine(ErrorMessages);
            Console.WriteLine(ErrorMessages.Replace("\n", "\\n").Replace("\r", "\\r"));

            expectedErrorMessages =
                "test0\r\n\r\ntest1\r\n\r\ntest2\r\n\r\ntest3\r\n\r\ntest4\r\n\r\ntest5\r\n\r\ntest6\r\n\r\ntest7\r\n\r\ntest8\r\n\r\ntest10\r\n\r\n";
            Assert.AreEqual(expectedErrorMessages, ErrorMessages, "do not ignore warnings (ie. noncritical). Include TVerificationResults");

            // test ARestrictToTypeWhichRaisesError, restrict to string errorcontext
            coll.BuildScreenVerificationResultList(out ErrorMessages, out FirstControl, out FirstErrorContext, true, typeof(string), false);
            Console.WriteLine(ErrorMessages);
            Console.WriteLine(ErrorMessages.Replace("\n", "\\n").Replace("\r", "\\r"));

            expectedErrorMessages =
                "test8\r\n\r\n";
            Assert.AreEqual(expectedErrorMessages, ErrorMessages, "restrict to string errorcontext");

            // test AUpdateFirstErrorControl
            coll.BuildScreenVerificationResultList(out ErrorMessages, out FirstControl, out FirstErrorContext, true, null, false);
            // it seems that res2/tb1 is ignored, because it is not a screenverificationresult
            Assert.AreEqual(tb3, FirstControl, "first control should be tb3");
            Assert.AreEqual(tb3, coll.FirstErrorControl, "first error control should be tb3");
            // now testing with res8/tb3 inserted before tb2, and not updating first error control
            coll.Insert(3, res9);
            coll.BuildScreenVerificationResultList(out ErrorMessages, out FirstControl, out FirstErrorContext, false, null, false);
            Assert.AreEqual(tb2, FirstControl, "first control should be tb2");
            Assert.AreEqual(tb3, coll.FirstErrorControl, "first error control should still be tb3");
        }
        public void TestRemove()
        {
            TVerificationResult           res0, res1, res2, res3, res4, res5, res6, res7;
            TVerificationResultCollection coll = new TVerificationResultCollection();

            res0 = new TVerificationResult(null, "test0", TResultSeverity.Resv_Noncritical);
            coll.Add(res0);
            res1 = new TVerificationResult(null, "test1", TResultSeverity.Resv_Noncritical);
            coll.Add(res1);
            TextBox tb1 = new TextBox();

            res2 = new TVerificationResult(tb1, "test2", TResultSeverity.Resv_Noncritical);
            coll.Add(res2);
            res3 = new TVerificationResult(tb1, "test3", TResultSeverity.Resv_Noncritical);
            coll.Add(res3);
            DataColumn col = new DataColumn("test", typeof(int));

            res4 = new TScreenVerificationResult(null, col, "test4", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res4);
            DataTable  tab  = new DataTable("test");
            DataColumn col2 = new DataColumn("test2", typeof(string));

            tab.Columns.Add(col2);
            DataColumn col3 = new DataColumn("test3", typeof(string));

            tab.Columns.Add(col3);
            res5 = new TScreenVerificationResult(null, col2, "test5", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res5);
            res6 = new TScreenVerificationResult(null, col, "test6", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res6);
            res7 = new TScreenVerificationResult(null, col3, "test7", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res7);

            Assert.AreEqual(8, coll.Count, "should be 8 elements at the start of the test");

            // Remove(DataColumn)
            coll.Remove(col);
            Assert.AreEqual(7, coll.Count, "only one element should be removed, even if there are 2 results with column col");
            Assert.AreEqual(4, coll.IndexOf(res5), "res4 was removed");
            coll.Insert(4, res4);
            coll.Remove(new DataColumn("test"));
            Assert.AreEqual(8, coll.Count, "nothing happens when trying to remove unknown column");

            // Remove(IResultInterface value)
            coll.Remove(res1);
            Assert.AreEqual(7, coll.Count, "res1 should have been removed");
            Assert.AreEqual(1, coll.IndexOf(res2), "res1 was removed");
            coll.Insert(1, res1);
            Assert.Throws(typeof(ArgumentException),
                          delegate { coll.Remove(new TVerificationResult(null, "test3", TResultSeverity.Resv_Info)); },
                          "trying to remove unknown verification result throws ArgumentException");

            // Remove(String AResultColumnName)
            coll.Remove("nonexisting");
            Assert.AreEqual(8, coll.Count, "nothing happens when trying to remove unknown resultcolumnname");
            coll.Remove(col.ColumnName);
            Assert.AreEqual(7, coll.Count, "should have removed res4");
            Assert.AreEqual(res6, coll.FindBy(col), "first result with col should be res6");
            coll.Insert(4, res4);

            // Remove(object AResultContext)
            coll.Remove(new TextBox());
            Assert.AreEqual(8, coll.Count, "nothing happens when trying to remove unknown object");
            coll.Remove(tb1);
            Assert.AreEqual(6, coll.Count, "should have removed res2 and res3");
            Assert.AreEqual(null, coll.FindBy(tb1), "there should not be any result with tb1");
        }
        public void TestFindBy()
        {
            TVerificationResult           res0, res1, res2, res3, res4, res5, res6, res7;
            TVerificationResultCollection coll = new TVerificationResultCollection();

            res0 = new TVerificationResult(null, "test0", TResultSeverity.Resv_Noncritical);
            coll.Add(res0);
            res1 = new TVerificationResult(null, "test1", TResultSeverity.Resv_Noncritical);
            coll.Add(res1);
            res2 = new TVerificationResult("stringobject2", "test2", TResultSeverity.Resv_Noncritical);
            coll.Add(res2);
            res3 = new TVerificationResult("stringobject3", "test3", TResultSeverity.Resv_Noncritical);
            coll.Add(res3);
            DataColumn col = new DataColumn("test", typeof(int));

            res4 = new TScreenVerificationResult(null, col, "test4", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res4);
            DataTable  tab  = new DataTable("test");
            DataColumn col2 = new DataColumn("test2", typeof(string));

            tab.Columns.Add(col2);
            DataColumn col3 = new DataColumn("test3", typeof(string));

            tab.Columns.Add(col3);
            res5 = new TScreenVerificationResult(null, col2, "test5", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res5);
            res6 = new TScreenVerificationResult(null, col, "test6", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res6);
            res7 = new TScreenVerificationResult(null, col3, "test7", null, TResultSeverity.Resv_Noncritical);
            coll.Add(res7);

            // FindBy(index)
            Assert.Throws(typeof(ArgumentOutOfRangeException), delegate { coll.FindBy(20); }, "there is no verification result at index 20");

            for (int i = 0; i < 8; i++)
            {
                TVerificationResult v = null;

                switch (i)
                {
                case 0: v = res0; break;

                case 1: v = res1; break;

                case 2: v = res2; break;

                case 3: v = res3; break;

                case 4: v = res4; break;

                case 5: v = res5; break;

                case 6: v = res6; break;

                case 7: v = res7; break;
                }

                Assert.AreEqual(v, coll.FindBy(i), "res" + i.ToString() + " should be at index " + i.ToString());
            }

            // FindBy(object AResultContext)
            Assert.AreEqual(res2, coll.FindBy("stringobject2"), "should find res2 by resultcontext");
            Assert.AreEqual(res3, coll.FindBy("stringobject3"), "should find res3 by resultcontext");
            Assert.AreEqual(null, coll.FindBy("stringobject4"), "there is no verification result with resultcontext stringobject4");
            Assert.AreEqual(null, coll.FindBy(null), "looking for null returns null");

            // FindBy(DataColumn AResultColumn)
            Assert.AreEqual(res4, coll.FindBy(col), "should find res4 by column (first result with that column)");
            Assert.AreEqual(res5, coll.FindBy(col2), "should find res5 by column");
            Assert.AreEqual(res7, coll.FindBy(col3), "should find res7 by column");
            Assert.AreEqual(null, coll.FindBy(new DataColumn("test")), "should not find an unknown column");

            // FindAllBy(DataColumn AResultColumn)
            List <TScreenVerificationResult> result = coll.FindAllBy(col);

            Assert.AreEqual(2, result.Count, "FindAllBy Column should find 2 objects");
            Assert.AreEqual(res4, result[0], "first object should be res4");
            Assert.AreEqual(res6, result[1], "second object should be res6");

            result = coll.FindAllBy(new DataColumn("test"));
            Assert.IsNull(result, "FindAllBy returns null for unknown column");

            // FindAllBy(DataTable ADataTable)
            result = coll.FindAllBy(tab);
            Assert.AreEqual(2, result.Count, "FindAllBy Table should find 2 objects");
            Assert.AreEqual(res5, result[0], "first object should be res5");
            Assert.AreEqual(res7, result[1], "second object should be res7");

            result = coll.FindAllBy(new DataTable("test"));
            Assert.IsNull(result, "FindAllBy returns null for unknown table");
        }
        /// <summary>
        /// save the changes
        /// </summary>
        /// <returns></returns>
        public bool SaveChanges()
        {
            Boolean Result            = false;
            String  CheckedStringList = clbSites.GetCheckedStringList();

            String[]     SiteKeyArray       = CheckedStringList.Split(',');
            Int32        Counter            = 0;
            List <Int64> AddedSiteKeyList   = new List <Int64>();
            List <Int64> RemovedSiteKeyList = new List <Int64>();
            Int64        RemovedSiteKey;
            String       RemovedSiteName;
            Boolean      AnySiteRemoved = false;
            String       UserMessage    = Catalog.GetString(
                "Are you sure you want to remove access to following sites? You will not be able to create Partner Keys for them any longer! \r\n");

            TVerificationResultCollection VerificationResultCollection = new TVerificationResultCollection();
            TVerificationResult           VerificationResult           = TStringChecks.StringMustNotBeEmpty(cmbDefaultSite.Text,
                                                                                                            lblDefaultSite.Text);

            // Handle addition/removal to/from TVerificationResultCollection
            VerificationResultCollection.Auto_Add_Or_AddOrRemove(null, VerificationResult, null);

            if (!TDataValidation.ProcessAnyDataValidationErrors(false, VerificationResultCollection, this.GetType()))
            {
                return(false);
            }

            // save site keys selected for possible use
            for (Counter = 0; Counter < SiteKeyArray.Length; Counter++)
            {
                AddedSiteKeyList.Add(Convert.ToInt64(SiteKeyArray[Counter]));
            }

            // create list of site keys that have been removed and double check with user
            foreach (DataRow SiteRow in AvailableSitesTable.Rows)
            {
                if (!Convert.ToBoolean(SiteRow[SharedConstants.SYSMAN_AVAILABLE_SITES_COLUMN_IS_PARTNER_LEDGER]))
                {
                    // check if previously checked site is now no longer checked
                    RemovedSiteKey = Convert.ToInt64(SiteRow[PUnitTable.GetPartnerKeyDBName()]);

                    if (OriginallyCheckedSites.Contains(RemovedSiteKey))
                    {
                        AnySiteRemoved = true;
                        RemovedSiteKeyList.Add(RemovedSiteKey);
                        RemovedSiteName = SiteRow[PUnitTable.GetUnitNameDBName()].ToString();
                        UserMessage    += "\r\n" + String.Format("{0:0000000000}", RemovedSiteKey) + " - " + RemovedSiteName;
                    }
                }
            }

            if (AnySiteRemoved)
            {
                if (MessageBox.Show(UserMessage, Catalog.GetString("Remove access to Sites"), MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Warning) == DialogResult.No)
                {
                    return(false);
                }
            }

            // save default site key
            if (cmbDefaultSite.SelectedValue != null)
            {
                TSystemDefaults.SetSystemDefault(SharedConstants.SYSDEFAULT_SITEKEY, cmbDefaultSite.SelectedValue.ToString());
            }

            Result = TRemote.MSysMan.WebConnectors.SaveSiteKeys(AddedSiteKeyList, RemovedSiteKeyList);

            if (Result)
            {
                // reload data from server here so the list is sorted by check box value first and then site name (consider doing this
                // on client in the future if performance issues)
                LoadSitesData();

                FPetraUtilsObject.DisableSaveButton();

                // We don't have unsaved changes anymore
                FPetraUtilsObject.HasChanges = false;
            }

            return(Result);
        }