/// <summary> /// Initializes a new instance of the <see cref="ValidatorDescriptionAttribute" /> class. /// </summary> /// <param name="tag">The validation tag.</param> /// <param name="validationResultType">The validation result type.</param> /// <param name="validationType">The validation type.</param> public ValidatorDescriptionAttribute(string tag, ValidationResultType validationResultType = ValidationResultType.Error, ValidationType validationType = ValidationType.Field) { Tag = tag; ValidationResultType = validationResultType; ValidationType = validationType; }
public string Generate(int length, ValidationType validationType) { var passwordValidation = new PasswordValidationService(); var wordChar = GenerateChars(length, validationType); var word = new String(wordChar); var measuredPasswordStrength = passwordValidation.MeasurePasswordStrength(word); if (validationType == ValidationType.Strong) while (measuredPasswordStrength != 100) { wordChar = GenerateChars(length, validationType); word = new String(wordChar); measuredPasswordStrength = passwordValidation.MeasurePasswordStrength(word); } else if (validationType == ValidationType.Medium) while (measuredPasswordStrength != 50) { wordChar = GenerateChars(length, validationType); word = new String(wordChar); measuredPasswordStrength = passwordValidation.MeasurePasswordStrength(word); } else if (validationType == ValidationType.Weak) while (measuredPasswordStrength != 20) { wordChar = GenerateChars(length, validationType); word = new String(wordChar); measuredPasswordStrength = passwordValidation.MeasurePasswordStrength(word); } return word ; }
public ValidationResult(string message, string description, ValidationType validationType) : this() { this.Message = message; this.Description = description; this.ValidationType = validationType; }
public ValidationRule(Func<bool> condition, string message, ValidationType validationType = ValidationType.Required) { Condition = condition; Message = message; ValidationType = validationType; }
public IHttpActionResult Get(int length, ValidationType validationType) { var generatePasswordService = new PasswordGenerateService(); var password = generatePasswordService.Generate(length, validationType); return Ok(password); }
public XmlValidatingReader(String xmlFragment, XmlNodeType fragType, XmlParserContext context) { reader = new XmlTextReader(xmlFragment, fragType, context); entityHandling = EntityHandling.ExpandEntities; validationType = ValidationType.Auto; reader.Normalization = true; }
/// <summary> /// Add the Stage validations /// </summary> /// <param name="validationType">The type of validation to perform. /// Only the dialog should use the FromDialog type.</param> public void addValidations(ValidationType validationType) { Int32 stageId; if (!Int32.TryParse(getId(), out stageId) || stageId < 0 || stageId >= m_maxStages) { DataConfiguration.addValidation("The stage ID must be within 0 and " + (m_maxStages - 1).ToString()); } else if (stageId != 0 && getDescription().Length == 0) { DataConfiguration.addValidation("The stage description must be specified (Stage: " + getId() + ")"); } if (validationType.Equals(ValidationType.Complete)) { if (!hasCompletions()) { DataConfiguration.addValidation("Stage completions are mandatory (Stage: " + getId() + ")"); } else { int actionCount; int totalActionCount = 0; foreach (Completion completion in getCompletions()) { switch (completion.getCompletionType()) { case CompletionType.Fight_Mob: case CompletionType.Use_Skill_On_Mob_Type: case CompletionType.Use_Skill_On_Object: actionCount = completion.getCount(); if (actionCount == -1) { // If there is no count then it "counts" as one actionCount = 1; } totalActionCount += actionCount; break; } } if (totalActionCount >= 32) { DataConfiguration.addValidation("There cannot be more than 32 actions in a stage (Stage: " + getId() + ")"); } // Verify CompletionType interdependencies /*if (Completion.contains(getCompletions(), CompletionType.Take_Item_To_Location) && !Completion.contains(getCompletions(), CompletionType.Nearest_Nav)) { DataConfiguration.addValidation("The type '" + CompletionType.Take_Item_To_Location.ToString() + "' requires the '" + CompletionType.Nearest_Nav.ToString() + "' type (Stage: " + getId() + ")."); }*/ } } // ValidationType.Complete }
public static string GetValidationErrorMessage(ValidationType validType) { string errorMessage, dummy; //Get Error Message GetValidationDetails(validType, out dummy, out errorMessage); return errorMessage; }
public string GetSubmitScript(string formId, RouteValueDictionary routeValues, string actionUrl, ValidationType validation = ValidationType.None) { if (routeValues == null) throw new ArgumentNullException("routeValues"); if (String.IsNullOrWhiteSpace(actionUrl)) throw new ArgumentNullException("actionUrl"); if (String.IsNullOrWhiteSpace(formId)) throw new ArgumentNullException("formId"); var scriptTemplate = "var param = [{1}]; setFormParams('{0}', param); submitForm(this, event, '{0}', '{2}', '{3}'); return false;"; return String.Format(scriptTemplate, formId, SafeConvert.ToJSArray(routeValues), actionUrl, validation); }
public static string GetValidationExpression(ValidationType validType) { string regularExpression, dummy; //Get regular Expression GetValidationDetails(validType, out regularExpression, out dummy); return regularExpression; }
public static ValidationMessage AddValidationMessage(this Controller controller, string title, string message, ValidationType validationtType = ValidationType.Info) { Validator validator = controller.TempData["Validator"] as Validator; validator = validator ?? new Validator(); var validationMessage = validator.AddValidationMessage(title, message, validationtType); controller.TempData["Validator"] = validator; return validationMessage; }
public XmlValidatingReader (XmlReader reader) { sourceReader = reader; xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) resolver = new XmlUrlResolver (); entityHandling = EntityHandling.ExpandEntities; validationType = ValidationType.Auto; storedCharacters = new StringBuilder (); }
public ValidationMessage AddValidationMessage(string title, string message, ValidationType messageType) { var validation = new ValidationMessage() { Title = title, Message = message, MessageType = messageType }; ValidationMessages.Add(validation); return validation; }
// Constructors. public XmlValidatingReader(XmlReader reader) { this.reader = (reader as XmlTextReader); if(this.reader == null) { throw new ArgumentException (S._("Xml_NotTextReader"), "reader"); } entityHandling = EntityHandling.ExpandEntities; validationType = ValidationType.Auto; this.reader.Normalization = true; }
private static void HeightLessThanTwo_ThrowsException(ValidationType validationType) { ExceptionAssert.Throws( () => { // Arrange BoardValidationError[] errors; // Act BoardValidator.Validate(5, 1, new[] { 1, 2, 3, 4, 0 }, validationType, out errors); }, typeof(ArgumentException)); }
// SxS: This method resolves an Uri but does not expose it to caller. It's OK to suppress the SxS warning. private void SetupValidation(ValidationType valType) { _validator = BaseValidator.CreateInstance(valType, this, _schemaCollection, _eventHandling, _processIdentityConstraints); XmlResolver resolver = GetResolver(); _validator.XmlResolver = resolver; if (_outerReader.BaseURI.Length > 0) { _validator.BaseUri = (resolver == null) ? new Uri(_outerReader.BaseURI, UriKind.RelativeOrAbsolute) : resolver.ResolveUri(null, _outerReader.BaseURI); } _coreReaderImpl.ValidationEventHandling = (_validationType == ValidationType.None) ? null : _eventHandling; }
public static bool Validate(ValidationType type,string input) { string regex = string.Empty; switch (type) { case ValidationType.Email: regex = EmailPattern; break; default: throw new Exception("没有找到验证类型!"); } return Regex.IsMatch(input, regex); }
public static void CheckTypeValid(Type type, ValidationType valType, string key) { switch (valType) { case ValidationType.Select: { if (!type.IsPrimitive && !_validNonPrimitive.Contains(type) && !typeof(IEnumerable).IsAssignableFrom(type)) { throw new InvalidValidationBuilderException($"Registered property ({key})" + $" can not be of type {type}."); } } break; case ValidationType.OrderBy: { if (!type.IsPrimitive && !_validNonPrimitive.Contains(type)) { throw new InvalidValidationBuilderException ($"Registered property: {key} can not be of type {type}."); } ; } break; case ValidationType.Filter: { if (!type.IsPrimitive && !_validNonPrimitive.Contains(type)) { throw new InvalidValidationBuilderException ($"Registered property: {key} can not be of type {type}."); } ; } break; case ValidationType.Expand: { if (type.IsValueType) { throw new InvalidValidationBuilderException ($"Registered property: {key} can not be of type: {type}. Expand is limited to classes."); } } break; default: { throw new ArgumentOutOfRangeException(nameof(valType), valType, null); } } }
// Initializes a new instance of XmlValidatingReaderImpl class with the specified arguments. // This constructor is used when creating XmlValidatingReaderImpl reader via "XmlReader.Create(..)" internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler?settingsEventHandler, bool processIdentityConstraints) { XmlAsyncCheckReader?asyncCheckReader = reader as XmlAsyncCheckReader; if (asyncCheckReader != null) { reader = asyncCheckReader.CoreReader; } _outerReader = this; _coreReader = reader; _coreReaderImpl = (reader as XmlTextReaderImpl) !; if (_coreReaderImpl == null) { XmlTextReader?tr = reader as XmlTextReader; if (tr != null) { _coreReaderImpl = tr.Impl; } } if (_coreReaderImpl == null) { throw new ArgumentException(SR.Arg_ExpectingXmlTextReader, nameof(reader)); } _coreReaderImpl.XmlValidatingReaderCompatibilityMode = true; _coreReaderNSResolver = reader as IXmlNamespaceResolver; _processIdentityConstraints = processIdentityConstraints; #pragma warning disable 618 _schemaCollection = new XmlSchemaCollection(_coreReader.NameTable); #pragma warning restore 618 _schemaCollection.XmlResolver = GetResolver(); _eventHandling = new ValidationEventHandling(this); if (settingsEventHandler != null) { _eventHandling.AddHandler(settingsEventHandler); } _coreReaderImpl.ValidationEventHandling = _eventHandling; _coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse); _validationType = ValidationType.DTD; SetupValidation(ValidationType.DTD); }
private void SetupValidation(ValidationType valType) { validator = BaseValidator.CreateInstance(valType, this, schemaCollection, eventHandler, processIdentityConstraints); XmlResolver resolver = GetResolver(); validator.XmlResolver = resolver; if (outerReader.BaseURI.Length > 0) { validator.BaseUri = (resolver == null) ? new Uri(outerReader.BaseURI, UriKind.RelativeOrAbsolute) : resolver.ResolveUri(null, outerReader.BaseURI); } UpdateHandlers(); }
public static ResponseStatus ToResponseStatus(this ValidationType type) { switch (type) { case ValidationType.Unauthorized: return(ResponseStatus.Unauthorised); case ValidationType.NotFound: return(ResponseStatus.NotFound); case ValidationType.Invalid: default: return(ResponseStatus.Invalid); } }
protected bool RoomVisibleInput => roomVisibilityDropdown != null ? roomVisibilityDropdown.options[roomVisibilityDropdown.value].text == "PUBLIC" ? true : false : true; // If there is no dropdown then the default value is TRUE protected override bool ValidateInput(ValidationType validationType) { bool validated = true; if (validationType == ValidationType.Create) { if (string.IsNullOrWhiteSpace(RoomNameInput)) { Debug.LogWarning("Room name is empty"); validated = false; } } return(base.ValidateInput(validationType) && validated); }
public void SetAllGivenProperties() { // Arrange. bool isMatch = true; string message = "message"; ValidationType validationType = ValidationType.Range; // Act. ValidationPredicateResult result = new ValidationPredicateResult(isMatch, message, validationType); // Assert. Assert.AreEqual(isMatch, result.IsMatch); Assert.AreEqual(message, result.Message); Assert.AreEqual(validationType, result.ValidationType); }
/// <summary> /// Validierung eines XML-Dokument /// </summary> /// <param name="xmlDoc">Referenz auf das Dokument</param> /// <param name="validationType">Angabe des Validierung-Typs</param> /// <param name="schemaUri">URI der Schemadatei, falls gegen eine solche Validierung werden soll</param> /// <returns>Gibt einen Wert der XmlValidatorResult-Auflistung zurück</returns> public XmlValidatorResult ValidateXmlDocument(XmlDocument xmlDoc, ValidationType validationType, string schemaUri) { //MemoryStream aus dem Xml-Dokument erzeugen //MemoryStream xmlStream = new MemoryStream(); //xmlDoc.Save(xmlStream); //xmlStream.Seek(0, SeekOrigin.Begin); StringReader xmlStream = new StringReader(xmlDoc.InnerXml); // Mit dem MemoryStream eine XmlReader-Instanz erzeugen XmlReader xrdr = XmlReader.Create(xmlStream); // xmlStream.Seek(0, SeekOrigin.Begin); return(ValidateXml(xrdr, validationType, schemaUri)); }
/// <summary> /// 初始化 HtmlDocumentValidation 的新实例。 /// </summary> /// <param name="name">此验证的名称信息(用于向用户界面显示)。</param> /// <param name="documentValidation">一个委托,用于验证 HtmlDocument 是否符合规则。</param> /// <param name="errorMessage">验证不符合规则时的提示信息。</param> public ValidationDelegateTaken(String name, ValidationType validationType, System.Func<HtmlAgilityPack.HtmlDocument, bool> documentValidation, String errorMessage) { this.documentValidation = documentValidation; this.errorMessage = errorMessage; this.Name = name; this.Type = validationType; if (documentValidation == null) { throw new ArgumentNullException("documentValidation"); } if (errorMessage == null) { throw new ArgumentNullException("errorMessage"); } }
/// <summary> /// Validate a package for the given validation context. /// </summary> /// <param name="packageId">Package Id in the format of [package name]@[package version].</param> /// <param name="validationType">The type of validation to assess.</param> /// <returns>True if the validation successfully completed.</returns> public static bool ValidatePackage(string packageId, ValidationType validationType) { if (string.IsNullOrEmpty(packageId)) { throw new ArgumentNullException(packageId); } var packageIdParts = packageId.Split('@'); if (packageIdParts.Length != 2) { throw new ArgumentException("Malformed package Id " + packageId); } return(ValidatePackage(packageIdParts[0], packageIdParts[1], validationType)); }
public static void Should(this IValidationResult source, ValidationType type, Guid guid) { switch (type) { case ValidationType.Pass: ShouldPass(source, guid); break; case ValidationType.Fail: ShouldFail(source, guid); break; default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// Constructs the validator with a XSD schema. /// </summary> /// <param name="xsd">XSD schema.</param> public Validator(string xsd) { //validate arguments if (xsd == null) { throw new ArgumentNullException("xsd"); } else if (xsd.Length == 0) { throw new ArgumentOutOfRangeException("xsd"); } //store schema m_schema = xsd; m_validationType = ValidationType.Schema; }
/// <summary> /// 验证 /// </summary> /// <param name="info"></param> /// <param name="type"></param> /// <param name="propertys"></param> /// <returns></returns> public virtual IList <ErrorInfo> ValidateInfo(object info, ValidationType type, IList <string> propertys = null) { var results = new List <ErrorInfo>(); if (!CheckInfo(info)) { return(results); } var valids = GetValidations(info.GetType()); foreach (var validInfo in valids) { ValidPorpertyValue(results, info, type, validInfo, propertys); } return(results); }
/* Methode zum Validieren eines XML-Dokuments */ public XmlValidatorResult ValidateXmlDocument(XmlDocument xmlDoc, ValidationType validationType, string schemaFileName) { // MemoryStream aus dem Xml-Dokument erzeugen MemoryStream xmlStream = new MemoryStream(); xmlDoc.Save(xmlStream); xmlStream.Seek(0, SeekOrigin.Begin); // Mit dem MemoryStream eine XmlTextReader-Instanz erzeugen XmlTextReader xmlTextReader = new XmlTextReader(xmlStream); xmlStream.Seek(0, SeekOrigin.Begin); return(ValidateXml(xmlTextReader, validationType, schemaFileName)); }
private static void Duplication_IsInvalid(ValidationType validationType) { // Arrange BoardValidationError[] errors; // Act bool isValid = BoardValidator.Validate(3, 3, new[] { 1, 2, 3, 4, 5, 6, 7, 7, 0 }, validationType, out errors); // Assert Assert.IsFalse(isValid); Assert.IsTrue(errors.Length > 0); Assert.AreEqual(BoardValidationErrorType.Duplication, errors[0].ErrorType); Assert.IsNotNull(errors[0].Position); Assert.AreEqual(1, errors[0].Position.X); Assert.AreEqual(2, errors[0].Position.Y); }
public ValidationPredicateResult(bool isMatch, string message, ValidationType validationType) { if (message == null) { throw new ArgumentNullException("message"); } if (message.Length == 0) { throw new ArgumentException(ValidationPredicateMessages.NullOrEmptyStringMessage, "message"); } this.isMatch = isMatch; this.message = message; this.validationType = validationType; }
private void Add <T, P>( Expression <Func <T, P> > expression, string message, string reference, ValidationType type, Exception exception = null) { string display = expression.PropertyDisplay(); reference = reference ?? expression.PropertyPath(); message = message ?? (ValidationMessage.IsTypeError(type) ? Resource.XNotValid : Resource.XValid); message = Regex.Replace(message, @"\{0\}", display); Messages.Add(new ValidationMessage(message, reference, type) { Exception = exception }); }
/// <summary> /// This method checks data to see if it is valid as well as allowing you to specify a minimum/maximum length. /// (Overrides Password minimum length.) /// </summary> /// <param name="strVal">The string data to check.</param> /// <param name="typeValid">This specifies the type of validation to use.</param> /// <param name="minLength">This is the minimum length that the string must be to pass validation.</param> /// <param name="maxLength">This is the maximum length that the string must be to pass validation.</param> /// <returns></returns> public static bool RegExCheck(this string strVal, ValidationType typeValid, int minLength, int maxLength) { if (minLength == 0 && strVal.Length == 0) { return(true); } if (strVal.Length < minLength || strVal.Length > maxLength) { return(false); } if (typeValid == ValidationType.Password) { return(RegExMatch(strVal, $@"^[a-zA-Z0-9 !#$@%&*+=?^_{{|}}~-]{{{minLength},{maxLength}}}$")); } return(RegExCheck(strVal, typeValid)); }
public virtual string GetErrorMessage(string propertyName, ValidationType validation) { var mp = _m.GetProperty(propertyName); if (mp == null) { return(string.Empty); } var mpv = new ObjectDefPropertyValidation(); // mp.GetValidation(validation); if (mpv == null) { return(string.Empty); } return(mpv.ValidationMessage); }
/// <summary> /// /// </summary> /// <param name="type"></param> /// <param name="expiresMinute"></param> /// <returns></returns> public SmsContent GetSmsContent(ValidationType type, int expiresMinute = 5) { var code = new Random(Guid.NewGuid().GetHashCode()).Next(100000, 999999); if (_appSettings.DeveloperMode) { code = 123456; } string content; switch (type) { case ValidationType.Register: content = $"您正在使用手机号注册福禄通行证账号,验证码:{code},{expiresMinute}分钟内有效。如非本人操作,请忽略本短信。"; break; case ValidationType.ChangePhoneNo: content = $"您正在修改手机号,验证码:{code},{expiresMinute}分钟内有效。请勿将验证码泄露给他人使用。"; break; case ValidationType.ResetPassword: content = $"您正在使用手机号进行修改密码操作,验证码:{code},{expiresMinute}分钟内有效。验证码提供给让人可能导致账号被盗,请勿泄露,谨防被骗。"; break; case ValidationType.Login: content = $"您正在使用短信验证码登录功能,验证码:{code},{expiresMinute}分钟内有效。请勿将验证码泄露给他人使用。"; break; case ValidationType.Validate: expiresMinute = 15; content = $"您正在使用手机验证操作,验证码:{code},{expiresMinute}分钟内有效。如非本人操作,请忽略本短信。"; break; default: content = $"验证码:{code},{expiresMinute}分钟内有效。请勿将验证码泄露给他人使用。"; break; } return(new SmsContent { Code = code.ToString(), Content = content, ExpiresMinute = expiresMinute, ValidationType = type }); }
public virtual bool IsValid(string propertyName, ValidationType validation) { var mp = _m.GetProperty(propertyName); if (mp == null) { return(false); } var mpv = _m.Validations.Where(p => p.ValidationType == validation).FirstOrDefault(); if (mpv == null) { return(true); //if no such validation, continue } var bResult = false; switch (mpv.ValidationType) { case ValidationType.Required: bResult = ValidateRequired(propertyName); break; case ValidationType.Range: bResult = ValidateRange(propertyName, mpv); break; case ValidationType.StringLength: bResult = ValidateStringLength(propertyName, mpv); break; case ValidationType.RegularExpression: bResult = ValidateRegularExpression(propertyName, mpv); break; case ValidationType.Identifier: bResult = ValidateIdentifier(propertyName, mpv); break; case ValidationType.Email: bResult = ValidateEmail(propertyName, mpv); break; default: break; } return(bResult); }
public ValidateItem(string text, string message, ValidationType validationtype, string regexmessageonfail = "") { Text = text; Message = message; Type = validationtype; Regex = ""; if (validationtype == ValidationType.Email) { Regex = "@"; } else if (validationtype == ValidationType.Phone) { Regex = @"^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$"; } RegExpression = new Regex(Regex); RegexMessage = regexmessageonfail; }
public void Check_exception_values( string message, string stackTrace, string reference, ValidationType type, string expected) { try { throw new CustonException(message, stackTrace); } catch (CustonException ex) { ValidationMessage result = new(ex, reference, type); Assert.Equal(result.Message, expected); Assert.Equal(result.Type, type); Assert.Equal(result.Reference, reference); } }
/// <summary>Resets the members of the settings class to their default values.</summary> public void Reset() { this.checkCharacters = true; this.closeInput = false; this.conformance = ConformanceLevel.Document; this.ignoreComments = false; this.ignoreProcessingInstructions = false; this.ignoreWhitespace = false; this.lineNumberOffset = 0; this.linePositionOffset = 0; this.prohibitDtd = true; this.schemas = null; this.schemasNeedsInitialization = true; this.validationFlags = (XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.AllowXmlAttributes); this.validationType = ValidationType.None; this.xmlResolver = new XmlUrlResolver(); }
// Initializes a new instance of XmlValidatingReaderImpl class with the specified arguments. // This constructor is used when creating XmlValidatingReaderImpl reader via "XmlReader.Create(..)" internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler settingsEventHandler, bool processIdentityConstraints) { XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader; if (asyncCheckReader != null) { reader = asyncCheckReader.CoreReader; } outerReader = this; coreReader = reader; coreReaderImpl = reader as XmlTextReaderImpl; if (coreReaderImpl == null) { XmlTextReader tr = reader as XmlTextReader; if (tr != null) { coreReaderImpl = tr.Impl; } } if (coreReaderImpl == null) { throw new ArgumentException(Res.GetString(Res.Arg_ExpectingXmlTextReader), "reader"); } coreReaderImpl.XmlValidatingReaderCompatibilityMode = true; coreReaderNSResolver = reader as IXmlNamespaceResolver; this.processIdentityConstraints = processIdentityConstraints; #pragma warning disable 618 schemaCollection = new XmlSchemaCollection(coreReader.NameTable); #pragma warning restore 618 schemaCollection.XmlResolver = GetResolver(); eventHandling = new ValidationEventHandling(this); if (settingsEventHandler != null) { eventHandling.AddHandler(settingsEventHandler); } coreReaderImpl.ValidationEventHandling = eventHandling; coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse); validationType = ValidationType.DTD; SetupValidation(ValidationType.DTD); }
private void Validate(String filename, ValidationType vt) { try { //Implement the readers. Set the ValidationType. txtreader = new XmlTextReader(filename); reader = new XmlValidatingReader(txtreader); reader.ValidationType = vt; //If the reader is set to validate, set the event handler. if (vt == ValidationType.None) { Console.WriteLine("\nParsing XML file " + filename.ToString()); } else { Console.WriteLine("\nValidating XML file " + filename.ToString()); m_success = true; //Set the validation event handler. reader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); } // Read XML data while (reader.Read()) { } if (vt == ValidationType.None) { Console.WriteLine("Finished parsing file."); } else { Console.WriteLine("Validation finished. Validation {0}", (m_success == true ? "successful" : "failed")); } } finally { //Close the reader. if (reader != null) { reader.Close(); } } }
void Initialize(XmlResolver resolver) { nameTable = null; #if !SILVERLIGHT if (!EnableLegacyXmlSettings()) { xmlResolver = resolver; // limit the entity resolving to 10 million character. the caller can still // override it to any other value or set it to zero for unlimiting it maxCharactersFromEntities = (long)1e7; } else #endif { xmlResolver = (resolver == null ? CreateDefaultResolver() : resolver); maxCharactersFromEntities = 0; } lineNumberOffset = 0; linePositionOffset = 0; checkCharacters = true; conformanceLevel = ConformanceLevel.Document; ignoreWhitespace = false; ignorePIs = false; ignoreComments = false; dtdProcessing = DtdProcessing.Prohibit; closeInput = false; maxCharactersInDocument = 0; #if !SILVERLIGHT schemas = null; validationType = ValidationType.None; validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints; validationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes; #endif #if ASYNC || FEATURE_NETCORE useAsync = false; #endif isReadOnly = false; #if !SILVERLIGHT IsXmlResolverSet = false; #endif }
/// <summary> /// /// </summary> public async Task SaveLog(int appId, string content, ValidationType type, string phone, string ip, bool isSuccess, string code, int expiresMinute, string smsMsgId, string smsMsg) { var smsRecordEntity = new SmsRecordEntity { SendTime = DateTime.Now, ClientId = appId, Content = content, SendType = type.ToString(), Receiver = phone, IpAddress = ip, SendResult = isSuccess, Remark = isSuccess ? $"发送成功,msg_id:{smsMsgId}" : $"发送失败,错误描述:{smsMsg},msg_id:{smsMsgId}" }; await _smsRecordRepository.InsertAsync(smsRecordEntity); await _unitOfWork.SaveChangesAsync(); }
private static void PerformValidation(this TextBox tbx, ValidationType validationType) { char[] enteredString = tbx.Text.ToCharArray(); switch (validationType) { case ValidationType.Amount: tbx.Text = AmountValidation(enteredString); break; case ValidationType.Integer: tbx.Text = IntegerValidation(enteredString); break; default: break; } tbx.SelectionStart = tbx.Text.Length; }
protected virtual bool ValidateInput(ValidationType validationType) { if (validationType == ValidationType.Create) { if (string.IsNullOrWhiteSpace(SaveNameInput)) { Debug.LogWarning("Invalid player input, save name is empty!"); return(false); } if (!SaveDataManager.Instance.ValidateNewSaveName(SaveNameInput)) { Debug.LogWarning("Invalid player input, a save file with the same name already exists!"); return(false); } } return(true); }
public static int Validate(ValidationType validationType, List <string> passwordDatabaseList) { var numberOfValidPasswords = 0; var passwordObjects = CreatePasswordObjects(passwordDatabaseList); switch (validationType) { case ValidationType.MinMaxAmountOfRequiredCharacter: numberOfValidPasswords = GetNumberOfValidPasswordsByMinMaxAmountOfRequiredCharacter(passwordObjects); break; case ValidationType.PositionOfRequiredCharacter: numberOfValidPasswords = GetNumberOfValidPasswordsByPositionOfRequiredCharacter(passwordObjects); break; } return(numberOfValidPasswords); }
// Initializes a new instance of XmlValidatingReaderImpl class with the specified arguments. // This constructor is used when creating XmlValidatingReaderImpl reader via "XmlReader.Create(..)" internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler settingsEventHandler, bool processIdentityConstraints) { outerReader = this; coreReader = reader; coreReaderImpl = reader as XmlTextReaderImpl; if (coreReaderImpl == null) { XmlTextReader tr = reader as XmlTextReader; if (tr != null) { coreReaderImpl = tr.Impl; } } if (coreReaderImpl == null) { throw new ArgumentException(Res.GetString(Res.Arg_ExpectingXmlTextReader), "reader"); } coreReaderImpl.XmlValidatingReaderCompatibilityMode = true; coreReaderNSResolver = reader as IXmlNamespaceResolver; this.processIdentityConstraints = processIdentityConstraints; #pragma warning disable 618 schemaCollection = new XmlSchemaCollection(coreReader.NameTable); #pragma warning restore 618 schemaCollection.XmlResolver = GetResolver(); if (settingsEventHandler == null) { internalEventHandler = new ValidationEventHandler(InternalValidationCallback); eventHandler = internalEventHandler; coreReaderImpl.ValidationEventHandler = internalEventHandler; } else { eventHandler = settingsEventHandler; coreReaderImpl.ValidationEventHandler = settingsEventHandler; } validationType = ValidationType.DTD; SetupValidation(ValidationType.DTD); }
public DateValidationAttribute(ValidationType validationType, string compareWith = "", string fromDate = "") { _validationType = validationType; switch (validationType) { case ValidationType.Compare: { _propertyNameToCompare = compareWith; break; } case ValidationType.RangeValidation: { _fromDate = new DateTime(2000, 1, 1); _toDate = DateTime.Today; break; } } }
public bool IsValid(ValidationType validationType = ValidationType.Time) { switch (validationType) { case ValidationType.Time: return validTill > DateTime.Now; case ValidationType.Strict: if (validTill > DateTime.Now) User.Login(creditals); else { throw new SecurityException("Time validation failed"); } break; default: Trace.Write("Unexpectedly got to validationTypes default close"); throw new Exception("unexpected"); } return true; }
public static BaseValidator CreateInstance(ValidationType valType, XmlValidatingReaderImpl reader, XmlSchemaCollection schemaCollection, IValidationEventHandling eventHandling, bool processIdentityConstraints) { switch (valType) { case ValidationType.None: return new BaseValidator(reader, schemaCollection, eventHandling); case ValidationType.Auto: return new AutoValidator(reader, schemaCollection, eventHandling); case ValidationType.DTD: return new DtdValidator(reader, eventHandling, processIdentityConstraints); case ValidationType.XDR: return new XdrValidator(reader, schemaCollection, eventHandling); case ValidationType.Schema: return new XsdValidator(reader, schemaCollection, eventHandling); } return null; }
private static void GetValidationDetails(ValidationType validationType, out string regularExpression, out string errorMessage) { //Set ValidationHelper Type switch (validationType) { case ValidationType.Numbers: regularExpression = RegularExpression.NUMBERS; errorMessage = "Value must only contain numbers"; break; case ValidationType.AlphaNumeric: regularExpression = RegularExpression.ALPHANUMERIC; errorMessage = "Value must only contain character and alphabets"; break; case ValidationType.Characters: regularExpression = RegularExpression.CHARACTERS; errorMessage = "Value must only contain characters"; break; case ValidationType.Decimals: regularExpression = RegularExpression.DECIMAL; errorMessage = "Value is not the right format"; break; case ValidationType.Name: regularExpression = RegularExpression.NAME; errorMessage = "Name is not valid"; break; case ValidationType.Email: regularExpression = RegularExpression.EMAIL; errorMessage = "Email is invalid"; break; case ValidationType.PostalCode: regularExpression = RegularExpression.POSTAL_CODE; errorMessage = "Postal Code is invalid"; break; default: regularExpression = string.Empty; errorMessage = string.Empty; break; } }
private char[] GenerateChars(int length, ValidationType validationType) { var word = new char[length]; var random = new Random(); for (var i = 0; i < length; i++) { _generators = new List<IGenerateCommand>() { new LowerCaseGenerate(), new UpperCaseGenerate(), new NumberGenerate() }; if (validationType == ValidationType.Strong) _generators.Add(new SpecialCharGenerate()); Thread.Sleep(10); word[i] = _generators[random.Next(0, _generators.Count)].Generate(); } return word; }
public static MvcHtmlString SubmitLink(this HtmlHelper helper, string title, string formId, string actionName, string controllerName, ValidationType validationType = ValidationType.All, object htmlAttributes = null, object submitParams = null) { var url = GetActionUrl(helper.ViewContext.RequestContext, actionName, controllerName); var paramsDictionary = new RouteValueDictionary(submitParams); var linkTag = GetSubmitTag("a", title, htmlAttributes); linkTag.Attributes.Add("href", "#"); if (paramsDictionary.Count > 0) { var key = paramsDictionary.GetHashCode(); var scriptTag = GetWrapperScriptTag(paramsDictionary, key); var script = String.Format("submitFormWithParams_{3}(this, event, '#{0}', '{1}', '{2}'); return false;", formId, url, validationType.ToString(), key); linkTag.Attributes.Add("onclick", script); return MvcHtmlString.Create(scriptTag.ToString(TagRenderMode.Normal) + linkTag.ToString(TagRenderMode.Normal)); } else { var script = String.Format("submitFormWithoutParams(this, event, '#{0}', '{1}', '{2}'); return false;", formId, url, validationType.ToString()); linkTag.Attributes.Add("onclick", script); return MvcHtmlString.Create(linkTag.ToString(TagRenderMode.Normal)); } }
public string ApplyXSL(string content, string title, XmlResolver resolver, ValidationType validate) { StringReader reader = new StringReader(content); XmlReaderSettings rsettings = new XmlReaderSettings(); if (validate != ValidationType.None) { rsettings.ValidationType = validate; if (validate == ValidationType.DTD) { rsettings.ProhibitDtd = false; } rsettings.ValidationEventHandler += MyValidationEventHandler; } XmlReader doc = XmlReader.Create(reader, rsettings); XsltArgumentList args = new XsltArgumentList(); args.AddParam("root-note", "", title); args.AddExtensionObject("http://beatniksoftware.com/tomboy", new TransformExtension()); StringWriter outWriter = new StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Auto; settings.OmitXmlDeclaration = true; XmlWriter writer = XmlWriter.Create(outWriter, settings); if (writer == null) { Logger.Error("XmlWriter was null"); throw new NullReferenceException("xmlWriter was null"); } _xsl.Transform(doc, args, writer, resolver); doc.Close(); outWriter.Close(); return outWriter.ToString(); }
public void SetType(Control control, ValidationType type) { if (this.infos.ContainsKey(control)) { // Especially, in design mode and type is none, ask whether remove validation information. if ((DesignMode) && (type == ValidationType.None)) { // Set right to left message box options. MessageBoxOptions options = (MessageBoxOptions)0; if (this.RightToLeft) { options = MessageBoxOptions.RtlReading | MessageBoxOptions.RightAlign; } if (MessageBox.Show( Resources.VALIDATOR_REMOVEWARNING, Resources.VALIDATOR_NAME, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, options) == DialogResult.Yes) { this.RemoveValidationInfo(control); } } else { this.infos[control].Type = type; } } else { this.AddValidationInfo(control); ValidationInfo info = this.infos[control]; info.Type = type; } }
private void Initialize(XmlResolver resolver) { _nameTable = null; if (!EnableLegacyXmlSettings()) { _xmlResolver = resolver; // limit the entity resolving to 10 million character. the caller can still // override it to any other value or set it to zero for unlimiting it _maxCharactersFromEntities = (long)1e7; } else { _xmlResolver = (resolver == null ? CreateDefaultResolver() : resolver); _maxCharactersFromEntities = 0; } _lineNumberOffset = 0; _linePositionOffset = 0; _checkCharacters = true; _conformanceLevel = ConformanceLevel.Document; _ignoreWhitespace = false; _ignorePIs = false; _ignoreComments = false; _dtdProcessing = DtdProcessing.Prohibit; _closeInput = false; _maxCharactersInDocument = 0; _schemas = null; _validationType = ValidationType.None; _validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints; _validationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes; _useAsync = false; _isReadOnly = false; IsXmlResolverSet = false; }
/// <summary> /// Instantiates a new validating XML reader. /// </summary> /// <param name="xmlReader"></param> /// <param name="validationType"></param> /// <param name="xsdResourceName"></param> /// <returns></returns> public static XmlReader NewValidatingReader(XmlReader xmlReader, ValidationType validationType, params string[] xsdResourceName) { if (Logger.IsUtilVerbose) Logger.UtilSource.TraceEvent(TraceEventType.Verbose, 0, "Instantiating new validating reader with validation: " + validationType + " and XSDs " + Misc.ArrayToString(xsdResourceName)); XmlReaderSettings xmlReaderSettings = new XmlReaderSettings(); if (validationType == ValidationType.DTD) { xmlReaderSettings.ProhibitDtd = false; } else if ((validationType == ValidationType.Schema) && (xsdResourceName != null)) { XmlSchemaSet sc = new XmlSchemaSet(); sc.Add(XmlSchema.Read(Parameter.GetEmbeddedResourceStream(xsdResourceName[0]), null)); xmlReaderSettings.Schemas.Add(sc); } else if (validationType != ValidationType.None) { throw new BREException("Validation type should be DTD, Schema or None. If Schema, a schema resource name must be passed."); } xmlReaderSettings.ValidationType = validationType; return XmlReader.Create(xmlReader, xmlReaderSettings); }
/// <summary> /// Instantiates a new validating XML reader. /// </summary> /// <param name="xmlReader"></param> /// <param name="validationType"></param> /// <returns></returns> public static XmlReader NewValidatingReader(XmlReader xmlReader, ValidationType validationType) { return NewValidatingReader(xmlReader, validationType, null); }