public static void ValidateFor <TModel, TProperty>(
     this HtmlHelper <TModel> htmlHelper,
     Expression <Func <TModel, TProperty> > expression
     )
 {
     ValidationExtensions.ValidateFor(htmlHelper, expression);
 }
Beispiel #2
0
        //Kiểm tra object truyền vào có tên trùng trong database không
        //KQ: false: TenTacGia bị trùng, true: cập nhật thành công
        public ResponseDetails UpdateTheLoai(TheLoai theLoai)
        {
            /*Bắt lỗi ký tự đặc biệt*/
            if (ValidationExtensions.isSpecialChar(theLoai.TenTheLoai))
            {
                return(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Error,
                    Message = "Không được chứa ký tự đặc biệt",
                    Value = theLoai.TenTheLoai.ToString()
                });
            }
            /*End*/

            /*Bắt lỗi [Tên thể loại]*/
            if (FindByCondition(t => t.TenTheLoai.Equals(theLoai.TenTheLoai) && t.TheLoaiID != theLoai.TheLoaiID).Any())
            {
                return(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Error,
                    Message = "Tên thể loại bị trùng",
                    Value = theLoai.TenTheLoai
                });
            }
            /*End*/

            Update(theLoai);
            return(new ResponseDetails()
            {
                StatusCode = ResponseCode.Success, Message = "Sửa thể loại thành công"
            });
        }
        private void Validate(ModelStateDictionary modelstate, CreateTwoFactorModel model, IdentityUser user)
        {
            if (model.Type == TwoFactorType.EmailCode)
            {
                if (string.IsNullOrEmpty(model.DataEmail))
                {
                    modelstate.AddModelError("DataEmail", Resources.TwoFactor.ErrorMessageEmailRequired);
                }

                if (model.DataEmail.Equals(user.Email, StringComparison.OrdinalIgnoreCase))
                {
                    ModelState.AddModelError("DataEmail", Resources.TwoFactor.ErrorMessageEmailNotAllowed);
                }

                if (!ValidationExtensions.IsValidEmailAddress(model.DataEmail))
                {
                    modelstate.AddModelError("DataEmail", string.Format(Resources.TwoFactor.ErrorMessageInvalidEmail, model.DataEmail));
                }
            }
            else if (model.Type == TwoFactorType.OtpCode)
            {
                if (string.IsNullOrEmpty(model.OtpData))
                {
                    modelstate.AddModelError("", Resources.TwoFactor.ErrorMessageOtpUnknown);
                }
            }
            else if (model.Type == TwoFactorType.PinCode)
            {
                if (model.DataPin.Length < 4 || model.DataPin.Length > 8)
                {
                    modelstate.AddModelError("DataPin", Resources.TwoFactor.ErrorMessagePinValidation);
                }
            }
        }
Beispiel #4
0
        public bool Contains(HttpRequestMethod method, string path)
        {
            ValidationExtensions.ThrowIfNull(method, nameof(method));
            ValidationExtensions.ThrowIfNullOrEmpty(path, nameof(path));

            return(this.routingTable.ContainsKey(method) && this.routingTable[method].ContainsKey(path));
        }
Beispiel #5
0
        public Func <IHttpRequest, IHttpResponse> Get(HttpRequestMethod method, string path)
        {
            ValidationExtensions.ThrowIfNull(method, nameof(method));
            ValidationExtensions.ThrowIfNullOrEmpty(path, nameof(path));

            return(this.routingTable[method][path]);
        }
 public HttpHeader(string key, string value)
 {
     ValidationExtensions.ThrowIfNullOrEmpty(key, nameof(key));
     ValidationExtensions.ThrowIfNullOrEmpty(value, nameof(value));
     this.Key   = key;
     this.Value = value;
 }
Beispiel #7
0
        //Kiểm tra object truyền vào có tên trùng trong database không
        //KQ: false: TenTacGia bị trùng, true: cập nhật thành công
        public ResponseDetails UpdateTacGia(TacGia tacGia)
        {
            /*Bắt lỗi ký tự đặc biệt*/
            if (ValidationExtensions.isSpecialChar(tacGia.TenTacGia))
            {
                return(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Error,
                    Message = "Không được chứa ký tự đặc biệt",
                    Value = tacGia.TenTacGia.ToString()
                });
            }
            /*End*/

            /*Bắt lỗi [Tên tác giả]*/
            if (FindByCondition(t => t.TenTacGia.Equals(tacGia.TenTacGia) && t.TacGiaID != tacGia.TacGiaID).Any())
            {
                return(new ResponseDetails()
                {
                    StatusCode = ResponseCode.Error,
                    Message = "Tên tác giả bị trùng",
                    Value = tacGia.TenTacGia
                });
            }
            /*End*/

            Update(tacGia);
            return(new ResponseDetails()
            {
                StatusCode = ResponseCode.Success, Message = "Sửa tác giả thành công"
            });
        }
        public static MvcHtmlString BootstrapEditorFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression)
        {
            MvcHtmlString label      = LabelExtensions.LabelFor(helper, expression, new { @class = "control-label col-xs-12 col-sm-4 col-md-3" });
            MvcHtmlString editor     = EditorExtensions.EditorFor(helper, expression, new { htmlAttributes = new { @class = "form-control" } });
            MvcHtmlString validation = ValidationExtensions.ValidationMessageFor(helper, expression, null, new { @class = "text-danger" });
            // Build the input elements
            TagBuilder editorDiv = new TagBuilder("div");

            editorDiv.AddCssClass("col-xs-4 col-sm-2 col-md-2 col-lg-1");
            editorDiv.InnerHtml = editor.ToString();
            // Build the validation message elements
            TagBuilder validationSpan = new TagBuilder("span");

            validationSpan.AddCssClass("help-block");
            validationSpan.InnerHtml = validation.ToString();
            TagBuilder validationDiv = new TagBuilder("div");

            validationDiv.AddCssClass("col-xs-12 col-md-8 col-sm-offset-4 col-md-offset-3");
            validationDiv.InnerHtml = validationSpan.ToString();
            // Combine all elements
            StringBuilder html = new StringBuilder();

            html.Append(label.ToString());
            html.Append(editorDiv.ToString());
            html.Append(validationDiv.ToString());
            // Build the outer div
            TagBuilder outerDiv = new TagBuilder("div");

            outerDiv.AddCssClass("form-group");
            outerDiv.InnerHtml = html.ToString();
            return(MvcHtmlString.Create(outerDiv.ToString()));
        }
Beispiel #9
0
        private async void btnSubmit_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            var caller = sender as Button;

            empAddContext.name  = empNameTxtBox.Text;
            empAddContext.email = empEmailTxtBox.Text;
            if (!ValidationExtensions.IsValidEmailFormat(empAddContext.email))
            {
                MessageBox.Show("Provided email is not in valid formate, please retry!");
                return;
            }

            empAddContext.gender = comboBox1.Text;
            empAddContext.status = comboBox2.Text;
            await commandInvoker.InvokeAsync(caller.Tag.ToString(), caller.Name.ToString());

            dataGridView1.DataSource = employeeViewModel.Employees;
            if (employeeViewModel.Employees.Count > 0)
            {
                empNameTxtBox.Text  = string.Empty;
                empEmailTxtBox.Text = string.Empty;
            }
            else
            {
                ErrorLabel.Text = "There has been some issue in saving the data, please read the log";
            }
        }
Beispiel #10
0
        public static MvcHtmlString JQM_TextBoxFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, InputConfig config = null, IDictionary <string, object> htmlAttributes = null)
        {
            TagBuilder tagResult = new TagBuilder("div");

            tagResult.MergeAttribute("class", "ui-field-contain");
            if (config == null || (config != null && string.IsNullOrEmpty(config.PlaceHolder)))
            {
                tagResult.InnerHtml += LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();
            }

            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary <string, object>();
            }

            if (config != null)
            {
                foreach (var item in config.GetAttributes())
                {
                    if (htmlAttributes.Count(p => p.Key == item.Key) == 0)
                    {
                        htmlAttributes.Add(item);
                    }
                }
            }
            tagResult.InnerHtml += InputExtensions.TextBoxFor(htmlHelper, expression, htmlAttributes).ToHtmlString();
            tagResult.InnerHtml += ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();
            return(tagResult.ToHtml());
        }
        private static bool ComponentIsAttached(Component context, Source source, Type type)
        {
            switch (source)
            {
            case Source.Local: return(context.GetComponent(type) != null);

            case Source.FromParents: return(context.GetComponentInParent(type) != null);

            case Source.FromChildren: return(context.GetComponentsInChildren(type) != null);

            case Source.Global
                when typeof(Object).IsAssignableFrom(type): return(Object.FindObjectsOfType(type) != null);

            case Source.Global: throw ValidationExtensions.NewGlobalDependencyIllegalTypeException(type, context);

            case Source.Anchor:
            {
                var anchor = context.GetComponentInParent <IAnchor>();
                if (anchor == null)
                {
                    return(false);
                }

                return(anchor.gameObject.GetComponentInChildren(type) != null);
            }

            default: throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #12
0
        protected override string RenderInput(Kooboo.CMS.Form.IColumn column)
        {
            var sb    = new StringBuilder();
            var input = string.Format("<input id=\"{0}\" name=\"{0}\"{3} type=\"{1}\" value=\"@(Model.{0} ==null ? \"\" : Model.{0}.ToLocalTime().ToString())\" {2}/>", column.Name, this.Type,
                                      ValidationExtensions.GetUnobtrusiveValidationAttributeString(column), column.AllowNull ? "" : " readonly=\"readonly\"");

            sb.Append(@"@if ((bool?)ViewContext.Controller.ViewData[""WebResourceUrl.Rendered""] != true)
            {
                ViewContext.Controller.ViewData[""WebResourceUrl.Rendered""] = true;");
            const string script = @"
                <script src=""@Kooboo.CMS.Toolkit.Controls.ControlsScript.GetWebResourceUrl()"" type=""text/javascript"" ></script>";
            const string css    = @"
                <link href=""@Kooboo.CMS.Toolkit.Controls.ControlsScript.GetDatetimeResourceUrl()"" type=""text/css"" rel=""stylesheet"" />";

            sb.Append(css);
            sb.Append(script);
            sb.Append("\t\t\t}");
            var func = String.Format(@"
                <script type='text/javascript'>
                    $(function() {{
                        $('input[name=""{0}""]').datetimepicker({{
                            showSecond: true,
                            timeFormat: 'HH:mm:ss'
                        }});
                    }});
                </script>", column.Name);

            sb.Append(func);
            sb.Append(input);
            return(sb.ToString());
        }
Beispiel #13
0
        public CreateUserValidator()
        {
            RuleFor(req => req.Nick)
            .NotEmpty()
            .MinimumLength(3)
            .MaximumLength(20)
            .Matches(RegularExpressions.Nick)
            .WithMessage(@"Nick must starts with the letter and can contains only letters and digits.");

            RuleFor(req => req.Login)
            .NotEmpty()
            .MinimumLength(19)
            .MaximumLength(20)
            .Must(a => ValidationExtensions.IsValidUnsignedLongValue(a))
            .WithMessage("Invalid value!");

            RuleFor(req => req.Password)
            .NotEmpty()
            .MinimumLength(19)
            .MaximumLength(20)
            .Must(a => ValidationExtensions.IsValidUnsignedLongValue(a))
            .WithMessage("Invalid value!");

            RuleFor(req => req.Email)
            .NotEmpty()
            .MinimumLength(19)
            .MaximumLength(20)
            .Must(a => ValidationExtensions.IsValidUnsignedLongValue(a))
            .WithMessage("Invalid value!");
        }
Beispiel #14
0
        public void AddParameter(string parameterName, object parameter)
        {
            ValidationExtensions.ThrowIfNullOrEmpty(parameterName, nameof(parameterName));
            ValidationExtensions.ThrowIfNull(parameter, nameof(parameter));

            this.sessionParameters[parameterName] = parameter;
        }
 public static MvcHtmlString ValidationMessageBootstrapFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression)
 {
     return(MvcHtmlString.Create(
                "<span class=\"help-inline\">" + Environment.NewLine +
                (ValidationExtensions.ValidationMessageFor(htmlHelper, expression) ?? MvcHtmlString.Empty).ToString() + Environment.NewLine +
                "</span>"
                ));
 }
Beispiel #16
0
        public HttpCookie GetCookie(string key)
        {
            ValidationExtensions.ThrowIfNullOrEmpty(key, nameof(key));

            // TODO: Validation for existing parameter (maybe throw exception)

            return(this.httpCookies[key]);
        }
Beispiel #17
0
 public CommandValidator(TotemContext dbContext)
 {
     RuleFor(m => m.Description).NotEmpty();
     RuleFor(m => m.ContractString).NotEmpty().StringMustBeValidContract();
     RuleFor(m => m.VersionNumber).NotEmpty().Must(BeAValidVersion).WithMessage("'Version Number' must follow semantic version system.");
     RuleFor(m => m).MustAsync((m, cancellationToken) => ValidationExtensions.IsUniqueContract(m.Id, m.VersionNumber, dbContext, cancellationToken))
     .WithMessage(m => $"Contract Id '{m.Id}' with Version '{m.VersionNumber}' already exist.");
 }
 public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, string message = null, string cssClass = null, string dir = null, string id = null, string lang = null, string style = null, string title = null)
 {
     return(ValidationExtensions.ValidationSummary(
                htmlHelper,
                message,
                SpanAttributes(cssClass, dir, id, lang, style, title)
                ));
 }
Beispiel #19
0
        public object GetParameter(string parameterName)
        {
            ValidationExtensions.ThrowIfNullOrEmpty(parameterName, nameof(parameterName));

            // TODO: Validation for existing parameter (maybe throw exception)

            return(this.sessionParameters[parameterName]);
        }
Beispiel #20
0
        public void Add(HttpRequestMethod method, string path, Func <IHttpRequest, IHttpResponse> func)
        {
            ValidationExtensions.ThrowIfNull(method, nameof(method));
            ValidationExtensions.ThrowIfNullOrEmpty(path, nameof(path));
            ValidationExtensions.ThrowIfNull(func, nameof(func));

            this.routingTable[method].Add(path, func);
        }
Beispiel #21
0
 public static MvcHtmlString ValidationMessageFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, string validationMessage = null, string cssClass = null, string dir = null, string id = null, string lang = null, string style = null, string title = null)
 {
     return(ValidationExtensions.ValidationMessageFor(
                htmlHelper,
                expression,
                validationMessage,
                SpanAttributes(cssClass, dir, id, lang, style, title)
                ));
 }
Beispiel #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyContext{TEntity, TProperty}"/> class.
 /// </summary>
 /// <param name="context">The validation context for the parent entity.</param>
 /// <param name="value">The property value.</param>
 /// <param name="name">The property name.</param>
 /// <param name="jsonName">The JSON property name.</param>
 /// <param name="text">The property text.</param>
 public PropertyContext(ValidationContext <TEntity> context, TProperty value, string name, string?jsonName = null, LText?text = null)
 {
     Parent      = Check.NotNull(context, nameof(context));
     Name        = Check.NotEmpty(name, nameof(name));
     JsonName    = jsonName ?? Name;
     UseJsonName = context.UseJsonNames;
     Text        = text ?? ValidationExtensions.ToSentenceCase(name) !;
     Value       = value;
 }
Beispiel #23
0
        public void AddCookie(HttpCookie httpCookie)
        {
            ValidationExtensions.ThrowIfNull(httpCookie, nameof(httpCookie));

            if (!httpCookies.ContainsKey(httpCookie.Key))
            {
                this.httpCookies.Add(httpCookie.Key, httpCookie);
            }
        }
Beispiel #24
0
        public static MvcHtmlString JQM_CheckBoxFor <TModel>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, bool> > expression, FlipswitchConfig config)
        {
            TagBuilder tagResult = new TagBuilder("div");

            tagResult.MergeAttribute("class", "ui-field-contain");
            config.Configuration.Add("data-role", "flipswitch");
            tagResult.InnerHtml += InputExtensions.CheckBoxFor <TModel>(htmlHelper, expression, config.GetAttributes()).ToHtmlString();
            tagResult.InnerHtml += ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();
            return(tagResult.ToHtml());
        }
Beispiel #25
0
        public static MvcHtmlString ZN_DropDownListFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, IEnumerable <SelectListItem> selectList, string optionLabel = null, object htmlAttributes = null)
        {
            TagBuilder tagResult = new TagBuilder("div");

            tagResult.MergeAttribute("class", "form-group");
            tagResult.InnerHtml += LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();
            tagResult.InnerHtml += System.Web.Mvc.Html.SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes).ToHtmlString();
            tagResult.InnerHtml += ValidationExtensions.ValidationMessageFor(htmlHelper, expression, "", new { @class = "error" }).ToHtmlString();
            return(tagResult.ToHtml());
        }
Beispiel #26
0
        public static MvcHtmlString ZN_PasswordFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, object htmlAttributes = null)
        {
            TagBuilder tagResult = new TagBuilder("div");

            tagResult.MergeAttribute("class", "form-group");
            tagResult.InnerHtml += LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();
            tagResult.InnerHtml += InputExtensions.PasswordFor(htmlHelper, expression, htmlAttributes).ToHtmlString();
            tagResult.InnerHtml += ValidationExtensions.ValidationMessageFor(htmlHelper, expression, "", new { @class = "error" }).ToHtmlString();
            return(tagResult.ToHtml());
        }
Beispiel #27
0
 public CommandValidator(TotemContext dbContext)
 {
     RuleFor(m => m.ModifiedContract.Id).NotEmpty().WithName("Id");
     RuleFor(m => m.ModifiedContract.Description).NotEmpty().WithName("Description");
     RuleFor(m => m.ModifiedContract.ContractString).NotEmpty().StringMustBeValidContract();
     RuleFor(m => m.ModifiedContract.VersionNumber).NotEmpty().WithName("Version Number").Must(BeAValidVersion).WithMessage("'Version Number' must follow semantic version system.");
     RuleFor(m => m).MustAsync((m, cancellationToken) =>
                               ValidationExtensions.IsUniqueContract(m.ModifiedContract.Id, m.ModifiedContract.VersionNumber, dbContext, cancellationToken))
     .WithMessage(m => $"Version {m.ModifiedContract.VersionNumber} is already in use by another contract.")
     .When(x => x.ModifiedContract.Id == x.InitialContract.Id && x.ModifiedContract.VersionNumber != x.InitialContract.VersionNumber);
 }
Beispiel #28
0
        public CreateRateValidator()
        {
            RuleFor(x => x.Value)
            .GreaterThanOrEqualTo(1)
            .LessThanOrEqualTo(5)
            .Must(x => ValidationExtensions.IsDivisibleByZeroCommaFive(x))
            .WithMessage("Value must be divisible by 0.5");

            RuleFor(x => x.Description)
            .MaximumLength(500);
        }
Beispiel #29
0
        public static LiteralTag ValidationMessage <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, string message)
        {
            var reqName = RequestData.GetName(ReflectionHelper.GetAccessor(expression));
            var val     = ValidationExtensions.ValidationMessage(htmlHelper, reqName, message);

            if (val != null)
            {
                return(new LiteralTag(val.ToHtmlString()));
            }
            return(new LiteralTag(""));
        }
Beispiel #30
0
        public Server(int port, IServerRoutingTable serverRoutingTable, IHttpSessionStorage sessionStorage)
        {
            ValidationExtensions.ThrowIfNull(serverRoutingTable, nameof(serverRoutingTable));
            ValidationExtensions.ThrowIfNull(sessionStorage, nameof(sessionStorage));

            this.port = port;
            this.serverRoutingTable = serverRoutingTable;
            this.sessionStorage     = sessionStorage;

            this.tcpListener = new TcpListener(IPAddress.Parse(LocalHostIpAddress), port);
        }