コード例 #1
0
        private void Login()
        {
            UserValidationModel model = new UserValidationModel();

            model.LoginName = textBoxName.Text.TrimStart().TrimEnd();
            model.Password  = textBoxPassWord.Text;
            if (String.IsNullOrEmpty(model.LoginName) || String.IsNullOrEmpty(model.Password))
            {
                labelMessage.Text = "请录入登录信息";
            }
            else
            {
                HandlingResult   result = new HandlingResult();
                ValidationAction action = new ValidationAction();
                result = action.ValidateLogin(model);
                if (result.Successed)
                {
                    UserInformationModel user = (UserInformationModel)result.Result;
                    UserInformationContext.ID        = user.Id;
                    UserInformationContext.Name      = user.Name;
                    UserInformationContext.LoginName = user.LoginName;
                    UserInformationContext.LoginTime = DateTime.Now;
                    UserInformationContext.LoginPass = true;
                    UserInformationContext.StoreId   = "";
                    Close();
                }
                else
                {
                    labelMessage.Text = result.Message;
                }
            }
        }
コード例 #2
0
        public static ValidationContext CreateContext(
            Schema?schema                 = null,
            ValidationMode mode           = ValidationMode.Default,
            ValidationUpdater?updater     = null,
            ValidationAction action       = ValidationAction.Upsert,
            ResolvedComponents?components = null,
            DomainId?contentId            = null)
        {
            var context = new ValidationContext(
                TestUtils.DefaultSerializer,
                AppId,
                SchemaId,
                schema ?? new Schema(SchemaId.Name),
                components ?? ResolvedComponents.Empty,
                contentId ?? DomainId.NewGuid());

            context = context.WithMode(mode).WithAction(action);

            if (updater != null)
            {
                context = updater(context);
            }

            return(context);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: raindyi/BusinessReport
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new LoginForm());
            BasicConfigurator.Configure();
            ValidationAction action = new ValidationAction();

            if (action.ValidateLiceity().Successed)
            {
                LoginForm loginForm = new LoginForm();
                Application.Run(loginForm);
                if (UserInformationContext.LoginPass)
                {
                    Application.Run(new MainForm());
                }
                else
                {
                    Application.Exit();
                }
            }
            else
            {
                MessageBox.Show("软件未通过验证,请联系软件供应商");
                Application.Exit();
            }
        }
コード例 #4
0
 public ValidatorContainer(string errorHeader, ValidationAction action)
 {
     if (string.IsNullOrWhiteSpace(errorHeader) || action == null)
     {
         throw new InvalidOperationException("", new ArgumentNullException($"{nameof(errorHeader)} or {nameof(action)} is null"));
     }
     ErrorHeader = errorHeader;
     Action      = action;
 }
コード例 #5
0
ファイル: ValidationContext.cs プロジェクト: seamys/squidex
        public ValidationContext WithAction(ValidationAction action)
        {
            if (Action == action)
            {
                return(this);
            }

            return(Clone(clone => clone.Action = action));
        }
コード例 #6
0
        public static void ShowValidationIssue(int activePlayerId, ValidationAction validationAction, string floatText)
        {
            ValidationIssueDto validationIssueDto = new ValidationIssueDto();

            validationIssueDto.PlayerId         = activePlayerId;
            validationIssueDto.ValidationAction = validationAction;
            validationIssueDto.FloatText        = floatText;
            HubConnection.InvokeAsync("ShowValidationIssue", JsonConvert.SerializeObject(validationIssueDto));
        }
コード例 #7
0
        public override object Evaluate(List <string> args, ExpressionEvaluator evaluator, Creature player, Target target, CastedSpell spell, DiceStoppedRollingData dice = null)
        {
            ExpectingArguments(args, 3);
            string           dungeonMasterMessage = Expressions.GetStr(args[0], player, target, spell, dice);
            string           floatText            = Expressions.GetStr(args[1], player, target, spell, dice);
            ValidationAction validationAction     = Expressions.Get <ValidationAction>(args[2].Trim(), player, target, spell, dice);

            Validation.OnValidationFailed(dungeonMasterMessage, floatText, validationAction);
            return(null);
        }
コード例 #8
0
        public void AddValidator(FieldNameProvider nameProvider, string errorHeader, ValidationAction validationAction)
        {
            var fieldName = ValidateAndGetName(nameProvider);

            if (_fieldValidators.All((item) => item.FieldName != fieldName))
            {
                _fieldValidators.Add(new FieldValidator(fieldName));
            }
            _fieldValidators.FirstOrDefault((item) => item.FieldName == fieldName)?.AddValidator(errorHeader, validationAction);
        }
コード例 #9
0
        public static Task ValidateAsync(this IValidator validator, object?value, IList <string> errors,
                                         Schema?schema             = null,
                                         ValidationMode mode       = ValidationMode.Default,
                                         ValidationUpdater?updater = null,
                                         ValidationAction action   = ValidationAction.Upsert)
        {
            var context = CreateContext(schema, mode, updater, action);

            return(validator.ValidateAsync(value, context, CreateFormatter(errors)));
        }
コード例 #10
0
        public static ValueTask ValidateAsync(this IValidator validator, object?value, IList <string> errors,
                                              Schema?schema                 = null,
                                              ValidationMode mode           = ValidationMode.Default,
                                              ValidationUpdater?updater     = null,
                                              ValidationAction action       = ValidationAction.Upsert,
                                              ResolvedComponents?components = null,
                                              DomainId?contentId            = null)
        {
            var context = CreateContext(schema, mode, updater, action, components, contentId);

            return(validator.ValidateAsync(value, context, CreateFormatter(errors)));
        }
コード例 #11
0
        public static Task ValidateAsync(this IField field, object?value, IList <string> errors,
                                         Schema?schema              = null,
                                         ValidationMode mode        = ValidationMode.Default,
                                         ValidationUpdater?updater  = null,
                                         IValidatorsFactory?factory = null,
                                         ValidationAction action    = ValidationAction.Upsert)
        {
            var context = CreateContext(schema, mode, updater, action);

            var validator = new ValidatorBuilder(factory, context).ValueValidator(field);

            return(validator.ValidateAsync(value, context, CreateFormatter(errors)));
        }
コード例 #12
0
        public void AddValidator(string errorHeader, ValidationAction <T> validationAction)
        {
            if (errorHeader == null || validationAction == null)
            {
                throw new InvalidOperationException("Arguments is null",
                                                    new ArgumentNullException($"{nameof(errorHeader)} or {nameof(validationAction)} is null"));
            }
            if (Validators.ContainsKey(errorHeader))
            {
                return;
            }

            Validators.Add(errorHeader, validationAction);
        }
コード例 #13
0
        public static Task ValidateAsync(this IField field, object?value, IList <string> errors,
                                         Schema?schema              = null,
                                         ValidationMode mode        = ValidationMode.Default,
                                         ValidationUpdater?updater  = null,
                                         IValidatorsFactory?factory = null,
                                         ValidationAction action    = ValidationAction.Upsert)
        {
            var context = CreateContext(schema, mode, updater, action);

            var validators = Factories(factory).SelectMany(x => x.CreateValueValidators(context, field, null !)).ToArray();
            var validator  = new AggregateValidator(validators, Log);

            return(new FieldValidator(validator, field)
                   .ValidateAsync(value, context, CreateFormatter(errors)));
        }
コード例 #14
0
        public static async Task ValidateAsync(this ContentData data, PartitionResolver partitionResolver, IList <ValidationError> errors,
                                               Schema?schema              = null,
                                               ValidationMode mode        = ValidationMode.Default,
                                               ValidationUpdater?updater  = null,
                                               IValidatorsFactory?factory = null,
                                               ValidationAction action    = ValidationAction.Upsert)
        {
            var context = CreateContext(schema, mode, updater, action);

            var validator = new ContentValidator(partitionResolver, context, Factories(factory), Log);

            await validator.ValidateInputAsync(data);

            foreach (var error in validator.Errors)
            {
                errors.Add(error);
            }
        }
コード例 #15
0
        /// <summary>
        /// Constructs a new ValueNodeInputViewModel with the specified ValidationActions.
        /// The default values are carefully chosen and should probably not be changed unless you know what you are doing.
        /// </summary>
        /// <param name="connectionChangedValidationAction">The validation behaviour when the connection of this input changes.</param>
        /// <param name="connectedValueChangedValidationAction">The validation behaviour when the value of this input changes.</param>
        public ValueNodeInputViewModel(
            ValidationAction connectionChangedValidationAction     = ValidationAction.PushDefaultValue,
            ValidationAction connectedValueChangedValidationAction = ValidationAction.IgnoreValidation
            )
        {
            MaxConnections      = 1;
            ConnectionValidator = pending => new ConnectionValidationResult(pending.Output is ValueNodeOutputViewModel <T>, null);

            var connectedValues = GenerateConnectedValuesBinding(connectionChangedValidationAction, connectedValueChangedValidationAction);

            var localValues = this.WhenAnyValue(vm => vm.Editor)
                              .Select(e =>
            {
                if (e == null)
                {
                    return(Observable.Return(default(T)));
                }
                else if (!(e is ValueEditorViewModel <T>))
                {
                    throw new Exception($"The endpoint editor is not a subclass of ValueEditorViewModel<{typeof(T).Name}>");
                }
                else
                {
                    return(((ValueEditorViewModel <T>)e).ValueChanged);
                }
            })
                              .Switch();

            var valueChanged = Observable.CombineLatest(connectedValues, localValues,
                                                        (connectedValue, localValue) => Connections.Count == 0 ? localValue : connectedValue
                                                        )
                               .Multicast(new Subject <T>());

            valueChanged.Connect();
            valueChanged.ToProperty(this, vm => vm.Value, out _value);
            ValueChanged = Observable.Create <T>(observer =>
            {
                observer.OnNext(Value);
                observer.OnCompleted();
                return(Disposable.Empty);
            }).Concat(valueChanged);
        }
コード例 #16
0
        public static async Task ValidateAsync(this ContentData data, PartitionResolver partitionResolver, IList <ValidationError> errors,
                                               Schema?schema                 = null,
                                               ValidationMode mode           = ValidationMode.Default,
                                               ValidationUpdater?updater     = null,
                                               IValidatorsFactory?factory    = null,
                                               ValidationAction action       = ValidationAction.Upsert,
                                               ResolvedComponents?components = null,
                                               DomainId?contentId            = null)
        {
            var context = CreateContext(schema, mode, updater, action, components, contentId);

            var validator = new ValidatorBuilder(factory, context).ContentValidator(partitionResolver);

            await validator.ValidateInputAsync(data);

            foreach (var error in validator.Errors)
            {
                errors.Add(error);
            }
        }
コード例 #17
0
        public static ValidationContext CreateContext(
            Schema?schema             = null,
            ValidationMode mode       = ValidationMode.Default,
            ValidationUpdater?updater = null,
            ValidationAction action   = ValidationAction.Upsert)
        {
            var context = new ValidationContext(
                AppId,
                SchemaId,
                schema ?? new Schema(SchemaId.Name),
                DomainId.NewGuid());

            context = context.WithMode(mode).WithAction(action);

            if (updater != null)
            {
                context = updater(context);
            }

            return(context);
        }
コード例 #18
0
        private IObservable <T> GenerateConnectedValuesBinding(ValidationAction connectionChangedValidationAction, ValidationAction connectedValueChangedValidationAction)
        {
            var onConnectionChanged = this.Connections.Connect().Select(_ => Unit.Default).StartWith(Unit.Default)
                                      .Select(_ => Connections.Count == 0 ? null : Connections.Items.First());

            //On connection change
            IObservable <IObservable <T> > connectionObservables;

            if (connectionChangedValidationAction != ValidationAction.DontValidate)
            {
                //Either run network validation
                IObservable <NetworkValidationResult> postValidation = onConnectionChanged
                                                                       .SelectMany(con => Parent?.Parent?.UpdateValidation.Execute() ?? Observable.Return(new NetworkValidationResult(true, true, null)));

                if (connectionChangedValidationAction == ValidationAction.WaitForValid)
                {
                    //And wait until the validation is successful
                    postValidation = postValidation.SelectMany(validation =>
                                                               validation.NetworkIsTraversable
                            ? Observable.Return(validation)
                            : Parent.Parent.Validation.FirstAsync(val => val.NetworkIsTraversable));
                }

                if (connectionChangedValidationAction == ValidationAction.PushDefaultValue)
                {
                    //Or push a single default(T) if the validation fails
                    connectionObservables = postValidation.Select(validation =>
                    {
                        if (Connections.Count == 0)
                        {
                            return(Observable.Return(default(T)));
                        }
                        else if (validation.NetworkIsTraversable)
                        {
                            IObservable <T> connectedObservable =
                                ((ValueNodeOutputViewModel <T>)Connections.Items.First().Output).Value;
                            if (connectedObservable == null)
                            {
                                throw new Exception($"The value observable for output '{Connections.Items.First().Output.Name}' is null.");
                            }
                            return(connectedObservable);
                        }
                        else
                        {
                            return(Observable.Return(default(T)));
                        }
                    });
                }
                else
                {
                    //Grab the values observable from the connected output
                    connectionObservables = postValidation
                                            .Select(_ =>
                    {
                        if (Connections.Count == 0)
                        {
                            return(Observable.Return(default(T)));
                        }
                        else
                        {
                            IObservable <T> connectedObservable =
                                ((ValueNodeOutputViewModel <T>)Connections.Items.First().Output).Value;
                            if (connectedObservable == null)
                            {
                                throw new Exception($"The value observable for output '{Connections.Items.First().Output.Name}' is null.");
                            }
                            return(connectedObservable);
                        }
                    });
                }
            }
            else
            {
                //Or just grab the values observable from the connected output
                connectionObservables = onConnectionChanged.Select(con =>
                {
                    if (con == null)
                    {
                        return(Observable.Return(default(T)));
                    }
                    else
                    {
                        IObservable <T> connectedObservable =
                            ((ValueNodeOutputViewModel <T>)con.Output).Value;
                        if (connectedObservable == null)
                        {
                            throw new Exception($"The value observable for output '{Connections.Items.First().Output.Name}' is null.");
                        }
                        return(connectedObservable);
                    }
                });
            }
            IObservable <T> connectedValues = connectionObservables.SelectMany(c => c);

            //On connected output value change, either just push the value as is
            if (connectedValueChangedValidationAction != ValidationAction.DontValidate)
            {
                //Or run a network validation
                IObservable <NetworkValidationResult> postValidation = connectedValues.SelectMany(v =>
                                                                                                  Parent?.Parent?.UpdateValidation.Execute() ?? Observable.Return(new NetworkValidationResult(true, true, null)));
                if (connectedValueChangedValidationAction == ValidationAction.WaitForValid)
                {
                    //And wait until the validation is successful
                    postValidation = postValidation.SelectMany(validation =>
                                                               validation.IsValid
                            ? Observable.Return(validation)
                            : Parent.Parent.Validation.FirstAsync(val => val.IsValid));
                }

                connectedValues = postValidation.Select(validation =>
                {
                    if (Connections.Count == 0 ||
                        connectionChangedValidationAction == ValidationAction.PushDefaultValue && !validation.NetworkIsTraversable ||
                        connectedValueChangedValidationAction == ValidationAction.PushDefaultValue && !validation.IsValid)
                    {
                        //Push default(T) if the network isn't valid
                        return(default);
コード例 #19
0
        /// <summary>
        /// Enumerate all the descendants elements of this element and do validating.
        /// Preorder traversering.
        /// </summary>
        /// <param name="validationContext"></param>
        /// <param name="validateAction">The delegate method to do the validating.</param>
        /// <param name="finishAction">The delegate method to be called when the traverse finished.</param>
        /// <param name="getStopSignal">The delegate method which will fire stop signal.</param>
        internal static void ValidatingTraverse(ValidationContext validationContext, ValidationAction validateAction, ValidationAction finishAction, GetStopSignal getStopSignal)
        {
            Debug.Assert(validationContext != null);
            Debug.Assert(validationContext.McContext != null);
            Debug.Assert(validateAction != null);

            if (getStopSignal != null)
            {
                if (getStopSignal(validationContext))
                {
                    return;
                }
            }

            OpenXmlElement element = validationContext.Element;

            //specify whether ValidationAction is called
            bool validatingActed = false;

            // 1. Skip elements in ProcessContent.
            // 2. Select correct Choice / Fallback
            // Need bookkeep MC context
            // Need to collect MC context from ancestor

            // bookkeep MC context,
            // MC Spec: Compatibility-rule attributes shall affect the element to which they 1 are attached, including the element’s other attributes and contents.
            validationContext.McContext.PushMCAttributes2(element.MCAttributes, prefix => element.LookupNamespace(prefix));

            if (element.IsStrongTypedElement())
            {
                // only call validate on elements that defined in the format.
                if (element.IsInVersion(validationContext.FileFormat))
                {
                    validateAction(validationContext);
                    validatingActed = true;
                }
                else if (validationContext.McContext.IsProcessContent(element))
                {
                    // do not validate this element.
                }

                foreach (OpenXmlElement child in element.ChildElements)
                {
                    validationContext.Element = child;
                    ValidatingTraverse(validationContext, validateAction, finishAction, getStopSignal);
                }
            }
            else if (element.ElementTypeId == ReservedElementTypeIds.OpenXmlUnknownElementId ||
                     element.ElementTypeId == ReservedElementTypeIds.OpenXmlUnknownElementId)
            {
                // TODO: Issue: all types are weak types now, need to change the Framework to load strong typed elements!!!
                if (validationContext.McContext.IsProcessContent(element))
                {
                    // do validating on children elements.

                    foreach (OpenXmlElement child in element.ChildElements)
                    {
                        validationContext.Element = child;
                        ValidatingTraverse(validationContext, validateAction, finishAction, getStopSignal);
                    }
                }
            }
            else if (element.ElementTypeId == ReservedElementTypeIds.AlternateContentId)
            {
                validateAction(validationContext);
                validatingActed = true;

                OpenXmlCompositeElement selectedContent;

                selectedContent = validationContext.McContext.GetContentFromACBlock((AlternateContent)element, validationContext.FileFormat);

                if (selectedContent != null)
                {
                    foreach (var child in selectedContent.ChildElements)
                    {
                        validationContext.Element = child;
                        ValidatingTraverse(validationContext, validateAction, finishAction, getStopSignal);
                    }
                }
            }
            else if (element.ElementTypeId == ReservedElementTypeIds.OpenXmlMiscNodeId)
            {
                // non-element node
                // just skip
            }
            else
            {
                Debug.Assert(element is AlternateContentChoice || element is AlternateContentFallback);
                Debug.Assert(element.Parent != null && element.Parent is AlternateContent);

                // should not be here, otherwise, wrong case ( the parent is not AlternateContent).
            }

            validationContext.McContext.PopMCAttributes2();

            if (validatingActed && finishAction != null)
            {
                validationContext.Element = element;
                finishAction(validationContext);
            }
        }
コード例 #20
0
        /// <summary>
        /// Enumerate all the descendants elements of this element and do validating.
        /// Preorder traversering.
        /// </summary>
        /// <param name="validationContext"></param>
        /// <param name="validateAction">The delegate method to do the validating.</param>
        /// <param name="finishAction">The delegate method to be called when the traverse finished.</param>
        /// <param name="getStopSignal">The delegate method which will fire stop signal.</param>
        internal static void ValidatingTraverse(ValidationContext validationContext, ValidationAction validateAction, ValidationAction finishAction, GetStopSignal getStopSignal)
        {
            Debug.Assert(validationContext != null);
            Debug.Assert(validationContext.McContext != null);
            Debug.Assert(validateAction != null);

            if (getStopSignal != null)
            {
                if (getStopSignal(validationContext))
                {
                    return;
                }
            }

            OpenXmlElement element = validationContext.Element;

            //specify whether ValidationAction is called
            bool validatingActed = false;

            // 1. Skip elements in ProcessContent.
            // 2. Select correct Choice / Fallback
            // Need bookkeep MC context
            // Need to collect MC context from ancestor

            // bookkeep MC context, 
            // MC Spec: Compatibility-rule attributes shall affect the element to which they 1 are attached, including the element’s other attributes and contents.
            validationContext.McContext.PushMCAttributes2(element.MCAttributes, prefix => element.LookupNamespace(prefix));

            if (element.IsStrongTypedElement())
            {
                // only call validate on elements that defined in the format.
                if (element.IsInVersion(validationContext.FileFormat))
                {
                    validateAction(validationContext);
                    validatingActed = true;
                }
                else if (validationContext.McContext.IsProcessContent(element))
                {
                    // do not validate this element.
                }

             
                foreach (OpenXmlElement child in element.ChildElements)
                {
                    validationContext.Element = child;
                    ValidatingTraverse(validationContext, validateAction, finishAction, getStopSignal);
                }

            }
            else if (element.ElementTypeId == ReservedElementTypeIds.OpenXmlUnknownElementId ||
                  element.ElementTypeId == ReservedElementTypeIds.OpenXmlUnknownElementId)
            {
                // TODO: Issue: all types are weak types now, need to change the Framework to load strong typed elements!!!
                if (validationContext.McContext.IsProcessContent(element))
                {
                    // do validating on children elements.

                    foreach (OpenXmlElement child in element.ChildElements)
                    {
                        validationContext.Element = child;
                        ValidatingTraverse(validationContext, validateAction, finishAction, getStopSignal);
                    }
                }
            }
            else if (element.ElementTypeId == ReservedElementTypeIds.AlternateContentId)
            {

                validateAction(validationContext);
                validatingActed = true;

                OpenXmlCompositeElement selectedContent;

                selectedContent = validationContext.McContext.GetContentFromACBlock((AlternateContent)element, validationContext.FileFormat);

                if (selectedContent != null)
                {
                    foreach (var child in selectedContent.ChildElements)
                    {
                        validationContext.Element = child;
                        ValidatingTraverse(validationContext, validateAction, finishAction, getStopSignal);
                    }
                }
            }
            else if (element.ElementTypeId == ReservedElementTypeIds.OpenXmlMiscNodeId)
            {
                // non-element node
                // just skip
            }
            else
            {
                Debug.Assert(element is AlternateContentChoice || element is AlternateContentFallback);
                Debug.Assert(element.Parent != null && element.Parent is AlternateContent);

                // should not be here, otherwise, wrong case ( the parent is not AlternateContent).
            }

            validationContext.McContext.PopMCAttributes2();

            if (validatingActed && finishAction != null)
            {
                validationContext.Element = element;
                finishAction(validationContext);
            }
        }
 public UniqueValidationAttribute(ValidationAction action)
 {
     this.action  = action;
     ErrorMessage = "La valeur existe déjà...";
 }
コード例 #22
0
        public static T GetProperty <T>(this JObject jo, string propName, T defaultValue = default(T),
                                        ValidationIndicators exclusions              = ValidationIndicators.Null | ValidationIndicators.Empty,
                                        ValidationAction exclusionValidationAction   = ValidationAction.ReturnDefault,
                                        ValidationIndicators requirements            = ValidationIndicators.None,
                                        ValidationAction requirementValidationAction = ValidationAction.ReturnDefault
                                        )
        {
            var msg = string.Empty;

            if (jo == null || string.IsNullOrEmpty(propName))
            {
                switch (exclusionValidationAction)
                {
                case ValidationAction.ReturnDefault:
                    return(defaultValue);

                case ValidationAction.Throw:
                    throw new ArgumentNullException(nameof(jo));
                }
            }

            var rx = new Regex($"^{propName}$");
            var p  = jo.Properties().FirstOrDefault(w => rx.IsMatch(w.Name))?.Name;

            if (p == null && exclusions.HasFlag(ValidationIndicators.Null))
            {
                msg = $"No properties matching {rx}";
                Console.Write(msg);
                switch (exclusionValidationAction)
                {
                case ValidationAction.ReturnDefault:
                    return(defaultValue);

                case ValidationAction.Throw:
                    throw new Exception(msg);
                }
            }

            if (jo[p].Type == JTokenType.Null && exclusions.HasFlag(ValidationIndicators.Null))
            {
                msg = $"Property {p} does not exist on that object";
                Console.WriteLine(msg);
                switch (exclusionValidationAction)
                {
                case ValidationAction.ReturnDefault:
                    return(defaultValue);

                case ValidationAction.Throw:
                    throw new Exception(msg);
                }
            }

            if (jo[p].Type == JTokenType.Array || jo[p].Type == JTokenType.Object)
            {
                if (typeof(JObject) == typeof(T) || typeof(JArray) == typeof(T))
                {
                    return(jo[p].Value <T>());
                }

                return(defaultValue);
            }

            var val      = jo[p].Value <string>();
            var valFlags = val.GetValidationIndicators();

            if (valFlags.HasFlag(ValidationIndicators.Empty))
            {
                if (exclusions.HasFlag(ValidationIndicators.Empty))
                {
                    msg = $"Property {p} was empty but expected value";
                    Console.WriteLine(msg);
                    switch (exclusionValidationAction)
                    {
                    case ValidationAction.ReturnDefault:
                        return(defaultValue);

                    case ValidationAction.Throw:
                        throw new Exception(msg);
                    }
                }
                else
                {
                    return(jo[p].Value <T>());
                }
            }

            if (valFlags.HasFlag(ValidationIndicators.Null) && exclusions.HasFlag(ValidationIndicators.Null))
            {
                msg = $"Property {p} was null but expected value";
                Console.WriteLine(msg);

                switch (exclusionValidationAction)
                {
                case ValidationAction.ReturnDefault:
                    return(defaultValue);

                case ValidationAction.Throw:
                    throw new Exception(msg);
                }
            }

            if (valFlags.HasFlag(ValidationIndicators.Zero) && exclusions.HasFlag(ValidationIndicators.Zero))
            {
                msg = "Property {p} was 0 but expected value";
                Console.WriteLine(msg);

                switch (exclusionValidationAction)
                {
                case ValidationAction.ReturnDefault:
                    return(defaultValue);

                case ValidationAction.Throw:
                    throw new Exception(msg);
                }
            }

            if (valFlags.HasFlag(ValidationIndicators.Negative) && exclusions.HasFlag(ValidationIndicators.Negative))
            {
                msg = $"Property {p} was negative but expected positive integer";
                Console.WriteLine(msg);
                switch (exclusionValidationAction)
                {
                case ValidationAction.ReturnDefault:
                    return(defaultValue);

                case ValidationAction.Throw:
                    throw new Exception(msg);
                }
            }

            if (!valFlags.HasFlag(ValidationIndicators.Number) && requirements.HasFlag(ValidationIndicators.Number))
            {
                msg = $"Property {p} was not a number but expected one";
                Console.WriteLine(msg);
                switch (requirementValidationAction)
                {
                case ValidationAction.ReturnDefault:
                    return(defaultValue);

                case ValidationAction.Throw:
                    throw new Exception(msg);
                }
            }
            return(jo[p].Value <T>());
        }
コード例 #23
0
ファイル: Validation.cs プロジェクト: surlydev/MrAnnouncerBot
        public static void OnValidationFailed(string dungeonMasterMessage, string floatText, ValidationAction validationAction)
        {
            ValidationEventArgs ea = new ValidationEventArgs(dungeonMasterMessage, floatText, validationAction);

            ValidationFailing?.Invoke(null, ea);
            if (ea.OverrideWarning)
            {
                return;
            }

            ValidationFailed?.Invoke(null, ea);
        }
コード例 #24
0
    /// <summary>
    /// Open a previously exported robot.
    /// </summary>
    /// <param name="validate">If it is not null, this will validate the open inventor assembly.</param>
    public bool OpenExisting(ValidationAction validate, bool warnUnsaved = false)
    {
        if (SkeletonBase != null && warnUnsaved && !WarnUnsaved())
        {
            return(false);
        }

        string dirPath = OpenFolderPath();

        if (dirPath == null)
        {
            return(false);
        }

        try
        {
            List <RigidNode_Base> nodes = new List <RigidNode_Base>();
            SkeletonBase = BXDJSkeleton.ReadSkeleton(dirPath + "\\skeleton.bxdj");

            if (validate != null)
            {
                if (!validate(SkeletonBase, out string message))
                {
                    while (true)
                    {
                        DialogResult result = MessageBox.Show(message, "Assembly Validation", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                        if (result == DialogResult.Retry)
                        {
                            continue;
                        }
                        if (result == DialogResult.Abort)
                        {
                            return(false);
                        }
                        break;
                    }
                }
                #region DEBUG
#if DEBUG
                else
                {
                    MessageBox.Show(message);
                }
#endif
                #endregion
            }

            SkeletonBase.ListAllNodes(nodes);

            Meshes = new List <BXDAMesh>();

            foreach (RigidNode_Base n in nodes)
            {
                BXDAMesh mesh = new BXDAMesh();
                mesh.ReadFromFile(dirPath + "\\" + n.ModelFileName);

                if (!n.GUID.Equals(mesh.GUID))
                {
                    MessageBox.Show(n.ModelFileName + " has been modified.", "Could not load mesh.");
                    return(false);
                }

                Meshes.Add(mesh);
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }

        RMeta.UseSettingsDir  = false;
        RMeta.ActiveDir       = dirPath;
        RMeta.ActiveRobotName = dirPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Last();

        ReloadPanels();
        return(true);
    }
コード例 #25
0
 public ValidationEventArgs(string dungeonMasterMessage, string floatText, ValidationAction validationAction)
 {
     FloatText            = floatText;
     ValidationAction     = validationAction;
     DungeonMasterMessage = dungeonMasterMessage;
 }