public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            var legacyOfficeCodes = LegacyMappings.Select(x => x.LegacyIdentifier.Substring(0, 2)).ToList();

            #region AccountToBeMerged
            if (!string.IsNullOrWhiteSpace(AccountToBeMerged) && IncludeEDIInvoicingDetails == false)
            {
                results.Add(new ValidationResult("Account to be merged is not valid.", new[] { "AccountToBeMerged" }));
            }
            #endregion

            #region CombineSuffixes
            if (CombineSuffixes.HasValue && ConsolidateInvoicing == false)
            {
                results.Add(new ValidationResult("Combine Suffixes cannot be used if account is not consolidated.", new[] { "CombineSuffixes" }));
            }
            #endregion

            #region CommentLineRequiredComments
            if (!string.IsNullOrWhiteSpace(CommentLineRequiredComments) && CommentLineRequired == null)
            {
                results.Add(new ValidationResult("Cannot add Comment Line Required Comments.", new[] { "CommentLineRequiredComments" }));
            }
            #endregion

            #region ConsolidatedInvoiceMonth
            if (ConsolidatedInvoiceMonth == null && ConsolidateInvoicing == true && new[] { "ZE", "ZF", "ZI", "ZN", "ZP", "ZQ", "ZS", "ZT", "ZU", "ZV", "ZY", "ZZ" }.Any(o1 => legacyOfficeCodes.Any(o2 => o1 == o2)))
            {
                results.Add(new ValidationResult("Consolidated Invoice Month must be selected.", new[] { "ConsolidatedInvoiceMonth" }));
            }

            if (ConsolidatedInvoiceMonth != null && ConsolidateInvoicing == false)
            {
                results.Add(new ValidationResult("Consolidated Invoice Month cannot be used if account is not consolidated.", new[] { "ConsolidatedInvoiceMonth" }));
            }
            #endregion

            #region ConsolidatedInvoiceParameters
            if (ConsolidatedInvoiceParameters.HasValue && ConsolidateInvoicing == false)
            {
                results.Add(new ValidationResult("Consolidated Invoice Parameters cannot be used if account is not consolidated.", new[] { "CombineSuffixes" }));
            }
            #endregion

            #region ConsolidatedInvoicing
            IRepository           repository     = null;
            IValidationRepository validationRepo = null;
            IFeatureConfiguration featureConfig  = null;

            try
            {
                string errorMessageConsolidated;
                if (ServiceLocator.IsLocationProviderSet)
                {
                    try
                    {
                        repository     = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                        validationRepo = ServiceLocator.Current.GetInstance(typeof(IValidationRepository)) as IValidationRepository;
                        featureConfig  = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                    }
                    catch (ActivationException)
                    {
                        //do nothing
                    }
                }

                if (!legacyOfficeCodes.All(x => new[] { "BR", "BT", "CG", "DC", "DV", "LA", "RB", "SF", "TN", "TO", "TQ" }.Contains(x)))
                {
                    if (repository != null)
                    {
                        var suffixIds = LegacyMappings.Where(x => x.LegacySystemName == LegacySystemNames.Suffix.Name).Select(x => x.Id).ToArray();

                        var customer          = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.SecondaryCustomerProfiles);
                        var secondaryProfiles = customer.SecondaryCustomerProfiles;
                        var matchingProfiles  = secondaryProfiles.Where(sp => sp.LegacyMappings
                                                                        .Any(splm =>
                                                                             suffixIds.Contains(splm.Id)));

                        if (matchingProfiles.Any())
                        {
                            //var isoCurrency = matchingProfiles.First().ISOBillingCurrency;
                            //var billingCurrency = matchingProfiles.First().EBSCOBillingCurrency;

                            string errorMessage;

                            if (!validationRepo.ValidateConsolidatedInvoices(this, matchingProfiles.First(), out errorMessageConsolidated))
                            {
                                results.Add(new ValidationResult(string.Format(errorMessageConsolidated), null));
                            }
                        }
                    }
                }

                #endregion

                #region DiscountDays
                if ((DiscountDays ?? 0) > 0 && (CashDiscountPercent ?? 0) == 0)
                {
                    results.Add(new ValidationResult("Discount Days is not valid.", new[] { "DiscountDays" }));
                }
                if ((DiscountDays ?? 0) == 0 && (CashDiscountPercent ?? 0) > 0)
                {
                    results.Add(new ValidationResult("Discount Days is not valid.", new[] { "DiscountDays" }));
                }
                #endregion

                #region EDIFileTransmissionMethod
                if (string.IsNullOrWhiteSpace(EDIFileTransmissionMethod) && IncludeEDIInvoicingDetails)
                {
                    results.Add(new ValidationResult("EDI File Transmission Method is required.", new[] { "EDIFileTransmissionMethod" }));
                }
                if (!string.IsNullOrWhiteSpace(EDIFileTransmissionMethod) && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("EDI File Transmission Method is not valid.", new[] { "EDIFileTransmissionMethod" }));
                }
                #endregion

                #region EDIForMainRenewalInvoiceOnly
                if (EDIForMainRenewalInvoiceOnly && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("EDI For Main Renewal Invoice Only is not valid.", new[] { "EDIForMainRenewalInvoiceOnly" }));
                }
                #endregion

                #region EmailAddressesforAcknowledgements
                if (!string.IsNullOrWhiteSpace(EmailAddressesforAcknowledgements) && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("Email Addresses for Acknowledgements is not valid.", new[] { "EmailAddressesforAcknowledgements" }));
                }
                if (string.IsNullOrWhiteSpace(EmailAddressesforAcknowledgements) && ILSFormat != null && new[] { "EBSCO Standard", "Innovative" }.Contains(ILSFormat, StringComparer.OrdinalIgnoreCase))
                {
                    results.Add(new ValidationResult("Email Addresses for Acknowledgements is required.", new[] { "EmailAddressesforAcknowledgements" }));
                }
                #endregion

                #region F24216 - Add EDI System
                if (featureConfig != null)
                {
                    if (featureConfig.IsAvailable(FeaturesEnum.EDISystem))
                    {
                        if (!string.IsNullOrWhiteSpace(EDISystem) && IncludeEDIInvoicingDetails == false)
                        {
                            results.Add(new ValidationResult("EDI System is not valid.", new[] { "EDISystem" }));
                        }
                        if (string.IsNullOrWhiteSpace(EDISystem) && IncludeEDIInvoicingDetails == true)
                        {
                            results.Add(new ValidationResult("EDI System is required.", new[] { "EDISystem" }));
                        }
                    }
                }
                #endregion

                #region F20178 - Add Fund Code (Client Billing info fields)
                if (featureConfig != null)
                {
                    if (featureConfig.IsAvailable(FeaturesEnum.FundCodeFields))
                    {
                        if (FundCodeRequired == 1 && !string.IsNullOrWhiteSpace(FundCodeRequiredComments))
                        {
                            results.Add(new ValidationResult("Cannot add Fund Code Required Comments.", new[] { "FundCodeRequiredComments" }));
                        }
                        if (FundCodeRequired == 1 && !string.IsNullOrWhiteSpace(FundCodeToPrintOnInvoice))
                        {
                            results.Add(new ValidationResult("Cannot add Fund Code to print on Invoice.", new[] { "FundCodeToPrintOnInvoice" }));
                        }
                        if (FundCodeRequired == 2 && FundCodeToPrintOnInvoice?.Length > 6)
                        {
                            results.Add(new ValidationResult("Fund Code to print on Invoice can not be more than 6 characters.", new[] { "FundCodeToPrintOnInvoice" }));
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(HegisNumberRequiredComments) && HegisNumbersRequired == false)
                        {
                            results.Add(new ValidationResult("Cannot add Hegis Number Required Comments.", new[] { "HegisNumberRequiredComments" }));
                        }
                        if (!string.IsNullOrWhiteSpace(HegisNumberRequiredComments) && HegisNumberRequiredComments.StartsWith("------"))
                        {
                            results.Add(new ValidationResult("Hegis Number Required Comments is invalid.", new[] { "HegisNumberRequiredComments" }));
                        }
                        if (!string.IsNullOrWhiteSpace(HegisNumberRequiredComments) &&
                            (HegisNumberRequiredComments.StartsWith("**C") || HegisNumberRequiredComments.StartsWith("**c")) &&
                            !Regex.IsMatch(HegisNumberRequiredComments, @"\*\*[Cc][123]"))
                        {
                            results.Add(new ValidationResult("Hegis Number Required Comments is invalid.", new[] { "HegisNumberRequiredComments" }));
                        }
                    }
                }
                #endregion

                #region ILSFormat
                if (string.IsNullOrWhiteSpace(ILSFormat) && IncludeEDIInvoicingDetails == true)
                {
                    results.Add(new ValidationResult("ILS Format is required.", new[] { "ILSFormat" }));
                }
                if (!string.IsNullOrWhiteSpace(ILSFormat) && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("ILS Format is not valid.", new[] { "ILSFormat" }));
                }
                #endregion

                #region InvoiceTypestoInclude
                if (InvoiceTypestoInclude != null && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("Invoice Types to Include is not valid.", new[] { "InvoiceTypestoInclude" }));
                }
                #endregion

                #region MaximumInvoiceAmount
                if ((MaximumInvoiceAmount ?? 0) > 0 && (MaximumInvoiceLineItems ?? 0) > 0)
                {
                    results.Add(new ValidationResult("Maximum Invoice Amount and Maximum Line Items are mutually exclusive.", new[] { "MaximumInvoiceAmount" }));
                }
                #endregion

                #region MaximumInvoiceAmountComments
                if (!string.IsNullOrWhiteSpace(MaximumInvoiceAmountComments) && (MaximumInvoiceAmount ?? 0) == 0)
                {
                    results.Add(new ValidationResult("Cannot add Maximum Invoice Amount Comments.", new[] { "MaximumInvoiceAmountComments" }));
                }
                #endregion

                #region MaximumInvoiceLineItems
                if ((MaximumInvoiceAmount ?? 0) > 0 && (MaximumInvoiceLineItems ?? 0) > 0)
                {
                    results.Add(new ValidationResult("Maximum Invoice Amount and Maximum Line Items are mutually exclusive.", new[] { "MaximumInvoiceLineItems" }));
                }
                #endregion

                #region MaximumInvoiceLineItemsComments
                if (!string.IsNullOrWhiteSpace(MaximumInvoiceLineItemsComments) && (MaximumInvoiceLineItems ?? 0) == 0)
                {
                    results.Add(new ValidationResult("Cannot add Maximum Invoice Line Items Comments.", new[] { "MaximumInvoiceLineItemsComments" }));
                }
                #endregion

                #region PeriodSplit
                if (PeriodSplit != null && !legacyOfficeCodes.All(x => new[] { "ZE", "ZF", "ZI", "ZN", "ZP", "ZQ", "ZS", "ZT", "ZU", "ZV", "ZY", "ZZ" }.Contains(x)))
                {
                    results.Add(new ValidationResult("Period Split cannot be selected for this office code.", new[] { "PeriodSplit" }));
                }
                if (PeriodSplit != null && ConsolidateInvoicing == false)
                {
                    results.Add(new ValidationResult("Period Split cannot be used if account is not consolidated.", new[] { "PeriodSplit" }));
                }
                #endregion

                #region ProcessImmediately
                if (ProcessImmediately && ConsolidateInvoicing == false)
                {
                    results.Add(new ValidationResult("Process Immediately cannot be used if account is not consolidated.", new[] { "ProcessImmediately" }));
                }
                #endregion

                #region HoldUntilCurrentRatesAvailable
                if (HoldUntilCurrentRatesAvailable && ConsolidateInvoicing == false)
                {
                    results.Add(new ValidationResult("Hold Until Current Rates Available cannot be used if account is not consolidated.", new[] { "ProcessImmediately" }));
                }
                #endregion

                #region SortbyISC
                if (!string.IsNullOrWhiteSpace(SortbyISC) && SortbyISC != "S" && TSCRequired == true)
                {
                    results.Add(new ValidationResult("Sort by ISC is not valid.", new[] { "SortbyISC" }));
                }
                #endregion

                #region SpecialInstructions
                if (!string.IsNullOrWhiteSpace(SpecialInstructions) && IncludeEDIInvoicingDetails == false)
                {
                    results.Add(new ValidationResult("Special Instructions is not valid.", new[] { "MaximumInvoiceLineItemsComments" }));
                }
                #endregion

                #region TSCRequiredComments
                if (!string.IsNullOrWhiteSpace(TSCRequiredComments) && TSCRequired == false)
                {
                    results.Add(new ValidationResult("Cannot add TSC Required Comments.", new[] { "TSCRequiredComments" }));
                }
                #endregion

                #region UseC1CommentComments
                if (!string.IsNullOrWhiteSpace(UseC1CommentComments) && UseC1Comment == false)
                {
                    results.Add(new ValidationResult("Cannot add Use C1* Comment Comments.", new[] { "UseC1CommentComments" }));
                }
                #endregion

                #region UseC3CommentComments
                if (!string.IsNullOrWhiteSpace(UseC3CommentComments) && UseC3Comment == false)
                {
                    results.Add(new ValidationResult("Cannot add Use C3* Comment Comments.", new[] { "UseC3CommentComments" }));
                }
                #endregion

                #region BreakAdjustmentsBySubscriber
                if (BreakAdjustmentsbySubscriber && OriginalInvoiceItemCount > 0)
                {
                    results.Add(new ValidationResult("Break Adjustments by Subscriber is invalid.", new[] { "BreakAdjustmentsbySubscriber" }));
                }
                if (BreakAdjustmentsbySubscriber && SupplementalInvoiceItemCount > 0)
                {
                    results.Add(new ValidationResult("Break Adjustments by Subscriber is invalid.", new[] { "BreakAdjustmentsbySubscriber" }));
                }
                #endregion

                #region F13205;
                if (featureConfig != null)
                {
                    IEnumerable <BillingLocation> billingLocations = null;
                    var CcisAddedToInvoicesProfileFeatureEnabled   = featureConfig.IsAvailable(FeaturesEnum.CcisAddedToInvoicesProfile);

                    if (CcisAddedToInvoicesProfileFeatureEnabled)
                    {
                        if (IncludeInvoiceDetailReport == true && PrintInvoicesInOldFormat == true)
                        {
                            results.Add(new ValidationResult("Cannot include Invoice Detail Report if Invoice is printed in old format.", new[] { "IncludeInvoiceDetailReport" }));
                        }

                        if (PrintPageTotal == true && PrintRunningSubTotal == true)
                        {
                            results.Add(new ValidationResult("Cannot print both Running Sub-Total and Page Total on an Invoice.", new[] { "PrintPageTotal" }));
                        }

                        // if (featureConfig.IsAvailable(FeaturesEnum.ManageBillingAddresses))
                        if (featureConfig.IsAvailable("CA.F7222.US326097.BillingLocationSAPSync"))
                        {
                            if (repository != null && !IsDefault)
                            {
                                var suffixLegacyMappingIds = LegacyMappings.Where(lm => lm.LegacySystemName == LegacySystemNames.Suffix.Name).Select(x => x.Id);

                                billingLocations = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.BillingLocations)
                                                   .BillingLocations.Where(x => x.LegacyMappings.Any(lm => suffixLegacyMappingIds.Contains(lm.Id)))
                                                   .ToArray();

                                if (SplitPaymentUsePublicAdministrationVATMatrix && !billingLocations.All(x => x.CountryCode.Equals("IT")))
                                {
                                    results.Add(new ValidationResult("Public Administration VAT Matrix is only available in Italy.", new[] { "SplitPaymentUsePublicAdministrationVatMatrix" }));
                                }
                            }
                        }
                        else
                        {
                            if (SplitPaymentUsePublicAdministrationVATMatrix == true && !legacyOfficeCodes.Any(x => new[] { "ZI", "ZQ" }.Contains(x)))
                            {
                                results.Add(new ValidationResult("Public Administration VAT Matrix is only available in Italy.", new[] { "SplitPaymentUsePublicAdministrationVatMatrix" }));
                            }
                        }


                        //begin - can move to attributes when feature CA.F13205 enabled
                        if (string.IsNullOrWhiteSpace(MailInvoicesTo))
                        {
                            results.Add(new ValidationResult("Mail Invoices To is a required field.", new[] { "MailInvoicesTo" }));
                        }

                        Regex regex = new Regex(@"(([a-zA-Z0-9_\-\.']+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,63}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*");
                        if (!string.IsNullOrEmpty(AlternateReplyToEmailAddressForInvoices))
                        {
                            if (AlternateReplyToEmailAddressForInvoices.Length > 100)
                            {
                                results.Add(new ValidationResult("Alternate Reply To Email Address for Invoices exceeds maximum length of 100.", new[] { "AlternateReplyToEmailAddressForInvoices" }));
                            }

                            var email = regex.Match(AlternateReplyToEmailAddressForInvoices);
                            if (email.Value.Length != AlternateReplyToEmailAddressForInvoices.Length)
                            {
                                results.Add(new ValidationResult("Alternate Reply to Email Addresses for Invoices is invalid.  Multiple emails should be seperated by a semicolon ';'", new[] { "AlternateReplyToEmailAddressForInvoices" }));
                            }
                        }

                        if (!string.IsNullOrEmpty(EmailAddressForOvernightEdits))
                        {
                            if (EmailAddressForOvernightEdits.Length > 200)
                            {
                                results.Add(new ValidationResult("Email Address for Overnight Edits exceeds maximum length of 200.", new[] { "EmailAddressForOvernightEdits" }));
                            }
                            var email = regex.Match(EmailAddressForOvernightEdits);
                            if (email.Value.Length != EmailAddressForOvernightEdits.Length)
                            {
                                results.Add(new ValidationResult("Email Addresses for Overnight Edits is invalid..  Multiple emails should be seperated by a semicolon ';'", new[] { "EmailAddressForOvernightEdits" }));
                            }
                        }
                        //end - can move to attributes when feature CA.F13205 enabled
                    }
                }
                #endregion

                if (validationRepo != null)
                {
                    string errorMessage;
                    if (!validationRepo.ValidateProfile(this, out errorMessage))
                    {
                        results.Add(new ValidationResult(string.Format("Profile failed SAP validation: {0}", errorMessage), null));
                    }
                }

                return(results);
            }
            finally
            {
                repository?.Dispose();
                validationRepo?.Dispose();
            }
        }
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List <ValidationResult>();

            if ((new[] { "US", "CA" }.Contains(CountryCode)) && string.IsNullOrWhiteSpace(PostalCode))
            {
                results.Add(new ValidationResult("Postal is required.", new[] { "Postal" }));
            }

            if (CountryCode == "US" && PostalCode != null && !Regex.Match(PostalCode, @"^\d{1,5}(\-\d{4})?$").Success)
            {
                results.Add(new ValidationResult("Postal is not valid.", new[] { "Postal" }));
            }

            if ((new[] { "US", "CA", "AU" }.Contains(CountryCode)) && string.IsNullOrWhiteSpace(StateProvince))
            {
                results.Add(new ValidationResult("State is required.", new[] { "StateProvince" }));
            }

            if (CountryCode == "CA" && PostalCode != null && !Regex.Match(PostalCode, @"(\D\d\D\s\d\D\d)").Success)
            {
                results.Add(new ValidationResult("Postal is not valid.", new[] { "Postal" }));
            }

            if (MainframeAddressOverride != null)
            {
                if (string.IsNullOrWhiteSpace(MainframeAddressOverride.PostalCode) && (MainframeAddressOverride.CountryCode == "US"))
                {
                    results.Add(new ValidationResult("ZIP is required.", new[] { "Postal" }));
                }

                if (!string.IsNullOrWhiteSpace(MainframeAddressOverride.PostalCode) && !(MainframeAddressOverride.CountryCode == "US"))
                {
                    results.Add(new ValidationResult("ZIP is for US only.", new[] { "Postal" }));
                }
            }


            var accountLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == LegacySystemNames.Account.Name);

            if (accountLegacyMapping != null && BillingProfile != null)
            {
                if (accountLegacyMapping.LegacyIdentifier.StartsWith("Z") && BillingProfile.TaxExemptNumber != null)
                {
                    results.Add(new ValidationResult("Tax Exempt Number cannot be used for this office."));
                }

                //VAT Number  Office != Z * Value is not null   VAT Number cannot be used for this office.
                if (BillingProfile.VATNumber != null && !accountLegacyMapping.LegacyIdentifier.StartsWith("Z"))
                {
                    results.Add(new ValidationResult("VAT Number cannot be used for this office.", new[] { "VATNumber" }));
                }
            }

            //GST Exempt  Billing Address Country != Canada  Value = Y   Country cannot be GST Exempt.
            if (BillingProfile.GSTExempt == true && CountryCode != "CA")
            {
                results.Add(new ValidationResult("Country cannot be GST Exempt."));
            }


            //QST Exempt  Billing Address Country != Canada  Value = Y   Country cannot be QST Exempt.
            if (BillingProfile.QSTExempt == true && CountryCode != "CA")
            {
                results.Add(new ValidationResult("Country cannot be QST Exempt."));
            }



            if (results.Count > 0)
            {
                return(results);
            }


            IValidationRepository validator  = null;
            IRepository           repository = null;

            try
            {
                if (ServiceLocator.IsLocationProviderSet)
                {
                    try
                    {
                        validator  = ServiceLocator.Current.GetInstance <IValidationRepository>();
                        repository = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                    }
                    catch (ActivationException) { }
                }

                /* validate the address using the tax service */
                if (validator != null)
                {
                    if (!validator.ValidateTaxAddress(this))
                    {
                        results.Add(new ValidationResult("Billing Address is not tax compliant.  City and/or Postal Code are invalid for the selected Country.", new[] { "SystemAddress" }));
                    }

                    string errorMessage;
                    if (!validator.ValidateBillingLocation(this, out errorMessage))
                    {
                        results.Add(new ValidationResult(string.Format("Billing location failed SAP validation: {0}", errorMessage), null));
                    }
                }


                if (LegacyMappings.Any(x => x.LegacySystemName == LegacySystemNames.Suffix.Name))
                {
                    if (MainframeAddressOverride == null)
                    {
                        if (repository != null)
                        {
                            var formatter        = new MainframeAddressFormatter(repository);
                            var convertedAddress = formatter.ConvertBillingAddress(this);
                            if (
                                (convertedAddress.Name ?? string.Empty).Length > 30 ||
                                (convertedAddress.Line1 ?? string.Empty).Length > 30 ||
                                (convertedAddress.Line2 ?? string.Empty).Length > 30 ||
                                (convertedAddress.Line3 ?? string.Empty).Length > 30
                                )
                            {
                                results.Add(new ValidationResult("Billing Address is not mainframe compliant. Please use Mainframe Override address."));
                            }
                        }
                    }
                    else
                    {
                        /* Check if the billing address is mainframe compliant and still mainframe override address is provided  */
                        if (repository != null)
                        {
                            var formatter        = new MainframeAddressFormatter(repository);
                            var convertedAddress = formatter.ConvertBillingAddress(this);
                            if (
                                (convertedAddress.Name ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line1 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line2 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line3 ?? string.Empty).Length <= 30
                                )
                            {
                                results.Add(new ValidationResult(
                                                "Billing Address is mainframe compliant. Please remove Mainframe Override address."));
                                return(results);
                            }
                        }

                        var context = new ValidationContext(MainframeAddressOverride, serviceProvider: null, items: null);
                        Validator.TryValidateObject(MainframeAddressOverride, context, results, true);
                    }

                    if (BillingProfile != null)
                    {
                        var context = new ValidationContext(BillingProfile, serviceProvider: null, items: null);
                        Validator.TryValidateObject(BillingProfile, context, results, true);
                    }


                    if (repository == null)
                    {
                        return(results);
                    }

                    if (accountLegacyMapping == null)
                    {
                        return(results);
                    }

                    var suffixLegacyMapping = LegacyMappings.First(x => x.LegacySystemName == LegacySystemNames.Suffix.Name);

                    var countries = repository.GetCountries();
                    var country   = countries.FirstOrDefault(x => x.Value == CountryCode);
                    if (string.IsNullOrEmpty(country?.MainframeShortCode) && MainframeAddressOverride == null)
                    {
                        results.Add(new ValidationResult("Billing Address is not mainframe compliant. Mainframe does not support the specified country.  Please use Mainframe Override Address."));
                    }
                }

                return(results);
            }
            finally
            {
                validator?.Dispose();
                repository?.Dispose();
            }
        }
        public new IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            IFeatureConfiguration featureConfig = null;

            if (ServiceLocator.IsLocationProviderSet)
            {
                try
                {
                    featureConfig = ServiceLocator.Current.GetInstance(typeof(IFeatureConfiguration)) as IFeatureConfiguration;
                }
                catch (ActivationException)
                {
                    //do nothing
                }
            }

            var results = new List <ValidationResult>();

            if ((new[] { "US", "CA" }.Contains(CountryCode)) && string.IsNullOrWhiteSpace(PostalCode))
            {
                results.Add(new ValidationResult("Postal is required.", new[] { "Postal" }));
            }

            if (CountryCode == "US" && PostalCode != null && !Regex.Match(PostalCode, @"^\d{1,5}(\-\d{4})?$").Success)
            {
                results.Add(new ValidationResult("Postal is not valid.", new[] { "Postal" }));
            }

            if ((new[] { "US", "CA", "AU" }.Contains(CountryCode)) && string.IsNullOrWhiteSpace(StateProvince))
            {
                results.Add(new ValidationResult("State is required.", new[] { "StateProvince" }));
            }

            if (CountryCode == "CA" && PostalCode != null && !Regex.Match(PostalCode, @"(\D\d\D\s\d\D\d)").Success)
            {
                results.Add(new ValidationResult("Postal is not valid.", new[] { "Postal" }));
            }

            if (FteCounts?.Select(x => x.CountType).Distinct().Count() != FteCounts?.Select((x => x.CountType)).Count())
            {
                results.Add(new ValidationResult("FTE Type cannot be selected more than once.", new[] { "Fte" }));
            }

            if (ShippingProfile != null)
            {
                var tempGST = ShippingProfile.GSTExempt.HasValue ? (bool)ShippingProfile.GSTExempt : false;
                var tempQST = ShippingProfile.QSTExempt.HasValue ? (bool)ShippingProfile.QSTExempt : false;

                if (CountryCode != "CA" && tempGST)
                {
                    results.Add(new ValidationResult("Country cannot be GST Exempt.", new[] { "GST Exempt" }));
                }

                if (CountryCode != "CA" && tempQST)
                {
                    results.Add(new ValidationResult("Country cannot be QST Exempt.", new[] { "QST Exempt" }));
                }

                //LANGUAGE
                var accountLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == LegacySystemNames.Account.Name);
                if (accountLegacyMapping != null)
                {
                    if (!string.IsNullOrWhiteSpace(ShippingProfile.Language) &&
                        !accountLegacyMapping.LegacyIdentifier.StartsWith("Z") &&
                        !new[] { "AU", "BA", "FB", "JA", "KO", "NZ", "TO", "TQ", "TW" }.Contains(accountLegacyMapping.LegacyIdentifier.Substring(0, 2)))
                    {
                        results.Add(new ValidationResult("Language cannot be selected for this office.", new[] { "Language" }));
                    }

                    if (!string.IsNullOrWhiteSpace(ShippingProfile.Language) &&
                        //!new[] { "DU - Dutch", "EN - Englisth", "FR - French", "GE - German", "IT - Italian", "PR - Portuguese", "SO - South African", "SP - Spanish", "TU - Turkish" }.Contains(ShippingProfile.Language))
                        !new[] { "DU", "EN", "FR", "GE", "IT", "PR", "SO", "SP", "TU" }.Contains(ShippingProfile.Language))
                    {
                        results.Add(new ValidationResult("Language code is invalid.", new[] { "Language" }));
                    }

                    if (featureConfig.IsAvailable(FeaturesEnum.SplitTaxExemptAndVatOnShippingProfile))
                    {
                        if (ShippingProfile != null)
                        {
                            if (accountLegacyMapping.LegacyIdentifier.StartsWith("Z") && !string.IsNullOrEmpty(ShippingProfile.TaxExemptNumber))
                            {
                                results.Add(new ValidationResult("Tax Exempt Number cannot be used for this office."));
                            }

                            //VAT Number  Office != Z * Value is not null   VAT Number cannot be used for this office.
                            if (!string.IsNullOrEmpty(ShippingProfile.VATNumber) && !accountLegacyMapping.LegacyIdentifier.StartsWith("Z"))
                            {
                                results.Add(new ValidationResult("VAT Number cannot be used for this office.", new[] { "VATNumber" }));
                            }
                        }
                    }
                }

                //ITEM FORMATS
                var ItemFormat1Thru6 = new List <string>();

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat1))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat1);
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat2))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat2);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat2" }));
                    }
                }


                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat3))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat3);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat3" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat4))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat4);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat4" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat5))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat5);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat5" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.ItemFormat6))
                {
                    ItemFormat1Thru6.Add(ShippingProfile.ItemFormat6);
                    if (ItemFormat1Thru6.Distinct().Count() != ItemFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Item Formats cannot be selected more than once.", new[] { "ItemFormat6" }));
                    }
                }

                //STANDARD FORMATS
                var StandardFormat1Thru6 = new List <string>();

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat1))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat1);
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat1))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat1" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat2))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat2);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat2" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat2))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat2" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat3))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat3);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat3" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat3))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat3" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat4))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat4);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat4" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat4))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat4" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat5))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat5);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat5" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat5))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat5" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(ShippingProfile.StandardFormat6))
                {
                    StandardFormat1Thru6.Add(ShippingProfile.StandardFormat6);
                    if (StandardFormat1Thru6.Distinct().Count() != StandardFormat1Thru6.Count())
                    {
                        results.Add(new ValidationResult("Standard Formats cannot be selected more than once.", new[] { "StandardFormat6" }));
                    }
                    if (ItemFormat1Thru6.Contains(ShippingProfile.StandardFormat6))
                    {
                        results.Add(new ValidationResult("Format cannot be selected as both Standard and Item Format.", new[] { "StandardFormat6" }));
                    }
                }

                //RATE CLASS
                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Institution) &&
                    ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Individual))
                {
                    results.Add(new ValidationResult("Individual and Institution are mutually exclusive.", new[] { "RateClass" }));
                }

                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) &&
                    ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator))
                {
                    results.Add(new ValidationResult("Special Educator and Regular Educator are mutually exclusive.", new[] { "RateClass" }));
                }

                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional) &&
                    ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional))
                {
                    results.Add(new ValidationResult("Special Professional and Regular Professional are mutually exclusive.", new[] { "RateClass" }));
                }

                if ((ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator)) &&
                    (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Field) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Military)))
                {
                    results.Add(new ValidationResult("Rate Class selection is mutually exclusive.", new[] { "RateClass" }));
                }

                if ((ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional)) &&
                    (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Field) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Military)))
                {
                    results.Add(new ValidationResult("Rate Class selection is mutually exclusive.", new[] { "RateClass" }));
                }

                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Field) &&
                    (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Military) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional)))
                {
                    results.Add(new ValidationResult("Rate Class selection is mutually exclusive.", new[] { "RateClass" }));
                }

                if (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Military) &&
                    (ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularEducator) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.Field) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.SpecialProfessional) ||
                     ShippingProfile.RateClass.HasFlag(ShippingProfile.RateClassEnum.RegularProfessional)))
                {
                    results.Add(new ValidationResult("Rate Class selection is mutually exclusive.", new[] { "RateClass" }));
                }


                #region Postage
                if (featureConfig.IsAvailable(FeaturesEnum.AddJetsDropAddress))
                {
                    if (!string.IsNullOrEmpty(ShippingProfile.Postage))
                    {
                        string countryCode = CountryCode;
                        bool   isAlternateShippingAddress = false;

                        if (JetsAddress != null)
                        {
                            countryCode = JetsAddress.CountryCode;
                            isAlternateShippingAddress = true;
                        }
                        else if (DropAddress != null)
                        {
                            countryCode = DropAddress.CountryCode;
                            isAlternateShippingAddress = true;
                        }

                        if (ShippingProfile.Postage == " " && countryCode != "US")
                        {
                            results.Add(isAlternateShippingAddress
                                ? new ValidationResult("US postage may not be valid based on alternate shipping address.",
                                                       new[] { "Postage" })
                                : new ValidationResult("US postage may not be valid based on shipping address.",
                                                       new[] { "Postage" }));
                        }

                        if (ShippingProfile.Postage != " " && countryCode == "US")
                        {
                            results.Add(isAlternateShippingAddress
                                ? new ValidationResult("Postage must be US based on alternate shipping address.",
                                                       new[] { "Postage" })
                                : new ValidationResult("Postage must be US based on shipping address.",
                                                       new[] { "Postage" }));
                        }
                    }
                }
                #endregion
            }

            #region JetsAddress.JetsServiceChargePercent
            if (JetsAddress != null)
            {
                var accountLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == "Mainframe - Account");
                if (accountLegacyMapping != null)
                {
                    if ((JetsAddress.JetsServiceChargePercent > 0m) &&
                        (!new[] { "AU", "BA", "FB", "JA", "KO", "MX", "TW", "ZE", "ZF", "ZI", "ZJ", "ZN", "ZP", "ZQ", "ZR", "ZS", "ZT", "ZU", "ZV", "ZX", "ZY", "ZZ" }.Contains(accountLegacyMapping.LegacyIdentifier.Substring(0, 2))))
                    {
                        results.Add(new ValidationResult("JETS Service Charge Percent cannot be used for this office.", new[] { "JetsServiceChargePercent" }));
                    }
                }
            }
            #endregion

            if (results.Count > 0)
            {
                return(results);
            }


            IValidationRepository validator  = null;
            IRepository           repository = null;
            try
            {
                if (ServiceLocator.IsLocationProviderSet)
                {
                    try
                    {
                        validator  = ServiceLocator.Current.GetInstance <IValidationRepository>();
                        repository = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                    }
                    catch (ActivationException) { }
                }



                //var context = new ValidationContext(Address, serviceProvider: null, items: null);
                //var result = Validator.TryValidateObject(Address, context, results, true);
                //if(!result)
                //    return results;

                //IRepository repository = null;
                ////IListLookupService lookupService = null;
                //if (ServiceLocator.IsLocationProviderSet)
                //    try
                //    {
                //        //repository = ServiceLocator.Current.GetInstance(typeof(IRepository)) as IRepository;
                //        //lookupService = ServiceLocator.Current.GetInstance(typeof(IListLookupService)) as IListLookupService;
                //    }
                //    catch (ActivationException)
                //    {
                //        //do nothing
                //    }

                /* validate the address using the tax service */
                if (validator != null)
                {
                    if (!validator.ValidateTaxAddress(this))
                    {
                        results.Add(new ValidationResult("Shipping Address is not tax compliant.  City and/or Postal Code are invalid for the selected Country.", new[] { "SystemAddress" }));
                    }
                }

                if (LegacyMappings.Any(x => x.LegacySystemName == LegacySystemNames.Subscriber.Name))
                {
                    if (MainframeAddressOverride == null)
                    {
                        if (LegacyMappings.Any(x => x.LegacySystemName == LegacySystemNames.Subscriber.Name))
                        {
                            if (repository != null)
                            {
                                var formatter        = new MainframeAddressFormatter(repository);
                                var convertedAddress = formatter.ConvertShippingAddress(this);
                                if (
                                    (convertedAddress.Name ?? string.Empty).Length > 30 ||
                                    (convertedAddress.Line1 ?? string.Empty).Length > 30 ||
                                    (convertedAddress.Line2 ?? string.Empty).Length > 30 ||
                                    (convertedAddress.Line3 ?? string.Empty).Length > 30 ||
                                    (convertedAddress.Line4 ?? string.Empty).Length > 30
                                    )
                                {
                                    results.Add(new ValidationResult("Shipping Address is not mainframe compliant. Please use Mainframe Override address."));
                                }
                            }
                        }
                    }
                    else
                    {
                        /* Check if the shipping address is mainframe compliant and still mainframe override address is provided  */
                        if (repository != null)
                        {
                            var formatter        = new MainframeAddressFormatter(repository);
                            var convertedAddress = formatter.ConvertShippingAddress(this);
                            if (
                                (convertedAddress.Name ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line1 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line2 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line3 ?? string.Empty).Length <= 30 &&
                                (convertedAddress.Line4 ?? string.Empty).Length <= 30
                                )
                            {
                                results.Add(new ValidationResult(
                                                "Shipping Address is mainframe compliant. Please remove Mainframe Override address."));
                                return(results);
                            }
                        }

                        var context = new ValidationContext(MainframeAddressOverride, serviceProvider: null, items: null);
                        Validator.TryValidateObject(MainframeAddressOverride, context, results, true);
                    }

                    if (TapeAddress != null)
                    {
                        var context = new ValidationContext(TapeAddress, serviceProvider: null, items: null);
                        Validator.TryValidateObject(TapeAddress, context, results, true);
                    }

                    if (JetsAddress != null)
                    {
                        var context = new ValidationContext(JetsAddress, serviceProvider: null, items: null);
                        Validator.TryValidateObject(JetsAddress, context, results, true);
                    }

                    if (DropAddress != null)
                    {
                        var context = new ValidationContext(DropAddress, serviceProvider: null, items: null);
                        Validator.TryValidateObject(DropAddress, context, results, true);
                    }

                    if (ShippingProfile != null)
                    {
                        var context = new ValidationContext(ShippingProfile, serviceProvider: null, items: null);
                        Validator.TryValidateObject(ShippingProfile, context, results, true);
                    }

                    if (LegacyMappings.Count > 0)
                    {
                        if (repository == null)
                        {
                            return(results);
                        }

                        var accountLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == LegacySystemNames.Account.Name);
                        if (accountLegacyMapping == null)
                        {
                            return(results);
                        }

                        var subcodeLegacyMapping = LegacyMappings.FirstOrDefault(x => x.LegacySystemName == LegacySystemNames.Subscriber.Name);

                        if (subcodeLegacyMapping != null)
                        {
                            if (subcodeLegacyMapping.LegacyIdentifier.Length < 10)
                            {
                                results.Add(new ValidationResult("Subscriber Mapping is not 2 character long.", new[] { "Subscriber Code" }));
                            }

                            var existingCustomer = repository.GetCustomer(CustomerId, RelatedEntitiesEnum.ShippingLocations);
                            foreach (var location in existingCustomer.ShippingLocations.Where(x => x.Id != Id && x.LegacyMappings.Any(alm => alm.Id == accountLegacyMapping.Id)))
                            {
                                if (location.LegacyMappings.Any(x => x.LegacySystemName == LegacySystemNames.Subscriber.Name && x.LegacyIdentifier == subcodeLegacyMapping.LegacyIdentifier))
                                {
                                    results.Add(new ValidationResult("Subscriber is already mapped to an existing address.", new[] { "Subscriber Code" }));
                                    break;
                                }
                            }

                            var countries = repository.GetCountries();
                            var country   = countries.FirstOrDefault(x => x.Value == CountryCode);
                            if (string.IsNullOrEmpty(country?.MainframeShortCode) && MainframeAddressOverride == null)
                            {
                                results.Add(new ValidationResult("Shipping Address is not mainframe compliant. Mainframe does not support the specified country.  Please use Mainframe Override Address."));
                            }
                        }
                    }

                    if (ShippingProfile != null)
                    {
                        if (!string.IsNullOrWhiteSpace(ShippingProfile.VATCountryCode) && !LegacyMappings[0].LegacyIdentifier.StartsWith("Z"))
                        {
                            results.Add(new ValidationResult("VAT Country Code cannot be selected for this office.", new[] { "VATCountryCode" }));
                        }
                    }

                    return(results);
                }
                else
                {
                    if (TapeAddress != null)
                    {
                        results.Add(new ValidationResult("Tape Address cannot be provided without a subscriber code.", new[] { "Tape Address" }));
                    }
                }
                return(results);
            }
            finally
            {
                validator?.Dispose();
                repository?.Dispose();
            }
        }