protected override void PerformValidation( Action <string> addValidationErrorAction, ValidatorType type, IViewModel owner, IViewModel targetVM, object validatorKey, IVMPropertyDescriptor targetProperty = null ) { bool validate = false; switch (type) { case ValidatorType.Property: if ((EnabledValidators & ValidatorTypes.Property) == ValidatorTypes.Property) { validate = true; } break; case ValidatorType.ViewModel: if ((EnabledValidators & ValidatorTypes.ViewModel) == ValidatorTypes.ViewModel) { validate = true; } break; } if (validate) { base.PerformValidation(addValidationErrorAction, type, owner, targetVM, validatorKey, targetProperty); } }
public static IValidator GetByType(ValidatorType type) { IValidator validator; switch (type) { case ValidatorType.EMPTY: validator = new ValidatorEmpty(); break; case ValidatorType.MONTH: validator = new ValidatorMonth(); break; case ValidatorType.YEAR: validator = new ValidatorYear(); break; case ValidatorType.CVV: validator = new ValidatorCvv(); break; case ValidatorType.CREDIT_CARD: validator = new ValidatorCreditCard(); break; default: validator = new ValidatorEmpty(); break; } return(validator); }
private void ValidatorTypeChanged() { Validator = (IValidator)ServiceProvider.GetService(ValidatorType); foreach (var info in ValidatorType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)) { if (info.FieldType.GetInterface(nameof(IEntity)) != null) { var service = info.GetValue(Validator); if (service == null) { service = ServiceProvider.GetService(info.FieldType); info.SetValue(Validator, service); } (service as IEntity).Context = Context; } } if (Validator as IEntity != null) { (Validator as IEntity).Context = Context; } if (Validator as ICaspianValidator != null) { (Validator as ICaspianValidator).Provider = ServiceProvider; } //Validator.Validate(EditContext.Model); }
public MessageItem(ErrorType ErrorType, ValidatorType ValidatorType, string Message) { this.ErrorType = ErrorType; this.ValidatorType = ValidatorType; this.Message = Message; Fields = new List<string>(); }
public AutoCorrectEventArgs(IRowStream source, ValidatorType validType, string fieldName, string oldValue, string newValue) { FieldName = fieldName; OldValue = oldValue; NewValue = newValue; Row = source; ValidatorType = validType; }
public TextBoxValidatorItem(TextBox _textBox, TextBlock _label, ValidatorType _type) { this.textBox = _textBox; this.label = _label; StartForeground = _label.Foreground; this.textBox.TextChanged += new TextChangedEventHandler(textBox_TextChanged); this.type = _type; }
public void RegisterComboBox(ComboBox cb, ValidatorType type) { ComboBoxValidatorItem item = new ComboBoxValidatorItem(cb, type); item.SelectionChanged += new SelectionChangedEventHandler(item_SelectionChange); this.itemscombobox.Add(item); item.CheckValid(); SetEnableButtons(); }
private static void Validation(IContainer container, string url, ValidatorType validatorType, string doctype) { var validator = container.Resolve<IValidator>(); validator.Url = url; validator.DocumentType = doctype; validator.ValidatorType = validatorType; validator.Validate(); }
public void TestConstraintNullIn() { var self = new ValidatorType(null); var spy = Substitute.For<Func<Type, IValidator>>(); var result = FluentConstraintsSteps.CreateValidator(self, spy); result.ShouldBe(null); spy.DidNotReceive().Invoke(Arg.Any<Type>()); }
public ErrorCapturedEventArgs(IRowStream source, ValidatorType validType, ErrorType errorType, string fieldName, string description) { FieldName = fieldName; ErrorType = errorType; Description = description; Row = source; ValidatorType = validType; }
public ValidatorInvocationBuilder( ValidatorType validatorType, Action <ValidatorInvocation> additionAction ) { _additionAction = additionAction; _validatorType = validatorType; }
public void RegisterTextBox(TextBox tb, TextBlock label, ValidatorType type) { TextBoxValidatorItem item = new TextBoxValidatorItem(tb, label, type); item.TextChange += new TextChangedEventHandler(item_TextChange); this.items.Add(item); item.CheckValid(); SetEnableButtons(); }
/// <summary> /// Internal helper to determine whether <see cref="Method" /> is legal for use. /// </summary> /// <returns><c>null</c> or the appropriate error message.</returns> private string ValidateMethodParameter() { if (string.IsNullOrEmpty(Method)) { return(SR.CustomValidationAttribute_Method_Required); } // Named method must be public and static var methodInfo = ValidatorType.GetRuntimeMethods() .SingleOrDefault(m => string.Equals(m.Name, Method, StringComparison.Ordinal) && m.IsPublic && m.IsStatic); if (methodInfo == null) { return(string.Format(CultureInfo.CurrentCulture, SR.CustomValidationAttribute_Method_Not_Found, Method, ValidatorType.Name)); } // Method must return a ValidationResult if (methodInfo.ReturnType != typeof(ValidationResult)) { return(string.Format(CultureInfo.CurrentCulture, SR.CustomValidationAttribute_Method_Must_Return_ValidationResult, Method, ValidatorType.Name)); } ParameterInfo[] parameterInfos = methodInfo.GetParameters(); // Must declare at least one input parameter for the value and it cannot be ByRef if (parameterInfos.Length == 0 || parameterInfos[0].ParameterType.IsByRef) { return(string.Format(CultureInfo.CurrentCulture, SR.CustomValidationAttribute_Method_Signature, Method, ValidatorType.Name)); } // We accept 2 forms: // 1-parameter form is ValidationResult Method(object value) // 2-parameter form is ValidationResult Method(object value, ValidationContext context), _isSingleArgumentMethod = (parameterInfos.Length == 1); if (!_isSingleArgumentMethod) { if ((parameterInfos.Length != 2) || (parameterInfos[1].ParameterType != typeof(ValidationContext))) { return(string.Format(CultureInfo.CurrentCulture, SR.CustomValidationAttribute_Method_Signature, Method, ValidatorType.Name)); } } _methodInfo = methodInfo; _firstParameterType = parameterInfos[0].ParameterType; return(null); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var param = new List <object> { value }; if (!string.IsNullOrWhiteSpace(ArgProperty)) { param.Add(ArgProperty == "this" ? validationContext.ObjectInstance : validationContext.ObjectInstance.GetType().GetProperty(ArgProperty)?.GetValue(validationContext.ObjectInstance)); } return((ValidationResult)ValidatorType.GetMethod(Method)?.Invoke(null, param.ToArray())); }
public BaseValidate Add(ValidatorType type, string value, string msg) { if (type == ValidatorType.Required) { return(this.AddRequired(value, msg)); } else { //正则表达式验证。。。。 } return(this); }
/// <summary> /// Запускает пользовательскую валидацию /// </summary> /// <param name="objectToValidate">объект для проверки</param> /// <param name="currentTarget">объект, на котором производится валидация</param> /// <param name="key">ключ, который идентифицирует источник <paramref name="objectToValidate"/></param> /// <param name="validationResults">результаты валидации</param> public override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults validationResults) { bool isValid; var messageTemplate = MessageTemplate; // Получаем информацию о методе и его параметрах var tempMethodInfo = ValidatorType.GetMethod(Method); var tempParametersInfo = tempMethodInfo.GetParameters(); // Заполняем массив типов параметров var parameterTypes = new Type[3]; parameterTypes[0] = tempParametersInfo[0].ParameterType; parameterTypes[1] = tempParametersInfo[1].ParameterType; parameterTypes[2] = Type.GetType("System.String&"); // Получаем информацию о методе var methodInfo = ValidatorType.GetMethod(Method, parameterTypes); // Заполняем массив фактических значений параметров var parameters = new object[3]; parameters[0] = Converter.ChangeType(objectToValidate, parameterTypes[0]); parameters[1] = Converter.ChangeType(currentTarget, parameterTypes[1]); parameters[2] = null; // Вызываем метод и получаем результат проверки if (methodInfo.IsStatic) { isValid = (bool)methodInfo.Invoke(ValidatorType, parameters); } else { // Создаем экземпляр объекта var validatorObject = Activator.CreateInstance(ValidatorType); isValid = (bool)methodInfo.Invoke(validatorObject, parameters); } if (isValid == Negated) { MessageTemplate = !string.IsNullOrWhiteSpace(parameters[2]?.ToString()) ? parameters[2].ToString() : messageTemplate; LogValidationResult( validationResults, string.Format(CultureInfo.CurrentCulture, MessageTemplate, objectToValidate, key, Tag, ValidatorType, Method), currentTarget, key ); } }
internal Validator(string t, string parentName) { if (!string.IsNullOrEmpty(t)) { t = t.First().ToString().ToUpper() + t.Substring(1); this._type = (ValidatorType)Enum.Parse(typeof(ValidatorType), t); } else { this._type = ValidatorType.None; } this._parentName = parentName; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { object arg = null; if (ArgProperty == "this") { arg = validationContext.ObjectInstance; } else { arg = validationContext.ObjectInstance.GetType().GetProperty(ArgProperty)?.GetValue(validationContext.ObjectInstance); } return((ValidationResult)ValidatorType.GetMethod(Method)?.Invoke(null, new object[] { value, arg })); }
/// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { unchecked { int result = 17; result = result * 23 + ValidatorType.GetHashCode(); result = result * 23 + ((Condition != null) ? Condition.GetHashCode() : 0); result = result * 23 + ((Message != null) ? Message.GetHashCode() : 0); result = result * 23 + ((Label != null) ? Label.GetHashCode() : 0); result = result * 23 + ((Value != null) ? Value.GetHashCode() : 0); result = result * 23 + ((Min != null) ? Min.GetHashCode() : 0); result = result * 23 + ((Max != null) ? Max.GetHashCode() : 0); return(result); } }
public ValidatorInvocation( ValidatorType type, IViewModel owner, IViewModel targetVM, IVMCollection targetCollection, IVMPropertyDescriptor targetProperty, object validatorKey = null ) { Type = type; Owner = owner; TargetVM = targetVM; TargetProperty = targetProperty; TargetCollection = targetCollection; ValidatorKey = validatorKey; }
public void IVerifyAWarningForLiveValidators(ValidatorType validator, string attribute, ValidatorActionType validatorType) { var factory = new EntityFactory(_entityName); var entity = factory.Construct(); var invalidAttribute = entity.GetInvalidAttribute(attribute, validator.ToString().ToLower().Capitalize()); var createPageDetailsSection = EntityDetailUtils.GetEntityDetailsSection(_entityName, _contextConfiguration); createPageDetailsSection.SetInputElement(attribute, invalidAttribute); switch (validatorType) { case ValidatorActionType.ON_SUBMIT: _createPage.SubmitButton.Click(); break; case ValidatorActionType.LIVE: createPageDetailsSection.GetInputElement(attribute).SendKeys(Keys.Tab); break; } var errors = createPageDetailsSection.GetErrorMessagesForAttribute(attribute); switch (validator) { case ValidatorType.LENGTH: //(int min, int max) attributeLengthMinMax = entity.GetLengthValidatorMinMax(attribute); //Assert.Contains($"The length of this field is not less than {attributeLengthMinMax.max}. Actual Length: {attributeLengthMinMax.max + 1}", errors); (_, int max) = entity.GetLengthValidatorMinMax(attribute); Assert.Contains($"The length of this field is not less than {max}. Actual Length: {max + 1}", errors); break; case ValidatorType.EMAIL: Assert.Contains($"The value is not a valid email", errors); break; case ValidatorType.NUMERIC: Assert.Contains("You can only use numbers in this field", errors); break; case ValidatorType.REQUIRED: Assert.Contains("This field is required", errors); break; default: throw new Exception($"{validator} is not a valid validator"); } }
public ValidatorDefinition( string dataType, ValidatorType validatorType, string rulesetOrExecutable) { Id = $"{dataType}_{Guid.NewGuid()}"; DataType = dataType; ValidatorType = validatorType; if (validatorType == ValidatorType.JsonRuleset || validatorType == ValidatorType.TextRules) { Ruleset = rulesetOrExecutable; } else { ExecutableBase64 = rulesetOrExecutable; } }
private string BuildUrl(ValidatorType ValidatorType) { var appSettingName = string.Format("{0}Validator", ValidatorType); var url = string.Empty; switch (ValidatorType) { case ValidatorType.XHTML: url = string.Format(_configManager.GetAppSetting(appSettingName), DocType.GetDocType(DocumentType), Url); break; case ValidatorType.CSS: url = string.Format(_configManager.GetAppSetting(appSettingName), Url); break; } return url; }
private ValidatorDefinition(string id, string dataType, string submitter, string submitterEmail, ValidatorType validatorType, string executableBase64, string ruleset, bool isApproved) { Id = id; DataType = dataType; Submitter = submitter; SubmitterEmail = submitterEmail; ValidatorType = validatorType; ExecutableBase64 = executableBase64; Ruleset = ruleset; IsApproved = isApproved; }
public BigInteger GetValidatorCount(ValidatorType type) { if (type == ValidatorType.Invalid) { return(0); } var max = GetMaxPrimaryValidators(); var count = 0; for (int i = 0; i < max; i++) { var validator = GetValidatorByIndex(i); if (validator.type == type) { count++; } } return(count); }
protected virtual void PerformValidation( Action <string> addValidationErrorAction, ValidatorType type, IViewModel owner, IViewModel targetVM, object validatorKey, IVMPropertyDescriptor targetProperty = null ) { var invocation = new ValidatorInvocation(type, owner, targetVM, null, targetProperty, validatorKey); var errors = ValidatorSetups .Where(x => x.Invocation.Equals(invocation)) .SelectMany(x => x.Result.Errors); errors.ForEach(x => addValidationErrorAction(x.Message)); ActualInvocations.Add( new ValidatorInvocation(type, owner, targetVM, null, targetProperty, validatorKey) ); }
// TextChanged events private void TextBoxChanged(ColorSpaceEnum space, ValidatorType validatorType, TextBox textBox) { // Supress declining partial typing if (textBox.Text.Length > 0 && (textBox.Text[0] == ',' || (textBox.Text[textBox.Text.Length - 1] == ','))) { return; } if (_validators[validatorType].Validate(textBox.Text)) { if (!_changeInProgress) { ChangeColor(space); textBox.ClearUndo(); } } else { RestoreValues(space); InfoLabel.Text = _validationErrors[space]; } }
/// <summary> /// 注册新的校验控件 /// </summary> /// <param name="errorMsg">校验不通过时的出错提示</param> /// <param name="valType">校验类型</param> /// <returns></returns> public BaseValidator NewValidator(string errorMsg, ValidatorType valType) { BaseValidator validator = null; switch (valType) { case ValidatorType.RequiredFieldValidator: validator = new RequiredFieldValidator(); validator.EnableClientScript = false; break; case ValidatorType.RangeValidator: validator = new RangeValidator(); (validator as RangeValidator).Type = ValidationDataType.Integer; validator.EnableClientScript = false; break; case ValidatorType.RegularExpressionValidator: validator = new RegularExpressionValidator(); validator.EnableClientScript = false; break; case ValidatorType.CompareValidator: validator = new CompareValidator(); validator.EnableClientScript = false; break; case ValidatorType.CustomValidator: validator = new CustomValidator(); validator.EnableClientScript = false; break; } validator.ErrorMessage = errorMsg; // 不显示校验控件。 validator.Display = ValidatorDisplay.None; return(validator); }
protected virtual void PerformCollectionValidation <TItemVM>( Action <TItemVM, string, object> addValidationErrorAction, ValidatorType type, IViewModel owner, IVMCollectionBase <TItemVM> targetCollection, object validatorKey, IVMPropertyDescriptor targetProperty = null ) where TItemVM : IViewModel { foreach (TItemVM item in targetCollection) { var invocation = new ValidatorInvocation(type, owner, item, null, targetProperty, validatorKey); var errors = ValidatorSetups .Where(x => x.Invocation.Equals(invocation)) .SelectMany(x => x.Result.Errors); errors.ForEach(x => addValidationErrorAction(item, x.Message, x.Details)); } ActualInvocations.Add( new ValidatorInvocation(type, owner, null, targetCollection, targetProperty, validatorKey) ); }
public RegexValidator(string name, ValidatorType type, FilterAction action, string pattern) : base(name, type, action) { this._regex = new Regex(pattern); }
private void AddNewValidator(PhantasmaKeys newValidator) { Timestamp startTime = simulator.CurrentTime; Timestamp endTime = simulator.CurrentTime.AddDays(1); var pollName = SystemPoll + ValidatorPollTag; var validators = (ValidatorEntry[])simulator.Nexus.RootChain.InvokeContract(simulator.Nexus.RootStorage, Nexus.ValidatorContractName, nameof(ValidatorContract.GetValidators)).ToObject(typeof(ValidatorEntry[])); var activeValidators = validators.Where(x => x.address != Address.Null); var activeValidatorCount = activeValidators.Count(); var choices = new PollChoice[activeValidatorCount + 1]; for (int i = 0; i < activeValidatorCount; i++) { choices[i] = new PollChoice() { value = validators[i].address.ToByteArray() }; } choices[activeValidatorCount] = new PollChoice() { value = newValidator.Address.ToByteArray() }; var serializedChoices = choices.Serialize(); //start vote for new validator simulator.BeginBlock(); simulator.GenerateCustomTransaction(owner, ProofOfWork.None, () => ScriptUtils.BeginScript(). AllowGas(owner.Address, Address.Null, 1, 9999). CallContract(ConsensusContractName, nameof(ConsensusContract.InitPoll), owner.Address, pollName, DomainSettings.ValidatorsOrganizationName, ConsensusMode.Majority, startTime, endTime, serializedChoices, 1). SpendGas(owner.Address). EndScript()); simulator.EndBlock(); for (int i = 0; i < activeValidatorCount; i++) { var validator = validatorKeyPairs[i]; //have each already existing validator vote on themselves to preserve the validator order simulator.BeginBlock(); simulator.GenerateCustomTransaction(validator, ProofOfWork.None, () => ScriptUtils.BeginScript(). AllowGas(validator.Address, Address.Null, 1, 9999). CallContract(ConsensusContractName, nameof(ConsensusContract.SingleVote), validator.Address, pollName, i). SpendGas(validator.Address). EndScript()); simulator.EndBlock(); } //skip until the voting is over simulator.TimeSkipDays(1.5); var votingRank = simulator.Nexus.RootChain.InvokeContract(simulator.Nexus.RootStorage, ConsensusContractName, nameof(ConsensusContract.GetRank), pollName, choices[activeValidatorCount].Serialize()).AsNumber(); //call SetValidator for each set validator address for (int i = 0; i <= activeValidatorCount; i++) { var validatorChoice = choices[i].value; ValidatorType validatorType = i < 2 ? Primary : Secondary; votingRank = simulator.Nexus.RootChain.InvokeContract(simulator.Nexus.RootStorage, ConsensusContractName, nameof(ConsensusContract.GetRank), pollName, validatorChoice).AsNumber(); simulator.BeginBlock(); var tx = simulator.GenerateCustomTransaction(owner, ProofOfWork.None, () => ScriptUtils.BeginScript(). AllowGas(owner.Address, Address.Null, 1, 9999). CallContract(ValidatorContractName, nameof(ValidatorContract.SetValidator), validatorChoice, votingRank, validatorType). SpendGas(owner.Address). EndScript()); simulator.EndBlock().First(); } }
public MessageItem(ErrorType ErrorType, ValidatorType ValidatorType, string Message, params string[] RelatedFields) : this(ErrorType, ValidatorType, Message) { this.Fields.AddRange(RelatedFields); }
public MessageItem(ErrorType ErrorType, ValidatorType ValidatorType, string Message, IEnumerable<string> RelatedFields) : this(ErrorType, ValidatorType, Message) { this.Fields.AddRange(RelatedFields); }
private static void CreateAndUpdateErrors(string errorMessage, string validatorName, List <VerifyError> errors, ValidatorType type = ValidatorType.BuildIn) { var error = new VerifyError { ErrorMessage = errorMessage, ValidatorName = validatorName, ViaValidatorType = type }; errors.Add(error); }
public static IValidator CreateValidator( ValidatorType self, Func<Type, IValidator> createValidator) { return self?.Type == null ? null : createValidator(self.Type); }
protected override void PerformCollectionValidation <TItemVM>(Action <TItemVM, string, object> addValidationErrorAction, ValidatorType type, IViewModel owner, IVMCollectionBase <TItemVM> targetCollection, object validatorKey, IVMPropertyDescriptor targetProperty = null) { bool validate = false; switch (type) { case ValidatorType.CollectionProperty: if ((EnabledValidators & ValidatorTypes.Property) == ValidatorTypes.Property) { validate = true; } break; case ValidatorType.CollectionViewModel: if ((EnabledValidators & ValidatorTypes.ViewModel) == ValidatorTypes.ViewModel) { validate = true; } break; } if (validate) { base.PerformCollectionValidation <TItemVM>(addValidationErrorAction, type, owner, targetCollection, validatorKey, targetProperty); } }
public static IValidator GetByType(ValidatorType type) { IValidator validator; switch (type) { case ValidatorType.EMPTY: validator = new ValidatorEmpty(); break; case ValidatorType.MONTH: validator = new ValidatorMonth(); break; case ValidatorType.YEAR: validator = new ValidatorYear(); break; case ValidatorType.CVV: validator = new ValidatorCvv(); break; case ValidatorType.CREDIT_CARD: validator = new ValidatorCreditCard(); break; default: validator = new ValidatorEmpty(); break; } return validator; }
public ResultValidator(string text, ValidatorType type, bool caseSensitive) { SearchText = text; Type = type; CaseSensitive = caseSensitive; }
public bool CanProcessValidation(ValidatorType validatorType) { return(ValidatorType == validatorType); }
public TextBoxValidatorItem(TextBox _textBox, ValidatorType _type) { this.textBox = _textBox; this.textBox.TextChanged += new TextChangedEventHandler(textBox_TextChanged); this.type = _type; }
// NOTE - witness not required, as anyone should be able to call this, permission is granted based on consensus public void SetValidator(Address target, BigInteger index, ValidatorType type) { Runtime.Expect(target.IsUser, "must be user address"); Runtime.Expect(type == ValidatorType.Primary || type == ValidatorType.Secondary, "invalid validator type"); var primaryValidators = GetValidatorCount(ValidatorType.Primary); var secondaryValidators = GetValidatorCount(ValidatorType.Secondary); Runtime.Expect(index >= 0, "invalid index"); var totalValidators = GetMaxTotalValidators(); Runtime.Expect(index < totalValidators, "invalid index"); var expectedType = index < GetMaxPrimaryValidators() ? ValidatorType.Primary : ValidatorType.Secondary; Runtime.Expect(type == expectedType, "unexpected validator type"); var requiredStake = Runtime.CallContext(NativeContractKind.Stake, nameof(StakeContract.GetMasterThreshold), target).AsNumber(); var stakedAmount = Runtime.GetStake(target); Runtime.Expect(stakedAmount >= requiredStake, "not enough stake"); if (index > 0) { var isPreviousSet = _validators.ContainsKey <BigInteger>(index - 1); Runtime.Expect(isPreviousSet, "previous validator slot is not set"); var previousEntry = _validators.Get <BigInteger, ValidatorEntry>(index - 1); Runtime.Expect(previousEntry.type != ValidatorType.Invalid, " previous validator has unexpected status"); } if (primaryValidators > 0) { var isValidatorProposed = _validators.ContainsKey <BigInteger>(index); if (isValidatorProposed) { var currentEntry = _validators.Get <BigInteger, ValidatorEntry>(index); if (currentEntry.type != ValidatorType.Proposed) { Runtime.Expect(currentEntry.type == ValidatorType.Invalid, "invalid validator state"); isValidatorProposed = false; } } if (isValidatorProposed) { Runtime.Expect(Runtime.IsWitness(target), "invalid witness"); } else { if (primaryValidators > 1) { var pollName = ConsensusContract.SystemPoll + ValidatorPollTag; var obtainedRank = Runtime.CallContext("consensus", "GetRank", pollName, target).AsNumber(); Runtime.Expect(obtainedRank >= 0, "no consensus for electing this address"); Runtime.Expect(obtainedRank == index, "this address was elected at a different index"); } else { var firstValidator = GetValidatorByIndex(0).address; Runtime.Expect(Runtime.IsWitness(firstValidator), "invalid witness"); } type = ValidatorType.Proposed; } } else { Runtime.Expect(Runtime.IsWitness(Runtime.GenesisAddress), "invalid witness"); } var entry = new ValidatorEntry() { address = target, election = Runtime.Time, type = type, }; _validators.Set <BigInteger, ValidatorEntry>(index, entry); if (type == ValidatorType.Primary) { var newValidators = GetValidatorCount(ValidatorType.Primary); Runtime.Expect(newValidators > primaryValidators, "number of primary validators did not change"); } else if (type == ValidatorType.Secondary) { var newValidators = GetValidatorCount(ValidatorType.Secondary); Runtime.Expect(newValidators > secondaryValidators, "number of secondary validators did not change"); } if (type != ValidatorType.Proposed) { Runtime.AddMember(DomainSettings.ValidatorsOrganizationName, this.Address, target); } Runtime.Notify(type == ValidatorType.Proposed ? EventKind.ValidatorPropose : EventKind.ValidatorElect, Runtime.Chain.Address, target); }
// NOTE - witness not required, as anyone should be able to call this, permission is granted based on consensus public void SetValidator(Address from, BigInteger index, ValidatorType type) { Runtime.Expect(from.IsUser, "must be user address"); Runtime.Expect(type != ValidatorType.Invalid, "invalid validator type"); var primaryValidators = GetValidatorCount(ValidatorType.Primary); var secondaryValidators = GetValidatorCount(ValidatorType.Secondary); Runtime.Expect(index >= 0, "invalid index"); var totalValidators = GetMaxTotalValidators(); Runtime.Expect(index < totalValidators, "invalid index"); if (primaryValidators > 1) { var pollName = ConsensusContract.SystemPoll + ValidatorPollTag; var obtainedRank = Runtime.CallContext("consensus", "GetRank", pollName, from).AsNumber(); Runtime.Expect(obtainedRank >= 0, "no consensus for electing this address"); Runtime.Expect(obtainedRank == index, "this address was elected at a different index"); } else if (primaryValidators == 1) { var firstValidator = GetValidatorByIndex(0).address; Runtime.Expect(IsWitness(firstValidator), "invalid witness"); } else if (primaryValidators == 0) { Runtime.Expect(IsWitness(Runtime.Nexus.GenesisAddress), "invalid witness"); } var expectedType = index < GetMaxPrimaryValidators() ? ValidatorType.Primary : ValidatorType.Secondary; Runtime.Expect(type == expectedType, "unexpected validator type"); var requiredStake = Runtime.CallContext(Nexus.StakeContractName, "GetMasterThreshold", from).AsNumber(); var stakedAmount = Runtime.CallContext(Nexus.StakeContractName, "GetStake", from).AsNumber(); Runtime.Expect(stakedAmount >= requiredStake, "not enough stake"); if (index > 0) { var isPreviousSet = _validators.ContainsKey <BigInteger>(index - 1); Runtime.Expect(isPreviousSet, "previous validator slot is not set"); } var entry = new ValidatorEntry() { address = from, election = Runtime.Time, type = type, }; _validators.Set <BigInteger, ValidatorEntry>(index, entry); if (type == ValidatorType.Primary) { var newValidators = GetValidatorCount(ValidatorType.Primary); Runtime.Expect(newValidators > primaryValidators, "number of primary validators did not change"); } else if (type == ValidatorType.Secondary) { var newValidators = GetValidatorCount(ValidatorType.Secondary); Runtime.Expect(newValidators > secondaryValidators, "number of secondary validators did not change"); } Runtime.Notify(EventKind.ValidatorAdd, Runtime.Chain.Address, from); }
private ValidatorInvocationBuilder CreateBuilder(ValidatorType type) { return(new ValidatorInvocationBuilder(type, _additionAction)); }
protected Validator(string name, ValidatorType type, FilterAction action) { this.Name = name ?? throw new ArgumentNullException(nameof(name)); this.Type = type; this.Action = action; }
internal ComboBoxValidatorItem(ComboBox _comboBox, ValidatorType _type) { this.comboBox = _comboBox; this.comboBox.SelectionChanged += comboBox_SelectionChanged; this.type = _type; }