Exemplo n.º 1
0
        public ValidationResultSet Validate()
        {
            var objProperties = Object.GetType().GetProperties();

            IsValid = objProperties.Any(p1 => p1.Name == "FirstName") &&
                      objProperties.Any(p2 => p2.Name == "LastName");

            if (IsValid)
            {
                string firstName = Object.GetType().GetProperty("FirstName")?.GetValue(Object) as string;
                string lastName  = Object.GetType().GetProperty("LastName")?.GetValue(Object) as string;

                IsValid = firstName == "Mark" && lastName == "Twain";
            }

            if (!IsValid)
            {
                _validations.Add(new ValidationItem(
                                     "You are not Mark Twain.",
                                     new [] { "FirstName", "LastName" },
                                     ValidationTypes.Error));

                return(new ValidationResultSet(Object, this));
            }

            return(ValidationResultSet.ValidResult(Object));
        }
Exemplo n.º 2
0
        public async Task <Confirmation> Record(InvolvedPartyCommand command)
        {
            // Load the existing occurrence for which the involved party should be recorded.
            var occurrence = await _occurenceRepo.ReadOccurrenceAsync(command.OccurrenceId);

            if (occurrence == null)
            {
                return(new Confirmation
                {
                    ResultMessage = "Invalid Occurrence"
                });
            }

            InvolvedParty involvedParty = CreateParty(command);

            ValidationResultSet valResultSet = _validation.Validate(involvedParty);

            if (valResultSet.IsInvalid)
            {
                return(new Confirmation
                {
                    Validations = valResultSet.ObjectValidations
                });
            }

            occurrence.AddInvolvedParty(involvedParty);

            // Update the occurrence within the repository.
            await _occurenceRepo.UpdateOccurrenceAsync(occurrence);

            return(new Confirmation
            {
                OccurrenceId = occurrence.OccurrenceId
            });
        }
Exemplo n.º 3
0
        public async Task <Confirmation> Record(OccurrenceCommand command)
        {
            var insured = Contact.IdentifiedAs(command.FirstName, command.LastName, command.DateOfBirth)
                          .PrimaryContactInfo(command.PhoneNumber)
                          .InsuredBy("Docker Insurance Company Inc.", command.PolicyNumber, command.InsuredState);

            var occurrence = Occurrence.ForInsured(insured, command.DateOfOccurrence);

            ValidationResultSet valResultSet = _validation.Validate(occurrence);

            if (valResultSet.IsInvalid)
            {
                return(new Confirmation
                {
                    Validations = valResultSet.ObjectValidations
                });
            }

            await _occurenceRepo.AddOccurrenceAsync(occurrence);

            // Publish domain event on message bus to notify other interested Microservices.
            var domainEvent = OccurrenceSubmittedEvent.FromOccurrence(occurrence);
            await _messaging.PublishAsync(domainEvent);

            return(new Confirmation
            {
                OccurrenceId = occurrence.OccurrenceId
            });
        }
 public SettingsValidationException(Type settingsType, string settingSection,
                                    ValidationResultSet validationResults)
     : base($"Type:{settingsType}; Section: {settingSection}; Results: {validationResults.ToIndentedJson()}")
 {
     SettingsType      = settingsType;
     SettingsSection   = settingSection;
     ValidationResults = validationResults;
 }
Exemplo n.º 5
0
        protected object BackgroundValidate(BackgroundWorker worker, DoWorkEventArgs e, params object[] args)
        {
            //Collect all documents to be validated. Some of these selected items
            //may be folders.
            var documents = new List <string>();
            var conn      = (IServerConnection)args[0];

            foreach (object a in args.Skip(1))
            {
                string rid = a.ToString();
                if (ResourceIdentifier.Validate(rid))
                {
                    var resId = new ResourceIdentifier(rid);
                    if (resId.IsFolder)
                    {
                        foreach (IRepositoryItem o in conn.ResourceService.GetRepositoryResources(rid).Children)
                        {
                            if (!o.IsFolder)
                            {
                                documents.Add(o.ResourceId);
                            }
                        }
                    }
                    else
                    {
                        documents.Add(rid);
                    }
                }
            }

            worker.ReportProgress(0);
            var context = new ResourceValidationContext(conn);

            var set = new ValidationResultSet();
            int i   = 0;

            foreach (string s in documents)
            {
                worker.ReportProgress((int)((i / (double)documents.Count) * 100), s);
                IResource item = null;
                try
                {
                    item = conn.ResourceService.GetResource(s);
                    set.AddIssues(ResourceValidatorSet.Validate(context, item, true));
                }
                catch (Exception ex)
                {
                    string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                    set.AddIssue(new ValidationIssue(item, ValidationStatus.Error, ValidationStatusCode.Error_General_ValidationError, string.Format("Failed to validate resource: {0}", msg)));
                }
                i++;
                worker.ReportProgress((int)((i / (double)documents.Count) * 100), s);
            }

            return(set.GetAllIssues());
        }
Exemplo n.º 6
0
        /// <summary>
        /// Performs any pre-save validation on the currently edited resource, by default
        /// this returns the results of a non-cascading <see cref="ResourceValidatorSet"/>
        /// validation run. Override this if you have a custom method of validation.
        /// </summary>
        protected virtual ICollection <ValidationIssue> ValidateEditedResource()
        {
            var conn    = _svc.CurrentConnection;
            var context = new ResourceValidationContext(conn);
            //Don't recurse as we only want to validate the current resource
            var issues = ResourceValidatorSet.Validate(context, this.Resource, false);
            var set    = new ValidationResultSet(issues);

            var errors = set.GetIssuesForResource(this.Resource.ResourceID, ValidationStatus.Error);

            return(errors);
        }
Exemplo n.º 7
0
        protected override ICollection <ValidationIssue> ValidateEditedResource()
        {
            string[] warnings;
            string[] errors;

            Func <ValidationIssue[]> validator = () =>
            {
                ValidateXml(out errors, out warnings);
                var issues = new List <ValidationIssue>();
                foreach (string err in errors)
                {
                    issues.Add(new ValidationIssue(this.Resource, ValidationStatus.Error, ValidationStatusCode.Error_General_ValidationError, err));
                }
                foreach (string warn in warnings)
                {
                    issues.Add(new ValidationIssue(this.Resource, ValidationStatus.Warning, ValidationStatusCode.Warning_General_ValidationWarning, warn));
                }

                //Put through ValidationResultSet to weed out redundant messages
                var set = new ValidationResultSet(issues);

                try
                {
                    var res     = ObjectFactory.DeserializeXml(editor.XmlContent);
                    var conn    = _edSvc.CurrentConnection;
                    var context = new ResourceValidationContext(conn);
                    //We don't care about dependents, we just want to validate *this* resource
                    var resIssues = ResourceValidatorSet.Validate(context, res, false);
                    set.AddIssues(resIssues);
                }
                catch
                {
                    //This can fail because the XML may be for something that Maestro does not offer a strongly-typed class for yet.
                    //So the XML may be legit, just not for this version of Maestro that is doing the validating
                }

                //Only care about errors. Warnings and other types should not derail us from saving
                return(set.GetAllIssues(ValidationStatus.Error));
            };

            if (this.InvokeRequired)
            {
                return((ValidationIssue[])this.Invoke(validator));
            }
            else
            {
                return(validator());
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Returns true if the tournament is ready to be started
 /// </summary>
 /// <param name="result">Result object with error messages</param>
 /// <returns></returns>
 public bool CanBeStarted(out ValidationResultSet result)
 {
     result = ValidationHelper.Validate(this);
     if (Status != TournamentStatus.Prestart)
     {
         result.Results.Add(new ValidationResult(Resources.Text.TournamentAlreadyStarted));
     }
     if (Contestants.Count == 0)
     {
         result.Results.Add(new ValidationResult(Resources.Text.TournamentTooFewContestants));
     }
     if (Judges.Count == 0)
     {
         result.Results.Add(new ValidationResult(Resources.Text.TournamentNoJudges));
     }
     result.IsValid = result.Results.Count == 0;
     return(result.IsValid);
 }
Exemplo n.º 9
0
        public async Task <AuthResult> AuthenticateForService(AuthenticateCaller authCommand)
        {
            // Validate the submitted credentials required from all providers:
            ValidationResultSet validationResults = _validationSrv.Validate(authCommand);

            if (validationResults.IsInvalid)
            {
                _logger.LogErrorDetails(
                    LogEvents.RequiredCredentialsError,
                    "Invalid submitted context and/or credentials", validationResults);

                return(AuthResult.Failed("Invalid authentication context and/or credentials."));
            }

            // Based on the service requesting the authentication token, lookup the associated provider.
            IAuthProvider provider = GetProvider(authCommand);

            if (provider == null)
            {
                return(AuthResult.Failed(
                           $"Requests from Api: {authCommand.Context.RequestingApi} can't be authenticated."));
            }

            // Delegate to the provider to determine if the submitted credentials are valid
            // for the service requesting the authentication token.
            if (!provider.IsValidAuthenticationRequest(authCommand.Context))
            {
                return(AuthResult.Failed("Invalid Authentication Request"));
            }

            // Since valid credential values have been received, delegate to the provider
            // to preform the authentication.
            AuthResult authResult = await provider.OnAuthenticateAsync(authCommand.Context);

            authResult = SetTokenForAuthenticationRequest(authResult, provider);

            _logger.LogTraceDetails(LogEvents.AuthResultDetermined,
                                    "Authentication results determined by provider.", authResult);

            return(authResult);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Returns true if the tournament is ready to be started
        /// </summary>
        public bool CanBeStarted()
        {
            var res = new ValidationResultSet();

            return(CanBeStarted(out res));
        }