public bool Attribute(object stateObject, string localName, string ns) { ValidationState state = ToState(stateObject); return(state.Attribute(localName, ns, this)); }
public void RunFullBlockTest() { var generator = new FullBlockTestGenerator(Network.Main); ValidationState validation = new ValidationState(Network.Main); validation.CheckMerkleRoot = false; validation.CheckProofOfWork = false; var scan = new ScanState(new PubKeyHashScanner(generator.CoinbaseKey.PubKey.ID), new Chain(), new Account(), 0); scan.CheckDoubleSpend = true; var mainChain = new Chain(Network.Main); var indexed = new IndexedBlockStore(new InMemoryNoSqlRepository(), CreateBlockStore()); indexed.Put(Network.Main.GetGenesis()); foreach(var test in generator.GetBlocksToTest(true, true).list.OfType<BlockAndValidity>()) { indexed.Put(test.block); mainChain.GetOrAdd(test.block.Header); Assert.True(scan.Process(mainChain, indexed) == test.connects); //if(!) //{ // Assert.True(test.throwsException); //} Assert.Equal(test.heightAfterBlock, scan.Chain.Height); Assert.Equal(test.hashChainTipAfterBlock, scan.Chain.Tip.HashBlock); mainChain.SetTip(scan.Chain.Tip); } }
private static void MergeValidationError(ValidationErrorState originalError, ValidationError newError) { if (originalError.ValidationState == ValidationState.ChildInvalid) { // If original error is due to child's issue, clear the error list, // as we don't care about its child's issues anymore and want to add its own issues. originalError.ErrorMessages.Clear(); } ValidationState errorState = GetValidationState(newError); if (originalError.ValidationState < errorState) { // Promote to the higher level of violation. originalError.ValidationState = errorState; } if (newError.IsWarning) { originalError.ErrorMessages.Add(string.Format(CultureInfo.CurrentUICulture, SR.WarningFormat, newError.Message)); } else { originalError.ErrorMessages.Add(newError.Message); } }
public override ValidationState Validate(UserBase userBase) { if (userBase == null) { throw new ArgumentNullException("userBase"); } ValidationState validationState = new ValidationState(); if (string.IsNullOrEmpty(userBase.Name)) { validationState.Errors.Add(CreateValidationError(userBase.Name, "Name.RequiredError", "Name is required.")); } if (!string.IsNullOrEmpty(userBase.Email)) { if (!Expressions.IsMatch("IsEmail", userBase.Email)) { validationState.Errors.Add(CreateValidationError(userBase.Email, "Email.InvalidError", "Email is invalid.")); } } if (!string.IsNullOrEmpty(userBase.Url)) { if (!Expressions.IsMatch("IsUrl", userBase.Url)) { validationState.Errors.Add(CreateValidationError(userBase.Url, "Url.InvalidError", "Url is invalid.")); } } return(validationState); }
public void ComponentChangesTriggersChangeTest() { var vc = new ValidationContext(); var component = new TextValidationComponent(); vc.Add(component); var stateChanges = new List <bool>(); List <ValidationState> changes = new List <ValidationState>(); vc.ValidationStatusChange.Subscribe(v => changes.Add(v)); vc.Valid.Subscribe(v => stateChanges.Add(v)); Assert.Equal(1, changes.Count); Assert.True(changes[0].IsValid); Assert.Equal(1, stateChanges.Count); var failedState = new ValidationState(false, ComponentValidationText1, component); component.PushState(failedState); Assert.Equal(2, changes.Count); Assert.Equal(2, stateChanges.Count); Assert.False(changes[1].IsValid); Assert.False(stateChanges[1]); Assert.Equal(ComponentValidationText1, changes[1].Text.ToSingleLine()); Assert.Equal(ComponentValidationText1, vc.Text.ToSingleLine()); Assert.False(vc.IsValid); }
public bool Emptiable(object stateObject) { ValidationState state = ToState(stateObject); RdpPattern p = state.Pattern; return(!(p.EndTagDeriv() is RdpNotAllowed)); }
private static bool Check2FA(string username, string tokenCode, ValidationStateDictionary states, AuthenticationDataDto currentUser, SecurityConfig settings) { bool status2 = true; if (settings.Cookie.Enable2FA) { var status = (currentUser.IsPasswordSet) && settings.Cookie.ExemptLocalAccountFrom2FA; if (!status) { var response = Auth2FAresponse(new Authentication2FARequest() { TokenCode = tokenCode, UserID = username }); if (response.ResponseCode != "0") { ValidationState v = new ValidationState(); v.Errors.Add(new ValidationError("TokenCode.InvalidTokenCode", tokenCode, response.ResponseDescription)); //"Invalid token code" states.Add(typeof(LogInDto), v); status2 = false; } } } return(status2); }
public void RunFullBlockTest() { var generator = new FullBlockTestGenerator(Network.Main); ValidationState validation = new ValidationState(Network.Main); validation.CheckMerkleRoot = false; validation.CheckProofOfWork = false; var scan = new ScanState(new PubKeyHashScanner(generator.CoinbaseKey.PubKey.ID), new Chain(), new Account(), 0); scan.CheckDoubleSpend = true; var mainChain = new Chain(Network.Main); var indexed = new IndexedBlockStore(new InMemoryNoSqlRepository(), CreateBlockStore()); indexed.Put(Network.Main.GetGenesis()); foreach (var test in generator.GetBlocksToTest(true, true).list.OfType <BlockAndValidity>()) { indexed.Put(test.block); mainChain.TrySetTip(test.block.Header); Assert.True(scan.Process(mainChain, indexed) == test.connects); //if(!) //{ // Assert.True(test.throwsException); //} Assert.Equal(test.heightAfterBlock, scan.Chain.Height); Assert.Equal(test.hashChainTipAfterBlock, scan.Chain.Tip.HashBlock); mainChain.SetTip(scan.Chain.Tip); } }
public override ValidationState Validate(RoleInput input) { if (input == null) { throw new ArgumentNullException("input"); } ValidationState validationState = new ValidationState(); if (string.IsNullOrEmpty(input.RoleName)) { validationState.Errors.Add(CreateValidationError(input.RoleName, "RoleName", "RoleName.RequiredError", "Role Name is not set")); } else { if (input.RoleName.Length > 256) { validationState.Errors.Add(CreateValidationError(input.RoleName, "RoleName", "RoleName.MaxLengthExceededError", "Role Name must be less than or equal to {0} characters long.", 256)); } } if (input.RoleType == RoleType.NotSet) { validationState.Errors.Add(CreateValidationError(input.RoleType, "RoleType", "RoleType.RequiredError", "One or more role types must be set")); } return(validationState); }
/// <summary> /// Check if the packet satisfies the rule's condition. /// </summary> /// /// <param name="isForInterest"></param> /// <param name="packetName"></param> /// <param name="keyLocatorName">The KeyLocator's name.</param> /// <param name="state">This calls state.fail() if the packet is invalid.</param> /// <returns>True if further signature verification is needed, or false if the /// packet is immediately determined to be invalid in which case this calls /// state.fail() with the proper code and message.</returns> /// <exception cref="ValidatorConfigError">if the supplied isForInterest doesn't match theone for which the rule is designed.</exception> public bool check(bool isForInterest, Name packetName, Name keyLocatorName, ValidationState state) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.FINE, "Trying to check {0} with keyLocator {1}", new Object[] { packetName.toUri(), keyLocatorName.toUri() }); if (isForInterest != isForInterest_) { throw new ValidatorConfigError("Invalid packet type supplied ( " + ((isForInterest) ? "interest" : "data") + " != " + ((isForInterest_) ? "interest" : "data") + ")"); } bool hasPendingResult = false; for (int i = 0; i < checkers_.Count; ++i) { bool result = checkers_[i].check(isForInterest, packetName, keyLocatorName, state); if (!result) { return(result); } hasPendingResult = true; } return(hasPendingResult); }
public override ValidationState Validate(PageInput input) { if (input == null) { throw new ArgumentNullException("input"); } ValidationState validationState = new ValidationState(); string slug = input.Slug.Trim(); if (string.IsNullOrEmpty(slug)) { validationState.Errors.Add(CreateValidationError(slug, "Slug", "Slug.RequiredError", "Slug is not set.")); } else { if (!Expressions.IsMatch("IsPathSlug", slug)) { validationState.Errors.Add(CreateValidationError(slug, "Slug", "Slug.NotValidError", "Slug is not valid.")); } } return(validationState); }
public void QuandoTentarExcluirOPaisPais01(string pais) { ValidationState state = ValidationUtil.GetRuleState(PaisesDict[pais], "RuleIsReferenced_EmpresaInstituicaoPais", DefaultContexts.Delete); MensagemPaisesDict.Add(pais, state); }
/// <summary> /// Validate <paramref name="instance" /> against <paramref /// name="schema" />, returning a list of validation errors. /// </summary> /// /// <remarks> /// <para> /// This method implements JSON Type Definition validation. The precise /// set of validation errors returned are those prescribed by the JSON /// Type Definition specification. The order of the validation errors is /// not meaningful. /// </para> /// /// <para> /// If <paramref name="schema" /> is not a correct schema (that is, its /// <see cref="Schema.Verify" /> raises an exception), then the behavior /// of this method is undefined. /// </para> /// </remarks> /// /// <param name="schema">The schema to validate against.</param> /// /// <param name="instance">The instance ("input") to validate.</param> /// /// <returns> /// <para> /// A list of validation errors, indicating parts of <paramref /// name="instance" /> that <paramref name="schema" /> rejected. This /// list will be empty if there are no validation errors. /// </para> /// /// <para> /// If <see cref="MaxErrors" /> is nonzero, then no more than <see /// cref="MaxErrors" /> errors are returned. Otherwise, all errors are /// returned. /// </para> /// </returns> /// /// <exception cref="MaxDepthExceededException"> /// If <see cref="MaxDepth" /> is nonzero, and validation runs into a /// chain of <c>ref</c>s deeper than the value of <see cref="MaxDepth" /// />. /// </exception> public IList <ValidationError> Validate(Schema schema, IJson instance) { ValidationState state = new ValidationState { Root = schema, InstanceTokens = new List <string>(), SchemaTokens = new List <List <string> >() { new List <string>() }, Errors = new List <ValidationError>(), MaxErrors = MaxErrors, }; try { validate(state, schema, instance); } catch (MaxErrorsReachedException) { // This is a dummy error. We should swallow this, and just // returned the abridged set of errors. } return(state.Errors); }
public bool OpenStartTag(object stateObject, string localName, string ns) { ValidationState state = ToState(stateObject); return(state.OpenStartTag(localName, ns)); }
public virtual async Task <IActionResult> Post([FromBody] TPostRequest request) { var validationState = new ValidationState(); PutResult result; // Make sure Id is not already set (no client-assigned Ids) if (request.Id != default(Guid)) { return(BadRequest(ErrorTranslator.GetErrorMessage("Resource identifiers cannot be assigned by the client."))); } else { result = await PutPipeline.Value.ProcessAsync( new PutContext <TResourceWriteModel, TAggregateRoot>(request, validationState), CancellationToken.None); } // Throw an exceptions that occurred for global exception handling if (result.Exception != null) { Logger.Error("Post", result.Exception); return(CreateActionResultFromException(result.Exception)); } Response.GetTypedHeaders().ETag = GetEtag(result.ETag); Response.GetTypedHeaders().Location = new Uri(GetResourceUrl(result.ResourceId.GetValueOrDefault())); return(result.ResourceWasCreated ? (IActionResult)Created(new Uri(GetResourceUrl(result.ResourceId.GetValueOrDefault())), null) : Ok()); }
public virtual async Task <IActionResult> Put([FromBody] TPutRequest request, Guid id) { // Manual binding of Id to main request model request.Id = id; // Read the If-Match header and populate the resource DTO with an etag value. string etag; bool enforceOptimisticLock = Request.TryGetRequestHeader(HeaderConstants.IfMatch, out etag); request.ETag = Unquoted(etag); var validationState = new ValidationState(); // Execute the pipeline (synchronously) var result = await PutPipeline.Value.ProcessAsync( new PutContext <TResourceWriteModel, TAggregateRoot>(request, validationState), CancellationToken.None); // Check for exceptions if (result.Exception != null) { Logger.Error("Put", result.Exception); return(CreateActionResultFromException(result.Exception, enforceOptimisticLock)); } Response.GetTypedHeaders().ETag = GetEtag(result.ETag); return(result.ResourceWasCreated ? (IActionResult)Created(new Uri(GetResourceUrl(result.ResourceId.GetValueOrDefault())), null) : NoContent()); }
public MockField(object value, object originalValue = null, ValidationState validationState = ValidationState.Valid, bool isChangedByUser = true) { Value = value; OriginalValue = originalValue; ValidationState = validationState; IsChangedByUser = isChangedByUser; IsEditable = true; }
private static IValidator <EditableStruct, ValidationState> CreateValidator(ValidationState state) { var validator = Substitute.For <IValidator <EditableStruct, ValidationState> >(); validator.Validate(Arg.Any <EditableStruct>()).Returns(state); return(validator); }
public ActionResult DeleteConfirmed(int id) { ValidationState validationstate = db.ValidationStates.Find(id); db.ValidationStates.Remove(validationstate); db.SaveChanges(); return(RedirectToAction("Index")); }
private void RaiseValidationStateChangedEvent(ValidationState previousState, ValidationState newState) { OnRaiseValidationStateChanged(previousState, newState); if (ValidationStateChanged != null) { ValidationStateChanged(this, previousState, newState); } }
protected virtual void HandleException(string area, Exception ex) { if (ExceptionHandler != null) { ExceptionHandler.HandleException(ex); } ValidationState.AddError(area, ex.Message); }
public string AddPortalSetting(PortalSetting portalSetting, ref ValidationStateDictionary states) { validationState = validator.Validate(portalSetting, states); if (validationState.IsValid) { return(portalSettingsRepository.AddSetting(portalSetting)); } return(validationState.Errors[0].Message); }
public void CanValidateBlocks() { foreach (var block in StoredBlock.EnumerateFolder(@"data\blocks")) { ValidationState validation = Network.Main.CreateValidationState(); validation.Now = block.Item.Header.BlockTime; Assert.True(validation.CheckBlock(block.Item)); } }
/// Implements simple validation, for example: /// Property is of type Int32, so it can not be 0 or property is of type String can not be null or empty /// It can be overrided on other classes that inherits BaseEntity public ValidationState Validate() { ValidationState validation = new ValidationState(); if (this.Id == 0) { validation.AddError(nameof(this.Id)); } if (String.IsNullOrEmpty(this.CreationUser)) { validation.AddError(nameof(this.CreationUser)); } if (this.CreationDate == DateTime.MinValue || this.CreationDate == null) { validation.AddError(nameof(this.CreationDate)); } if (String.IsNullOrEmpty(this.ModifiedUser)) { validation.AddError(nameof(this.ModifiedUser)); } if (this.ModifiedDate == DateTime.MinValue || this.ModifiedDate == null) { validation.AddError(nameof(this.ModifiedDate)); } string[] allowedActiveValues = { "A", "I" }; if (String.IsNullOrEmpty(this.Active) || !allowedActiveValues.Any(x => x == this.Active)) { validation.AddError(nameof(this.Active)); } //foreach (var field in this.GetType().GetProperties()) //{ // switch (field.PropertyType.Name) // { // case "Int32": // if (Convert.ToInt32(this.GetType().GetProperty(field.Name).GetValue(this, null)) == 0) // validation.AddError(field.Name); // break; // case "String": // if (String.IsNullOrEmpty(Convert.ToString(this.GetType().GetProperty(field.Name).GetValue(this, null)))) // validation.AddError(field.Name); // break; // case "DateTime": // if (Convert.ToDateTime(this.GetType().GetProperty(field.Name).GetValue(this, null)) == DateTime.MinValue) // validation.AddError(field.Name); // break; // } //} return(validation); }
public ActionResult Edit(ValidationState validationstate) { if (ModelState.IsValid) { db.Entry(validationstate).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(validationstate)); }
public virtual void Add(T obj) { (obj as BaseEntity).EntityCreated(); ValidationState validation = (obj as BaseEntity).Validate(); if (!validation.HasErrors()) { this.repository.Add(obj); } }
public virtual void Update(T obj) { (obj as BaseEntity).EntityModified(); ValidationState validation = (obj as BaseEntity).Validate(); if (!validation.HasErrors()) { this.repository.Update(obj); } }
protected virtual ValidationStateEntry GetValidationEntry(object model) { if (model == null || ValidationState == null) { return(null); } ValidationState.TryGetValue(model, out var entry); return(entry); }
public override IEnumerable <ValidationState> Validate(string propertyName) { if (propertyName == nameof(FullName)) { var errors = NotEqual("Reed Copsey").Validate(FullName, "This is a poor choice of names."); yield return(ValidationState.NewPropertyErrors(nameof(FullName), errors)); yield return(ValidationState.NewEntityErrors(errors)); } }
public void tx_valid() { // Read tests from test/data/tx_valid.json // Format is an array of arrays // Inner arrays are either [ "comment" ] // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, enforceP2SH // ... where all scripts are stringified scripts. var tests = TestCase.read_json("data/tx_valid.json"); foreach (var test in tests) { string strTest = test.ToString(); //Skip comments if (!(test[0] is JArray)) { continue; } JArray inputs = (JArray)test[0]; if (test.Count != 3 || !(test[1] is string) || !(test[2] is string)) { Assert.False(true, "Bad test: " + strTest); continue; } Dictionary <OutPoint, Script> mapprevOutScriptPubKeys = new Dictionary <OutPoint, Script>(); foreach (var vinput in inputs) { mapprevOutScriptPubKeys[new OutPoint(new uint256(vinput[0].ToString()), int.Parse(vinput[1].ToString()))] = script_tests.ParseScript(vinput[2].ToString()); } Transaction tx = new Transaction((string)test[1]); ValidationState state = Network.Main.CreateValidationState(); Assert.True(state.CheckTransaction(tx), strTest); Assert.True(state.IsValid); for (int i = 0; i < tx.Inputs.Count; i++) { if (!mapprevOutScriptPubKeys.ContainsKey(tx.Inputs[i].PrevOut)) { Assert.False(true, "Bad test: " + strTest); continue; } var valid = Script.VerifyScript( tx.Inputs[i].ScriptSig, mapprevOutScriptPubKeys[tx.Inputs[i].PrevOut], tx, i, ParseFlags(test[2].ToString()) , 0); Assert.True(valid, strTest + " failed"); } } }
ValidationState GetValidationState(ModelItem modelItem) { ValidationState validationState = ValidationState.Valid; ValidationErrorState validationError = GetValidationError(modelItem); if (validationError != null) { validationState = validationError.ValidationState; } return(validationState); }
public void Many_Disabled_Objects_With_Same_ApplicationName_DifferenceType_Can_Exist(DifferenceType differenceType, ValidationState validationState) { var ruleSet = new RuleSet(); var persistentApplication = new PersistentApplication(Session.DefaultSession); new ModelDifferenceObject(Session.DefaultSession) { Disabled = true, PersistentApplication = persistentApplication }.Save(); var modelDifferenceObject = new ModelDifferenceObject(Session.DefaultSession) { Disabled = true, PersistentApplication = persistentApplication }; Isolate.WhenCalled(() => modelDifferenceObject.DifferenceType).WillReturn(differenceType); RuleSetValidationResult target = ruleSet.ValidateTarget(modelDifferenceObject, ContextIdentifier.Save); var resultItem = target.Results.Where(item => item.Rule is RuleCombinationOfPropertiesIsUnique).Single(); Assert.AreEqual(validationState, resultItem.State); }
/// <summary> /// Used to change the ValidationState of the control and provide a custom message that will be displayed to clarify the state. /// </summary> public void ChangeValidationState(ValidationState validationState, String validationMessage) { if (validationState != ValidationState) { var newStateName = validationState.ToString(); GoToState(newStateName, true); SetValidationMessage(validationMessage); SetValidationState(validationState); //if (this.owner.IsFocused) //{ // this.GoToFocusedState(); //} } }
public void DateCreated_Can_Not_Be_Null(DifferenceType differenceType, ValidationState validationState) { var o = new ModelDifferenceObject(Session.DefaultSession); Isolate.WhenCalled(() => o.DifferenceType).WillReturn(differenceType); var ruleSet = new RuleSet(); RuleSetValidationResult target = ruleSet.ValidateTarget(o, ContextIdentifier.Save); RuleSetValidationResultItem @default = target.Results.Where( item => item.Rule is RuleRequiredField && ((RuleRequiredField)item.Rule).TargetMember.Name == o.GetPropertyInfo(x => x.DateCreated).Name).FirstOrDefault(); Assert.AreEqual(validationState, @default.State); }
public void Same_Application_Objets_Cannot_Exist(DifferenceType differenceType, ValidationState validationState) { var ruleSet = new RuleSet(); var persistentApplication = new PersistentApplication(Session.DefaultSession); var modelDifferenceObject = new ModelDifferenceObject(Session.DefaultSession) { PersistentApplication = persistentApplication }; modelDifferenceObject.Save(); var modelDifferenceObject1 = new ModelDifferenceObject(Session.DefaultSession) { PersistentApplication = persistentApplication }; Isolate.WhenCalled(() => modelDifferenceObject1.DifferenceType).WillReturn(differenceType); RuleSetValidationResult target = ruleSet.ValidateTarget(modelDifferenceObject1, ContextIdentifier.Save); Assert.IsInstanceOfType(typeof(RuleCombinationOfPropertiesIsUnique), target.Results[0].Rule); Assert.AreEqual(validationState, target.Results[0].State); }
BinaryExpression IsStartOf(Block block, TypeNode type, StatementList statements, Expression nameLocal, Expression nsLocal, StringBuilder expecting) { BinaryExpression result = null; if (IsStructuralType(type)) { SchemaElementDecl sd = SchemaElementDecl.Compile(this.module, type, Checker.GetCollectionElementType(type), this.errorHandler, schemaElementDeclCache); SchemaValidator validator = validator = sd.CreateValidator(this.errorHandler); ValidationState context = new ValidationState(); context.ErrorHandler = this.errorHandler; validator.validator.InitValidation(context); ArrayList members = validator.validator.ExpectedElements(context, false, false); foreach (TerminalNode node in members) { if (node is NamedNode) { NamedNode n = node as NamedNode; Identifier name = n.Name; if (expecting.Length>0) expecting.Append(" | "); expecting.Append(name.Name); BinaryExpression isName = new BinaryExpression(nameLocal, new Literal(name.Name, SystemTypes.String), NodeType.Eq); if (name.Prefix != null) { isName = new BinaryExpression(isName, new BinaryExpression(nsLocal, new Literal(name.Prefix.Name, SystemTypes.String), NodeType.Eq), NodeType.And); } if (result == null) result = isName; else result = new BinaryExpression(result, isName, NodeType.Or); } else if (node is WildcardNode) { // todo:??? } } } else { Identifier name = Checker.GetDefaultElementName(type); if (expecting.Length>0) expecting.Append(" | "); expecting.Append(name.Name); result = new BinaryExpression(nameLocal, new Literal(name.Name, SystemTypes.String), NodeType.Eq); if (name.Prefix != null) { result = new BinaryExpression(result, new BinaryExpression(nsLocal, new Literal(name.Prefix.Name, SystemTypes.String), NodeType.Eq), NodeType.And); } } return result; }
internal ValidationErrorState(List<string> errorMessages, ValidationState validationState) { this.ErrorMessages = errorMessages; this.ValidationState = validationState; }
public ValidationMessage(ValidationState state) { this.State = state; this.Message = String.Empty; }
public ValidationMessage(ValidationState state,string message) { this.State = state; this.Message = message; }
private void SetValidationState(ValidationState validationState) { ValidationState = validationState; }
void AddWriteContent(TypeNode type, StatementList statements, TypeNode referringType, Identifier writer, Expression source, SchemaValidator validator) { if (validator.validator is AllElementsContentValidator) { ValidationState context = new ValidationState(); context.ErrorHandler = this.errorHandler; validator.validator.InitValidation(context); ArrayList members = validator.validator.ExpectedElements(context, false, false); foreach (NamedNode childNode in members) { if (childNode.TypeNode == null) continue; // type resolution error. Expression src = GetMemberBinding(source, childNode.Member, childNode.TypeNode); AddWriteElement(statements, referringType, writer, childNode.Name, src, childNode.TypeNode, false); } } else { // Note: there is a SequenceNode wrapper we need to remove and throw away. SequenceNode seq = validator.RootNode as SequenceNode; if (seq != null) { // if seq is null then it's ContentType.Empty or Mixed and mixed is handled at the end. ContentNode n = seq.LeftChild; AddWriteContentNode(n, statements, referringType, writer, source); } } Member mixed = validator.validator.MixedMember; if (mixed != null) { MemberBinding mb = GetMemberBinding(source, mixed); if (mb.Type != null) AddWriteString(statements, referringType, writer, mb); } }
public ValidationResult() { _validationState = ValidationState.Passed; _validationMessages = new List<ValidationMessage>(); }
/// <summary> /// Add a validaiton message to this result collection /// </summary> /// <param name="message">The validation message</param> internal void Add(ValidationMessage message) { ValidationState = message.State; _validationMessages.Add(message); }
void AddReadContent(Class serializer, Block block, TypeNode type, StatementList statements, Identifier reader, Expression target, Expression required, Expression result, SchemaValidator validator) { // position us in the content. statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToContent")), new ExpressionList()))); Local elementName = new Local(Identifier.Empty,SystemTypes.String); statements.Add(new AssignmentStatement(elementName, new QualifiedIdentifier(reader, Identifier.For("LocalName")))); // make sure the element is not empty. If isEmpty = AddEmptyElementCheck(statements, reader); // Read the contents. statements = isEmpty.FalseBlock.Statements; statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("Read")), new ExpressionList()))); statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToContent")), new ExpressionList()))); ValidationState context = new ValidationState(); context.ErrorHandler = this.errorHandler; validator.validator.InitValidation(context); ArrayList members = null; if (validator.validator is AllElementsContentValidator) { members = validator.validator.ExpectedElements(context, false, false); AddReadAllGroup(serializer, block, type, statements, reader, target, required, result, members, validator.validator.MixedMember); } else { // There should be one root level anonymous Item0 member. SequenceNode seq = (SequenceNode)validator.RootNode; // this is a wrapper node. if (seq == null) { // perhaps it is ContentType.Empty or Mixed. if (validator.validator.ContentType == XmlSchemaContentType.Mixed || validator.validator.ContentType == XmlSchemaContentType.TextOnly){ Debug.Assert(validator.validator.MixedMember != null); statements.Add(new AssignmentStatement(GetMemberBinding(target, validator.validator.MixedMember), new MethodCall(new QualifiedIdentifier(reader, Identifier.For("ReadStringElement")), new ExpressionList()))); } return; } else { ContentNode n = seq.LeftChild; AddReadContentNode(n, block, statements, reader, target, required, result, validator); } } // consume final end tag statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("ReadEndTag")), new ExpressionList(elementName)))); }
private string BuildLabels (bool elements) { StringBuilder sb = new StringBuilder (); ValidationState s = new ValidationState (prevState); ICollection col = elements ? GetElementLabels (s) : GetAttributeLabels (s); foreach (XmlQualifiedName qname in col) { sb.Append (qname.ToString ()); sb.Append (' '); } return sb.ToString (); }