public void StringMaxLength()
        {
            var schema = new SimpleTypeSchema("Currency", typeof(string))
                         .SetStringMaxLength(3);

            schema.GetStringMaxLength() !.MaxLength.Should().Be(3);

            Property <string> currency = new Property <string>("Currency")
                                         .SetSchema(schema);

            var validationRules = ValidationProvider.Instance.GetValidationRules(currency).ToList();

            validationRules.Should().HaveCount(1);

            var messages = new MutablePropertyContainer()
                           .WithValue(currency, "USD")
                           .Validate(validationRules)
                           .ToList();

            messages.Should().BeEmpty();

            messages = new MutablePropertyContainer()
                       .WithValue(currency, "abcd")
                       .Validate(validationRules)
                       .ToList();

            messages[0].FormattedMessage.Should().Be("Value 'abcd' is too long (length: 4, maxLength: 3)");
        }
Ejemplo n.º 2
0
        protected override void OnPreRender(EventArgs e)
        {
            if (MaxLength > 0)
            {
                Attributes["maxlength"] = MaxLength.ToString();
            }

            if (Size > 0)
            {
                Attributes["size"] = Size.ToString();
            }

            if (!string.IsNullOrEmpty(WaterMarkText))
            {
                CssClass += " watermark";
                Attributes["watermarkvalue"] = WaterMarkText;
            }

            if (!string.IsNullOrEmpty(EnterKeyActivates))
            {
                Attributes["enteractivates"] = EnterKeyActivates;
            }

            base.OnPreRender(e);
        }
Ejemplo n.º 3
0
        public string GetString(Renamer renamer, MediaFile mediaFile)
        {
            string generatedString = GenerateString(renamer, mediaFile);

            if (MaxLength.HasValue)
            {
                generatedString = generatedString.Substring(0, MaxLength.GetValueOrDefault());
            }

            if (ForceCase.HasValue)
            {
                switch (ForceCase)
                {
                case FilePathTags.ForceCase.Lower:
                    generatedString = generatedString.ToLower();
                    break;

                case FilePathTags.ForceCase.Upper:
                    generatedString = generatedString.ToUpper();
                    break;

                default:
                    throw new InvalidOperationException();
                }
            }
            return(generatedString);
        }
Ejemplo n.º 4
0
        public static string OnTextChange(string text, RegexType regexType, MaxLength maxLength)
        {
            if (text.Trim().Length > (int)maxLength)
            {
                text = text.Substring(0, (int)maxLength);
                return(text);
            }
            var NombreRegex = regexType.GetStringValue();

            text = text.TrimStart().ToUpper().Replace("  ", " ");

            bool EsValido = (Regex.IsMatch(text, NombreRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));

            if (!EsValido)
            {
                if (text.Length > 1)
                {
                    text = text.Remove(text.Length - 1);
                }
                else
                {
                    text = "";
                }
            }
            return(text);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// クライアントでのバリデーション用の操作
        /// </summary>
        /// <param name="context">クライアントのバリデーションコンテキスト</param>
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (MinLength > 0)
            {
                // 最小値が設定されている場合以下のタグ属性を設定する
                // minlength                            最小桁数
                // min-length-err-msg                   バリデーションで設定されたエラーメッセージ
                context.Attributes["minlength"] = MinLength.ToString();
                if (!string.IsNullOrWhiteSpace(UnderMinErrorMessage))
                {
                    context.Attributes["minlength-err-msg"] = UnderMinErrorMessage;
                }
            }

            if (MaxLength > 0)
            {
                // 最大値が設定されている場合以下のタグ属性を設定する
                // maxlength                            最大桁数
                // max-length-err-msg                   バリデーションで設定されたエラーメッセージ
                context.Attributes["maxlength"] = MaxLength.ToString();
                if (!string.IsNullOrWhiteSpace(OverMaxErrorMessage))
                {
                    context.Attributes["maxlength-err-msg"] = OverMaxErrorMessage;
                }
            }
        }
Ejemplo n.º 6
0
        protected override void Execute(NativeActivityContext context)
        {
            var twilio      = context.GetExtension <ITwilioContext>();
            var timeout     = Timeout.Get(context);
            var finishOnKey = FinishOnKey.Get(context);
            var maxLength   = MaxLength.Get(context);
            var transcribe  = Transcribe.Get(context);
            var playBeep    = PlayBeep.Get(context);

            var actionUrl = twilio.ResolveBookmarkUrl(context.CreateTwilioBookmark(OnAction));

            // append record element
            var element = new XElement("Record",
                                       new XAttribute("action", actionUrl),
                                       timeout != null ? new XAttribute("timeout", ((TimeSpan)timeout).TotalSeconds) : null,
                                       finishOnKey != null ? new XAttribute("finishOnKey", finishOnKey) : null,
                                       maxLength != null ? new XAttribute("maxLength", ((TimeSpan)maxLength).TotalSeconds) : null,
                                       transcribe != null ? new XAttribute("transcribe", (bool)transcribe ? "true" : "false") : null,
                                       playBeep != null ? new XAttribute("playBeep", (bool)playBeep ? "true" : "false") : null);

            // write dial element and catch redirect
            GetElement(context).Add(
                element,
                new XElement("Redirect", actionUrl));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// クライアントでのバリデーション用の操作
        /// </summary>
        /// <param name="context">クライアントのバリデーションコンテキスト</param>
        public void AddValidation(ClientModelValidationContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (MinLength > 0)
            {
                // 最小値が設定されている場合以下のタグ属性を設定する
                // minlength                            最小桁数
                // notsupported-min-length-err-msg      未サポートブラウザでのエラーメッセージ
                // min-length-err-msg                   バリデーションで設定されたエラーメッセージ
                MergeAttribute(context.Attributes, "minlength", MinLength.ToString());
                MergeAttribute(context.Attributes, "notsupported-min-length-err-msg", "最小桁数「" + MinLength.ToString() + "」より短いです。");
                if (!string.IsNullOrWhiteSpace(UnderMinErrorMessage))
                {
                    MergeAttribute(context.Attributes, "min-length-err-msg", UnderMinErrorMessage);
                }
            }

            if (MaxLength > 0)
            {
                // 最大値が設定されている場合以下のタグ属性を設定する
                // maxlength                            最大桁数
                // notsupported-max-length-err-msg      未サポートブラウザでのエラーメッセージ
                // max-length-err-msg                   バリデーションで設定されたエラーメッセージ
                MergeAttribute(context.Attributes, "maxlength", MaxLength.ToString());
                MergeAttribute(context.Attributes, "notsupported-max-length-err-msg", "最大桁数「" + MaxLength.ToString() + "」より長いです。");
                if (!string.IsNullOrWhiteSpace(ErrorMessageString))
                {
                    MergeAttribute(context.Attributes, "max-length-err-msg", ErrorMessageString);
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 入力ダイアログ
        /// </summary>
        /// <returns></returns>
        protected override bool DoInput()
        {
            bool   ret    = false;
            string msgfmt = CommonProc.MessageText("G003");

            msgfmt = msgfmt.Replace("%param", ParamName);
            msgfmt = msgfmt.Replace("%length", MaxLength.ToString());
            if (AllowJapanese)
            {
                IMEInputTextDialog tdlg = new IMEInputTextDialog();
                tdlg.InputText = frontend.Text;
                tdlg.Caption   = msgfmt;
                tdlg.MaxLength = MaxLength;
                if (tdlg.ShowDialog() == DialogResult.OK)
                {
                    frontend.Text = tdlg.InputText;
                    ret           = true;
                }
                tdlg.Dispose();
            }
            else
            {
                KeyboardDialog kdlg = new KeyboardDialog();
                kdlg.InputArea    = frontend.Text;
                kdlg.Message_Text = msgfmt;
                kdlg.DispMode     = 0; //テキスト
                if (kdlg.ShowDialog() == DialogResult.OK)
                {
                    frontend.Text = kdlg.InputArea;
                    ret           = true;
                }
                kdlg.Dispose();
            }
            return(ret);
        }
Ejemplo n.º 9
0
 public void FromXml(XElement config)
 {
     SourceBuildings.FromXml(config, SourceBuildings);
     TargetBuildings.FromXml(config, TargetBuildings);
     UseSize.FromXml(config, UseSize);
     MaxLength.FromXml(config, MaxLength);
     MaxWidth.FromXml(config, MaxWidth);
 }
Ejemplo n.º 10
0
        public override bool Equals(object obj)
        {
            if (!(obj is BaseTag other))
            {
                return(false);
            }

            return(MaxLength.Equals(other.MaxLength));
        }
Ejemplo n.º 11
0
        public static string Truncate(string val, MaxLength length)
        {
            if (val.Length > (int)length)
            {
                return(val.Substring(0, (int)length));
            }

            return(val);
        }
        public void WriteToFile(string filePath)
        {
            var bytes = Encoding.UTF8.GetBytes(MaxLength.ToString());

            using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                fileStream.Write(bytes, 0, bytes.Length);
            }
        }
Ejemplo n.º 13
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            var text   = Text.Get <string>(executionContext);
            var min    = MinLength.Get <int>(executionContext);
            var max    = MaxLength.Get <int>(executionContext);
            var result = Codify(text, min, max);

            Result.Set(executionContext, result);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Renders control.
        /// </summary>
        /// <param name="writer">The HtmlTextWriter to render content to.</param>
        protected override void Render(HtmlTextWriter writer)
        {
            if (writer == null)
            {
                return;
            }

            bool renderSecondRow = ((Required || (RangeValidation && ValidationType != CustomValidationDataType.String) || RegularExpressionValidation) &&
                                    Enabled && (!ReadOnly));

            if (this.Theme != MasterPageTheme.Modern)
            {
                BaseValidatedControl.RenderValidatedControlBeginTag(Required && ShowRequired, writer, this.Width);
            }

            if (Masked)
            {
                if (!this.Width.IsEmpty)
                {
                    m_RadMaskedTextBox.Width = ((this.Theme == MasterPageTheme.Modern) ? this.Width : Unit.Percentage(100));
                }
                m_RadMaskedTextBox.RenderControl(writer);
            }
            else
            {
                if (!this.Width.IsEmpty)
                {
                    m_TextBox.Width = ((this.Theme == MasterPageTheme.Modern) ? this.Width : Unit.Percentage(100));
                }
                if (MultiLineMode && (MaxLength > 0))
                {
                    m_TextBox.Attributes.Add("maxLength", MaxLength.ToString(CultureInfo.CurrentCulture));
                }
                m_TextBox.RenderControl(writer);

                if (LengthInfoEnabled)
                {
                    string lengthInfoStringFormat = ((MaxLength > 0) ? Resources.TextBox_LengthInfoStringFormat2 : Resources.TextBox_LengthInfoStringFormat1);
                    writer.Write("<br />");
                    m_Span.RenderControl(writer);
                    writer.Write(string.Format(CultureInfo.CurrentCulture, " " + lengthInfoStringFormat, MaxLength));
                }
            }

            if (this.Theme != MasterPageTheme.Modern)
            {
                BaseValidatedControl.RenderValidatedControlMiddleTag(renderSecondRow, writer);
            }

            this.RenderValidators(writer);

            if (this.Theme != MasterPageTheme.Modern)
            {
                BaseValidatedControl.RenderValidatedControlEndTag(renderSecondRow, writer);
            }
        }
Ejemplo n.º 15
0
        public string printListingForParkWide(int duration)
        {
            string accessible = Accessible == 0 ? "No" : "Yes";
            string utilities  = Utilities == 0 ? "N/A" : "Yes";
            string rvLength   = MaxLength == 0 ? "N/A" : MaxLength.ToString();

            decimal totalCost = duration * CostPerDay;

            return(CampgroundName.ToString().PadRight(15) + SiteId.ToString().PadRight(15) + MaxOccupancy.ToString().PadRight(15) + accessible.PadRight(12) + rvLength.PadRight(10) + utilities.PadRight(12) + $"{totalCost:C}");
        }
Ejemplo n.º 16
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Controls.Clear();
/* ignore validation if control **NOT** enabled */
            if (!this.Enabled)
            {
                return;
            }
/* add RequiredFieldValidator */
            if (required)
            {
                _rfv = ControlFactory.GetRequiredValidator(
                    this.ID, this.ValidationGroup
                    );
                Controls.Add(_rfv);
            }
/* add RegularExpressionValidator */
            if (!String.IsNullOrEmpty(regex))
            {
                addRegexValidator();
            }

/*
 * client-side JavaScript character counter; **MUST** edit plugin file
 * to call on all server control(s)
 */
            if (TextMode == TextBoxMode.MultiLine && MaxLength > 0)
            {
                Attributes.Add(ControlFactory.MAXLENGTH_ATTR, MaxLength.ToString());
                Type cstype            = this.GetType();
                ClientScriptManager cs = Page.ClientScript;
// verify web.config <appSettings> keys exist
                if (!string.IsNullOrEmpty(_jsPath))
                {
                    if (!cs.IsClientScriptBlockRegistered(cstype, _jsPath))
                    {
                        Literal l = new Literal()
                        {
                            Text = String.Format(StringFormat.TAG_SCRIPT, _jsPath)
                        };
                        Page.Header.Controls.Add(l);
                        cs.RegisterClientScriptBlock(cstype, _jsPath, "");
                    }
                }
            }

/* add CompareValidator */
            AddCompareValidator();
/* client-side validation => ValidationGroup */
            if (ValidationGroup != String.Empty)
            {
                Attributes.Add(ControlFactory.VALIDATION_GROUP_ATTR, ValidationGroup);
            }
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Used to populate ListView
 /// </summary>
 /// <returns></returns>
 public string[] ItemArray()
 {
     return(new[]
     {
         Name,
         SystemType.ToString(),
         MaxLength.ToString(),
         Precision.ToString(),
         Scale.ToString()
     });
 }
        override protected void OnPreRender(EventArgs e)
        {
            // Ensure default work takes place
            base.OnPreRender(e);

            // Configure TextArea support
            if ((TextMode == TextBoxMode.MultiLine) && (MaxLength > 0))
            {
                // If we haven't already, include the supporting
                // script that limits the content of textareas.
                foreach (var script in ScriptIncludes)
                {
                    var scriptManager = ScriptManager.GetCurrent(Page);

                    if (scriptManager == null)
                    {
                        continue;
                    }

                    var absolutePath = VirtualPathUtility.ToAbsolute(script);

                    scriptManager.Scripts.Add(new ScriptReference(absolutePath));
                }

                // Add an expando attribute to the rendered control which sets  its maximum length (using the MaxLength Attribute)

                /* Where there is a ScriptManager on the parent page, use it to register the attribute -
                 * to ensure the control works in partial updates (like an AJAX UpdatePanel)*/

                var current = ScriptManager.GetCurrent(Page);
                if (current != null && (current.GetRegisteredExpandoAttributes().All(rea => rea.ControlId != ClientID)))
                {
                    ScriptManager.RegisterExpandoAttribute(this, ClientID, _maxLengthAttributeName,
                                                           MaxLength.ToString(CultureInfo.InvariantCulture), true);
                }
                else
                {
                    try
                    {
                        Page.ClientScript.RegisterExpandoAttribute(ClientID, _maxLengthAttributeName,
                                                                   MaxLength.ToString(CultureInfo.InvariantCulture));
                    }
                    catch (ArgumentException)
                    {
                        // This occurs if a script with this key has already been registered. The response should be to do nothing.
                    }
                }

                // Now bind the onkeydown, oninput and onpaste events to script to inject in parent page.
                Attributes.Add("onkeydown", "javascript:return LimitInput(this, event);");
                Attributes.Add("oninput", "javascript:return LimitInput(this, event);");
                Attributes.Add("onpaste", "javascript:return LimitPaste(this, event);");
            }
        }
Ejemplo n.º 19
0
        public bool MaxLength_IsValid(string propertyValue, int maxLength)
        {
            //Create Validator
            var validator = new MaxLength <Contact>(maxLength);
            RuleValidatorContext <Contact, string> context = BuildContextForLength(propertyValue);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return(validator.Validate(context, null, notification));
        }
Ejemplo n.º 20
0
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);
            RenderFieldHeader(context, output);

            var id = GetDomId();

            output.Content.AppendHtml("<textarea data-target=\"aiplugs-textarea.textarea\" data-action=\"keydown->aiplugs-textarea#updateHeight\" data-val=\"true\"");

            if (id != null)
            {
                output.Content.AppendHtml($"id=\"{id}\"");
            }

            if (Name != null)
            {
                output.Content.AppendHtml($"name=\"{Name}\"");
            }

            if (Placeholder != null)
            {
                output.Content.AppendHtml($"placeholder=\"{Placeholder}\"");
            }

            if (Required)
            {
                output.Content.AppendHtml($"required data-val-required=\"{Localizer[SharedResource.VAL_MSG_REQUIRED, Label]}\"");
            }

            if (!string.IsNullOrEmpty(Pattern))
            {
                var message = !string.IsNullOrEmpty(PatternErrorMessage) ? PatternErrorMessage : Localizer.MsgValPattern(Label, Pattern);
                output.Attr("data-val-regex", message);
                output.Attr("data-val-regex-pattern", Pattern);
            }

            if (MaxLength.HasValue)
            {
                output.Attr("data-val-maxlength", Localizer.MsgValMaxLengthForString(Label, MaxLength.Value));
                output.Attr("data-val-maxlength-max", MaxLength.ToString());
            }

            if (MinLength.HasValue)
            {
                output.Attr("data-val-minlength", Localizer.MsgValMinLengthForString(Label, MinLength.Value));
                output.Attr("data-val-minlength-min", MinLength.ToString());
            }

            output.Content.AppendHtml(">");
            output.Content.Append(Value ?? "");
            output.Content.AppendHtml("</textarea>");

            RenderFieldFooter(context, output, Name);
        }
Ejemplo n.º 21
0
 /// <summary>
 /// 最大多数のサーバーバリデーション時のエラーメッセージ取得
 /// </summary>
 /// <param name="displayName">表示名称(DisplayNameアトリビュートで変更できる)</param>
 /// <returns>必須エラーメッセージ</returns>
 string GetOverMaxErrorMessage(string displayName)
 {
     if (string.IsNullOrEmpty(OverMaxErrorMessage))
     {
         return(displayName + "の値が最大値「" + MaxLength.ToString() + "」を超えています。");
     }
     else
     {
         return(OverMaxErrorMessage);
     }
 }
Ejemplo n.º 22
0
        public XElement ToXml()
        {
            var config = new XElement("Rule");

            SourceBuildings.ToXml(config);
            TargetBuildings.ToXml(config);
            UseSize.ToXml(config);
            MaxLength.ToXml(config);
            MaxWidth.ToXml(config);

            return(config);
        }
Ejemplo n.º 23
0
        private string ValidateModels(StorageContext context, IEnumerable <PropertyInfo> storageSets)
        {
            string error = null;

            foreach (PropertyInfo storeageSetProp in storageSets)
            {
                object       storeageSet = storeageSetProp.GetValue(context);
                PropertyInfo listProp    = storeageSet.GetType().GetProperty(StorageManagerUtil.List, StorageManagerUtil.Flags);
                object       list        = listProp.GetValue(storeageSet);
                MethodInfo   method      = list.GetType().GetMethod(StorageManagerUtil.GetEnumerator);
                IEnumerator  enumerator  = (IEnumerator)method.Invoke(list, new object[] { });
                while (enumerator.MoveNext())
                {
                    object model = enumerator.Current;
                    foreach (PropertyInfo prop in model.GetType().GetProperties())
                    {
                        if (Attribute.IsDefined(prop, typeof(Required)))
                        {
                            object value = prop.GetValue(model);
                            if (value == null)
                            {
                                error =
                                    $"{model.GetType().FullName}.{prop.Name} is a required field. SaveChanges() has been terminated.";
                                break;
                            }
                        }

                        if (Attribute.IsDefined(prop, typeof(MaxLength)))
                        {
                            MaxLength maxLength = (MaxLength)Attribute.GetCustomAttribute(prop, typeof(MaxLength));
                            object    value     = prop.GetValue(model);
                            if (value != null)
                            {
                                string str = value.ToString();
                                if (str.Length > maxLength.length)
                                {
                                    error =
                                        $"{model.GetType().FullName}.{prop.Name} length is longer than {maxLength.length}. SaveChanges() has been terminated.";
                                    break;
                                }
                            }
                        }
                    }

                    if (error != null)
                    {
                        break;
                    }
                }
            }

            return(error);
        }
Ejemplo n.º 24
0
        public bool MaxLength_Expression_IsValid(string firstName, string lastName)
        {
            //Create Validator
            //FirstName Length must be at least the same length as the LastName
            var validator = new MaxLength <Contact>(c => (int)(c.LastName.Length));
            RuleValidatorContext <Contact, string> context = BuildContextForLength(firstName, lastName);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return(validator.Validate(context, null, notification));
        }
Ejemplo n.º 25
0
 protected override void OnPreRender(EventArgs e)
 {
     if (MaxLength > 0)
     {
         Attributes.Add("onkeypress", "LimitInput(this)");
         Attributes.Add("onbeforepaste", "doBeforePaste(this)");
         Attributes.Add("onpaste", "doPaste(this)");
         Attributes.Add("onmousemove", "LimitInput(this)");
         Attributes.Add("maxLength", MaxLength.ToString());
     }
     base.OnPreRender(e);
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Performs additional custom processes when writing customized attributes for html object in xsl template.
        /// </summary>
        /// <param name="writer">The XmlWriter to which you want to save xsl template.</param>
        protected override void OnWriteCustomAttributes(System.Xml.XmlWriter writer)
        {
            base.OnWriteCustomAttributes(writer);

            // "maxlength" attribute
            writer.WriteAttributeString("maxlength", MaxLength.ToString());

            // "readonly" attribute
            if (ReadOnly)
            {
                writer.WriteAttributeString("readonly", "readonly");
            }
        }
Ejemplo n.º 27
0
        public void RenderInput(TagHelperContext context, TagHelperOutput output, string name, string value = null, bool target = true)
        {
            output.Tag("input", () => {
                output.Attr("type", "checkbox");
                output.Attr("data-val", "true");

                if (value != null)
                {
                    output.Attr("value", value);
                }

                if (Pattern != null)
                {
                    var message = !string.IsNullOrEmpty(PatternErrorMessage) ? PatternErrorMessage : Localizer.MsgValPattern(Label, Pattern);
                    output.Attr("data-val-regex", message);
                    output.Attr("data-val-regex-pattern", Pattern);
                }

                if (MaxLength.HasValue)
                {
                    output.Attr("data-val-maxcount", Localizer.MsgValMaxLengthForArray(Label, MaxLength.Value));
                    output.Attr("data-val-maxcount-max", MaxLength.ToString());
                }

                if (MinLength.HasValue)
                {
                    output.Attr("data-val-mincount", Localizer.MsgValMinLengthForArray(Label, MinLength.Value));
                    output.Attr("data-val-mincount-min", MinLength.ToString());
                }

                if (!MinLength.HasValue && Required)
                {
                    output.Attr("data-val-mincount", Localizer.MsgValRequired(Label));
                    output.Attr("data-val-mincount-min", "1");
                }

                if (target)
                {
                    if (name != null)
                    {
                        output.Attr("name", name);
                    }
                    output.Attr("data-target", "aiplugs-tag-item.input");
                    output.Html(" checked ");
                }
                else
                {
                    output.Attr("class", "aiplugs-tag__dummy val-ignore");
                }
            });
        }
Ejemplo n.º 28
0
        public bool Equals(DataType other)
        {
            if (object.ReferenceEquals(other, null))
            {
                return(false);
            }

            if ((RefName != null) && (other.RefName != null))
            {
                return(RefName.Equals(other.RefName));
            }

            return(Type.Equals(other.Type) && MaxLength.Equals(other.MaxLength));
        }
Ejemplo n.º 29
0
      public string ToDisplayString()
      {
         string nullable = Required ? string.Empty : "?";
         string initial = !string.IsNullOrEmpty(InitialValue) ? $" = {InitialValue.Trim('"')}" : string.Empty;

         string lengthDisplay = "";

         if (MinLength > 0)
            lengthDisplay = $"[{MinLength}-{(MaxLength > 0 ? MaxLength.ToString() : "")}]";
         else if (MaxLength > 0)
            lengthDisplay = $"[{MaxLength}]";

         return $"{Name}: {Type}{nullable}{lengthDisplay}{initial}";
      }
Ejemplo n.º 30
0
        /// <summary>
        /// Returns the hash code for this object.
        /// </summary>
        /// <returns>A hash code for the current object.</returns>
        public override int GetHashCode()
        {
            int hashCode = -1182503711;

            hashCode = hashCode * -1521134295 + base.GetHashCode();
            hashCode = hashCode * -1521134295 + OrdinalPosition.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(ColumnDefault);

            hashCode = hashCode * -1521134295 + IsNullable.GetHashCode();
            hashCode = hashCode * -1521134295 + EqualityComparer <string> .Default.GetHashCode(DataType);

            hashCode = hashCode * -1521134295 + MaxLength.GetHashCode();
            hashCode = hashCode * -1521134295 + NumericPrecision.GetHashCode();
            return(hashCode);
        }
Ejemplo n.º 31
0
        public bool MaxLength_Expression_IsValid(string firstName, string lastName)
        {
            //Create Validator
            //FirstName Length must be at least the same length as the LastName
            var validator = new MaxLength<Contact>(c => (int)(c.LastName.Length));
            RuleValidatorContext<Contact, string> context = BuildContextForLength(firstName, lastName);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return validator.Validate(context, null, notification);
        }
Ejemplo n.º 32
0
        public bool MaxLength_IsValid(string propertyValue, int maxLength)
        {
            //Create Validator
            var validator = new MaxLength<Contact>(maxLength);
            RuleValidatorContext<Contact, string> context = BuildContextForLength(propertyValue);

            var notification = new ValidationNotification();

            //Validate the validator only, return true of no error returned
            return validator.Validate(context, null, notification);
        }
Ejemplo n.º 33
0
 static public string Parse(MaxLength value)
 {
     switch (value)
     {
         case MaxLength.All: return "-1 (all) for calling range";
         case MaxLength.One: return "1 (single character) for text length";
         case MaxLength.Zero: return "0 for text length";
         case MaxLength.MinusTwo: return "-2 (error) for text length)";
         case MaxLength.Length: return "actual length of calling range";
         case MaxLength.RandomWithinValidSize: return "RANDOM size <= actual size";
         case MaxLength.RandomOutsideValidSize: return "RANDOM size > actual size";
         case MaxLength.MaxInt: return "max Integer value";
         case MaxLength.NegativeMaxInt: return "negative max Integer value";
         default:
             throw new ArgumentException("Parse() has no support for " + ParseType(value));
     }
 }
Ejemplo n.º 34
0
        //---------------------------------------------------------------------------
        // Helper for GetText() test cases
        //---------------------------------------------------------------------------
        internal void GetTextHelper(SampleText sampleText, TargetRangeType callingRangeType, MaxLength maxLengthType, GetResult getResult, Type expectedException)
        {
            int maxLength = 0;
            string actualText = "";
            string expectedText = "";
            TextPatternRange callingRange;

            // Pre-Condition Verify text is expected value <<sampleText>> 
            TS_SetText(sampleText, out expectedText, CheckType.IncorrectElementConfiguration);

            // Pre-Condition Create calling range = <<callingRangeType>>
            TS_CreateRange(out callingRange, callingRangeType, null, false, CheckType.Verification);

            // Pre-Condition Determine length of text to get = <<maxLength>>
            TS_CalcMaxLength(maxLengthType, out maxLength, expectedText);

            // Call GetText(<<maxLength>>) <<expectedException>>
            TS_GetText(callingRange, ref actualText, maxLength, expectedException, CheckType.Verification);

            // Validate text is <<getResult>>
            TS_VerifyTextLength(getResult, actualText, expectedText, maxLength, expectedException, CheckType.Verification);
        }
Ejemplo n.º 35
0
        static internal void TS_CalcMaxLength(MaxLength lengthType, out int maxLength, string actualText)
        {
            maxLength = actualText.Length; // default to actual length

            // Calculate max length
            switch (lengthType)
            {
                case MaxLength.All:                         // -1 (all) for calling range
                    maxLength = -1;
                    break;
                case MaxLength.Zero:                        // 0 for text length
                    maxLength = 0;
                    break;
                case MaxLength.MinusTwo:                    // -2 (error) for text length)
                    maxLength = -2;
                    break;
                case MaxLength.Length:                      // actual length of calling range
                    maxLength = actualText.Length;
                    break;
                case MaxLength.RandomWithinValidSize:       // RANDOM size <= actual size
                    maxLength = (int)Helpers.RandomValue(1, maxLength);
                    break;
                case MaxLength.RandomOutsideValidSize:      // RANDOM size > actual size
                    maxLength = (int)Helpers.RandomValue(maxLength + 3, Int32.MaxValue);
                    break;
                case MaxLength.MaxInt:                      // max Integer value
                    maxLength = Int32.MaxValue;
                    break;
                case MaxLength.NegativeMaxInt:                   // negative max Integer value
                    maxLength = Int32.MinValue;
                    break;
                case MaxLength.One:                         // 1 (single chracter) for text length
                    maxLength = 1;
                    break;
                default:
                    throw new ArgumentException("TS_CalcMaxLength() has no support for " + ParseType(lengthType));
            }

            Comment("maxLength value to use in GetText() is = " + maxLength);
            m_TestStep++;
        }
Ejemplo n.º 36
0
 /// ---------------------------------------------------------------------------
 /// <summary>Parses values for enum</summary>
 /// ---------------------------------------------------------------------------
 static public string ParseType(MaxLength value)
 {
     return ParseType(value.GetType().ToString(), value.ToString());
 }