Example #1
0
        private void CreateTextEntry(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label, String placeholder, String value)
        {
            htmlTagBuilder.AppendLine($@"<label class=""col-md-2 control-label"" for=""{For.Name}"">{label}</label>");
            htmlTagBuilder.AppendLine($@"  <div class=""col-md-10"">");
            var helpProperty = GetHelp(attr);

            htmlTagBuilder.AppendLine($@"    <input class=""form-control"" name=""{For.Name}"" id=""{For.Name}"" placeholder=""{placeholder}"" value=""{value}"" ");

            if (attr.FieldType == FieldTypes.Hidden)
            {
                htmlTagBuilder.Append(@"type=""hidden"" ");
            }

            AddTextFieldTypeAttributes(htmlTagBuilder, attr, label);
            AddRequiredValidation(htmlTagBuilder, attr, label);
            AddMinMaxLengthValidation(htmlTagBuilder, attr, label);
            AddCompareToValidation(htmlTagBuilder, attr, label);
            AddNamespaceValiation(htmlTagBuilder, attr, label);

            htmlTagBuilder.AppendLine($@" />");

            htmlTagBuilder.AppendLine($@"    <span class=""text-danger field-validation-valid"" data-valmsg-replace=""true"" data-valmsg-for=""{For.Name}"" ></span>");

            if (!String.IsNullOrEmpty(helpProperty))
            {
                htmlTagBuilder.AppendLine($@"    <p class=""help-block"">{helpProperty}</p>");
            }

            htmlTagBuilder.AppendLine($@"  </div>");
        }
        public async Task IApiParameterAttributeTest()
        {
            var context = new TestActionContext(
                httpApi: null,
                httpApiConfig: new HttpApiConfig(),
                apiActionDescriptor: new ApiActionDescriptor(typeof(IMyApi).GetMethod("PostAsync")));

            context.RequestMessage.RequestUri = new Uri("http://www.webapi.com/");
            context.RequestMessage.Method     = HttpMethod.Post;

            var parameter = context.ApiActionDescriptor.Parameters[0].Clone("laojiu");
            IApiParameterAttribute attr = new FormFieldAttribute();
            await attr.BeforeRequestAsync(context, parameter);

            var body = await context.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("name=laojiu", body);

            // IgnoreWhenNull Test
            parameter = parameter.Clone(null);
            ((FormFieldAttribute)attr).IgnoreWhenNull = true;
            await attr.BeforeRequestAsync(context, parameter);

            body = await context.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("name=laojiu", body);
        }
        public async Task IApiActionAttributeTest()
        {
            var context = new ApiActionContext
            {
                RequestMessage = new HttpApiRequestMessage
                {
                    RequestUri = new Uri("http://www.mywebapi.com"),
                    Method     = HttpMethod.Post
                },
                ApiActionDescriptor = ApiDescriptorCache.GetApiActionDescriptor(typeof(IMyApi).GetMethod("PostAsync"))
            };

            var attr = new FormFieldAttribute("name", "laojiu");
            await attr.BeforeRequestAsync(context);

            var body = await context.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("name=laojiu", body);


            // IgnoreWhenNull Test
            var attr2 = new FormFieldAttribute("age", null)
            {
                IgnoreWhenNull = true
            };
            await attr2.BeforeRequestAsync(context);

            body = await context.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("name=laojiu", body);
        }
        public async Task IApiParameterAttributeTest()
        {
            var context = new ApiActionContext
            {
                RequestMessage = new HttpApiRequestMessage
                {
                    RequestUri = new Uri("http://www.mywebapi.com"),
                    Method     = HttpMethod.Post
                },
                ApiActionDescriptor = ApiDescriptorCache.GetApiActionDescriptor(typeof(IMyApi).GetMethod("PostAsync"))
            };

            var parameter = context.ApiActionDescriptor.Parameters[0];

            parameter.Value = "laojiu";

            IApiParameterAttribute attr = new FormFieldAttribute();
            await attr.BeforeRequestAsync(context, parameter);

            var body = await context.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("name=laojiu", body);

            // IgnoreWhenNull Test
            parameter.Value = null;
            ((FormFieldAttribute)attr).IgnoreWhenNull = true;
            await attr.BeforeRequestAsync(context, parameter);

            body = await context.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("name=laojiu", body);
        }
        public async Task IApiActionAttributeTest()
        {
            var context = new TestActionContext(
                httpApi: null,
                httpApiConfig: new HttpApiConfig(),
                apiActionDescriptor: new ApiActionDescriptor(typeof(IMyApi).GetMethod("PostAsync")));

            context.RequestMessage.RequestUri = new Uri("http://www.webapi.com/");
            context.RequestMessage.Method     = HttpMethod.Post;

            var attr = new FormFieldAttribute("name", "laojiu");
            await attr.BeforeRequestAsync(context);

            var body = await context.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("name=laojiu", body);


            // IgnoreWhenNull Test
            var attr2 = new FormFieldAttribute("age", null)
            {
                IgnoreWhenNull = true
            };
            await attr2.BeforeRequestAsync(context);

            body = await context.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("name=laojiu", body);
        }
Example #6
0
 private void CreateCheckBox(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label, String placeholder, String value)
 {
     htmlTagBuilder.AppendLine($@"<div class=""col-md-offset-2 col-md-10"">");
     htmlTagBuilder.AppendLine($@"  <div class=""checkbox"">");
     htmlTagBuilder.AppendLine($@"    <label for=""{For.Name}"">");
     htmlTagBuilder.AppendLine($@"      <input id=""{For.Name}"" name=""{For.Name}"" type=""checkbox"" value=""true"" />");
     htmlTagBuilder.AppendLine($@"       {label}");
     htmlTagBuilder.AppendLine($@"    </label>");
     htmlTagBuilder.AppendLine($@"  </div>");
     htmlTagBuilder.AppendLine($@"</div>");
 }
Example #7
0
 private String GetHelp(FormFieldAttribute attr)
 {
     if (!String.IsNullOrEmpty(attr.HelpResource))
     {
         var helpProperty = attr.ResourceType.GetProperty(attr.HelpResource, BindingFlags.Static | BindingFlags.Public);
         return((string)helpProperty.GetValue(helpProperty.DeclaringType, null));
     }
     else
     {
         return(null);
     }
 }
Example #8
0
 private static string GetLabel(FormFieldAttribute attr)
 {
     if (attr.ResourceType != null && !String.IsNullOrEmpty(attr.LabelDisplayResource))
     {
         var labelProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.LabelDisplayResource);
         return((labelProperty != null) ? (string)labelProperty.GetValue(labelProperty.DeclaringType, null) : (string)null);
     }
     else
     {
         return(null);
     }
 }
Example #9
0
        private void AddCompareToValidation(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label)
        {
            if (!String.IsNullOrEmpty(attr.CompareTo))
            {
                htmlTagBuilder.Append($@"data-val-equalto-other=""*.{attr.CompareTo}"" data-val=""true"" ");
                if (!String.IsNullOrEmpty(attr.CompareToMsgResource))
                {
                    var compareToMsgProperty = attr.ResourceType.GetProperty(attr.CompareToMsgResource, BindingFlags.Static | BindingFlags.Public);
                    var compareToMsg         = (string)compareToMsgProperty.GetValue(compareToMsgProperty.DeclaringType, null);

                    htmlTagBuilder.Append($@"data-val-equalto=""{compareToMsg}"" ");
                }
            }
        }
        public async Task OnRequestAsync()
        {
            var apiAction = new DefaultApiActionDescriptor(typeof(ITestApi).GetMethod("PostAsync"));
            var context   = new TestRequestContext(apiAction, string.Empty);

            context.HttpContext.RequestMessage.Method = HttpMethod.Post;

            var attr = new FormFieldAttribute("value", "laojiu");
            await attr.OnRequestAsync(context);

            var body = await context.HttpContext.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("value=laojiu", body);
        }
Example #11
0
        public async Task OnRequestAsync_Parameter()
        {
            var apiAction = new ApiActionDescriptor(typeof(ITestApi).GetMethod("PostAsync"));
            var context   = new TestRequestContext(apiAction, "laojiu");

            context.HttpContext.RequestMessage.Method = HttpMethod.Post;
            var parameterContext = new ApiParameterContext(context, 0);

            var attr = new FormFieldAttribute();
            await attr.OnRequestAsync(parameterContext, () => Task.CompletedTask);

            var body = await context.HttpContext.RequestMessage.Content.ReadAsStringAsync();

            Assert.Equal("value=laojiu", body);
        }
Example #12
0
        private static void ValidateProperty(FormFieldAttribute attr, ValidationResult result, IValidateable entity, PropertyInfo prop, Actions action)
        {
            var value = prop.GetValue(entity);

            if (prop.PropertyType == typeof(string))
            {
                ValidateString(result, prop, attr, value as String);
            }
            /// TODO: Find better approeach for detecting generic type entity headers.
            else if (prop.PropertyType.Name.StartsWith(nameof(EntityHeader))) /* YUCK! KDW 5/12/2017 */
            {
                ValidateEntityHeader(result, prop, attr, value as EntityHeader);
            }

            ValidateNumber(result, prop, attr, value);
        }
Example #13
0
        private void AddNamespaceValiation(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label)
        {
            if (attr.FieldType == FieldTypes.NameSpace)
            {
                htmlTagBuilder.Append(@"data-val-regex-pattern=""^[a-z0-9]{6,30}$"" ");
                htmlTagBuilder.Append($@"data-val-regex=""{Resources.CommonResources.Validation_RegEx_Namespace}"" ");

                /*  var namespaceMessageProperty = attr.ResourceType.GetProperty(attr.NamespaceUniqueMessageResource, BindingFlags.Static | BindingFlags.Public);
                 * if (namespaceMessageProperty != null)
                 * {
                 *    var namespaceMessage = (string)namespaceMessageProperty.GetValue(namespaceMessageProperty.DeclaringType, null);
                 *    htmlTagBuilder.Append($@"data-val-namespaceunique=""{namespaceMessage}"" ");
                 *    htmlTagBuilder.Append($@"data-val-namespaceunique-type=""{attr.NamespaceType.ToString().ToLower()}"" ");
                 * }*/
            }
        }
Example #14
0
 private void AddRequiredValidation(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label)
 {
     if (attr.IsRequired)
     {
         if (!String.IsNullOrEmpty(attr.RequiredMessageResource))
         {
             var validationProperty = attr.ResourceType.GetProperty(attr.RequiredMessageResource, BindingFlags.Static | BindingFlags.Public);
             var validationMessage  = (string)validationProperty.GetValue(validationProperty.DeclaringType, null);
             htmlTagBuilder.Append($@"data-val-required=""{validationMessage}"" data-val=""true"" ");
         }
         else
         {
             htmlTagBuilder.Append($@"data-val-required=""{Resources.CommonResources.Validation_Common_IsRequired.Replace("[FIELDNAME]", label)}"" data-val=""true"" ");
         }
     }
 }
Example #15
0
 private void AddMinMaxLengthValidation(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label)
 {
     if (attr.MinLength.HasValue && attr.MaxLength.HasValue)
     {
         var valMsg = CommonResources.Validation_Common_StringLength_MinMax.Replace("[FIELDNAME]", label).Replace("[MINLENGTH]", attr.MinLength.Value.ToString()).Replace("[MAXLENGTH]", attr.MaxLength.Value.ToString());
         htmlTagBuilder.Append($@"data-val-length-min=""{attr.MinLength.Value}"" data-val-length-max=""{attr.MaxLength.Value}"" data-val-length=""{valMsg}"" data-val=""true"" ");
     }
     else if (attr.MinLength.HasValue)
     {
         var valMsg = CommonResources.Validation_Common_StringLength_Min.Replace("[FIELDNAME]", label).Replace("[MINLENGTH]", attr.MinLength.Value.ToString());
         htmlTagBuilder.Append($@"data-val-length-min=""{attr.MinLength.Value}""  data-val-length=""{valMsg}"" data-val=""true"" ");
     }
     else if (attr.MaxLength.HasValue)
     {
         var valMsg = CommonResources.Validation_Common_StringLength_Max.Replace("[FIELDNAME]", label).Replace("[MAXLENGTH]", attr.MaxLength.Value.ToString());
         htmlTagBuilder.Append($@"data-val-length-max=""{attr.MaxLength.Value}"" data-val-length=""{valMsg}"" data-val=""true"" ");
     }
 }
Example #16
0
        private void AddTextFieldTypeAttributes(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label)
        {
            switch (attr.FieldType)
            {
            case FieldTypes.Password:
                htmlTagBuilder.Append(@"type=""password"" ");
                break;

            case FieldTypes.Email:
                htmlTagBuilder.Append(@"type=""text"" ");
                var valMsg = Resources.CommonResources.Validation_Common_InvalidEmailAddress.Replace("[FIELDNAME]", label);
                htmlTagBuilder.Append($@"data-val-email=""{valMsg}"" data-val=""true"" ");
                break;

            default:
                htmlTagBuilder.Append(@"type=""text"" ");
                break;
            }
        }
Example #17
0
        private void CreateMultiLineTextEntry(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label, String placeholder, String value)
        {
            htmlTagBuilder.AppendLine($@"<label class=""col-md-2 control-label"" for=""{For.Name}"">{label}</label>");
            htmlTagBuilder.AppendLine($@"  <div class=""col-md-10"">");
            var helpProperty = GetHelp(attr);

            htmlTagBuilder.AppendLine($@"    <textarea class=""form-control"" name=""{For.Name}"" id=""{For.Name}"" placeholder=""{placeholder}"" value=""{value}"" ");
            AddRequiredValidation(htmlTagBuilder, attr, label);
            htmlTagBuilder.AppendLine(@"></textarea>");

            htmlTagBuilder.AppendLine($@"    <span class=""text-danger field-validation-valid"" data-valmsg-replace=""true"" data-valmsg-for=""{For.Name}"" ></span>");

            if (!String.IsNullOrEmpty(helpProperty))
            {
                htmlTagBuilder.AppendLine($@"    <p class=""help-block"">{helpProperty}</p>");
            }

            htmlTagBuilder.AppendLine($@"  </div>");
        }
Example #18
0
        private void CreateOptionsList(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label, String placeholder, String value)
        {
            if (Items == null)
            {
                throw new Exception("Must provide a non-null value for Items if list type is OptionsList");
            }

            htmlTagBuilder.AppendLine($@"<label class=""col-md-2 control-label"" for=""{For.Name}"">{label}</label>");
            htmlTagBuilder.AppendLine($@"<div class=""col-md-10"">");
            htmlTagBuilder.AppendLine($@"  <select class=""form-control"" name=""{For.Name}"" id=""{For.Name}"" >");

            foreach (var option in Items)
            {
                htmlTagBuilder.AppendLine($@"  <option value=""{option.Key}"" >{option.Value}</option>");
            }
            htmlTagBuilder.AppendLine($@"  </select>");

            htmlTagBuilder.AppendLine($@"</div>");
        }
Example #19
0
 private static void AddRequiredFieldMissingMessage(ValidationResult result, FormFieldAttribute attr, string propertyName)
 {
     if (!String.IsNullOrEmpty(attr.RequiredMessageResource) && attr.ResourceType != null)
     {
         var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RequiredMessageResource);
         var validationMessage  = (string)validationProperty.GetValue(validationProperty.DeclaringType, null);
         result.AddUserError(validationMessage);
     }
     else
     {
         var propertyLabel = GetLabel(attr);
         if (String.IsNullOrEmpty(propertyLabel))
         {
             result.AddSystemError(Resources.ValidationResource.Entity_Header_Null_System.Replace("[NAME]", propertyName));
         }
         else
         {
             result.AddUserError(Resources.ValidationResource.PropertyIsRequired.Replace("[PROPERTYLABEL]", propertyLabel));
         }
     }
 }
Example #20
0
        private static void ValidateString(ValidationResult result, PropertyInfo propertyInfo, FormFieldAttribute attr, String value)
        {
            var propertyLabel = GetLabel(attr);

            if (String.IsNullOrEmpty(propertyLabel))
            {
                propertyLabel = propertyInfo.Name;
            }

            if (String.IsNullOrEmpty(value) && attr.IsRequired)
            {
                var validationMessage = String.Empty;

                if (attr.FieldType == FieldTypes.Hidden)
                {
                    result.AddSystemError(Resources.ValidationResource.SystemMissingProperty.Replace("[PROPERTYNAME]", propertyInfo.Name));
                }
                else
                {
                    if (!String.IsNullOrEmpty(attr.RequiredMessageResource) && attr.ResourceType != null)
                    {
                        var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RequiredMessageResource);
                        result.AddUserError((string)validationProperty.GetValue(validationProperty.DeclaringType, null));
                    }
                    else if (!String.IsNullOrEmpty(attr.LabelDisplayResource))
                    {
                        validationMessage = Resources.ValidationResource.PropertyIsRequired.Replace("[PROPERTYLABEL]", propertyLabel);
                        result.AddUserError(validationMessage);
                    }
                    else
                    {
                        result.AddSystemError(Resources.ValidationResource.SystemMissingProperty.Replace("[PROPERTYNAME]", propertyInfo.Name));
                    }
                }
            }

            if (!String.IsNullOrEmpty(value))
            {
                if (attr.FieldType == FieldTypes.Key)
                {
                    var reEx = new Regex("^[a-z0-9]{3,30}$");
                    if (!reEx.Match(value).Success)
                    {
                        if (attr.ResourceType == null)
                        {
                            throw new Exception($"Building Metadata - Reg Ex Validation has a resource text, but no resource type on {attr.LabelDisplayResource} {attr.LabelDisplayResource}");
                        }

                        result.AddUserError(ValidationResource.Common_Key_Validation);
                    }
                }

                if (!String.IsNullOrEmpty(attr.RegExValidation))
                {
                    var reEx = new Regex(attr.RegExValidation);
                    if (!reEx.Match(value).Success)
                    {
                        if (attr.ResourceType == null)
                        {
                            throw new Exception($"Building Metadata - Reg Ex Validation has a resource text, but no resource type on {attr.LabelDisplayResource} {attr.LabelDisplayResource}");
                        }

                        var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RegExValidationMessageResource);
                        result.AddUserError((string)validationProperty.GetValue(validationProperty.DeclaringType, null));
                    }
                }



                if (attr.MinLength.HasValue && attr.MaxLength.HasValue)
                {
                    if (value.Length < attr.MinLength || value.Length > attr.MaxLength)
                    {
                        result.AddUserError(Resources.ValidationResource.ValueLength_Between.Replace("[PROPERTY]", propertyLabel).Replace("[MIN]", attr.MinLength.ToString()).Replace("[MAX]", attr.MaxLength.ToString()));
                    }
                }
                else if (attr.MaxLength.HasValue)
                {
                    if (value.Length > attr.MaxLength)
                    {
                        result.AddUserError(Resources.ValidationResource.ValueLength_TooLong.Replace("[PROPERTY]", propertyLabel).Replace("[MAX]", attr.MaxLength.ToString()));
                    }
                }
                else if (attr.MinLength.HasValue)
                {
                    if (value.Length < attr.MinLength)
                    {
                        result.AddUserError(Resources.ValidationResource.ValueLength_TooShort.Replace("[PROPERTY]", propertyLabel).Replace("[MIN]", attr.MinLength.ToString()));
                    }
                }
            }
        }
Example #21
0
 private static void ValidateNumber(ValidationResult result, PropertyInfo propertyInfo, FormFieldAttribute attr, object value)
 {
 }
Example #22
0
 private static void ValidateEntityHeader(ValidationResult result, PropertyInfo prop, FormFieldAttribute attr, EntityHeader value)
 {
     if (value != null && String.IsNullOrEmpty(value.Id) && !String.IsNullOrEmpty(value.Text))
     {
         result.AddSystemError(Resources.ValidationResource.Entity_Header_MissingId_System.Replace("[NAME]", prop.Name));
     }
     else if (value != null && String.IsNullOrEmpty(value.Text) && !String.IsNullOrEmpty(value.Id))
     {
         result.AddSystemError(Resources.ValidationResource.Entity_Header_MissingText_System.Replace("[NAME]", prop.Name));
     }
     else if (attr.IsRequired)
     {
         if (value == null || value.IsEmpty())
         {
             AddRequiredFieldMissingMessage(result, attr, prop.Name);
         }
     }
 }
Example #23
0
 private void CreatePicker(StringBuilder htmlTagBuilder, FormFieldAttribute attr, String label, String placeholder, String value)
 {
 }
Example #24
0
        public static FormField Create(String name, FormFieldAttribute attr)
        {
            var field = new FormField();

            if (!String.IsNullOrEmpty(attr.LabelDisplayResource))
            {
                if (attr.ResourceType == null)
                {
                    throw new Exception($"Building Metadata - label is defined, but Resource Type is not defined on {name} {attr.LabelDisplayResource}");
                }

                var labelProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.LabelDisplayResource);
                field.Label = (string)labelProperty.GetValue(labelProperty.DeclaringType, null);
            }

            field.IsRequired = attr.IsRequired;
            if (field.IsRequired)
            {
                if (!String.IsNullOrEmpty(attr.RequiredMessageResource))
                {
                    if (attr.ResourceType == null)
                    {
                        throw new Exception($"Building Metadata - required message is defined, but Resource Type is not defined on {name} {attr.LabelDisplayResource}");
                    }

                    var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RequiredMessageResource);
                    field.RequiredMessage = (string)validationProperty.GetValue(validationProperty.DeclaringType, null);
                }
                else
                {
                    field.RequiredMessage = ValidationResource.PropertyIsRequired.Replace(Tokens.PROPERTY_LABEL, field.Label);
                }
            }

            field.IsUserEditable = attr.IsUserEditable;
            field.FieldType      = attr.FieldType.ToString();
            field.Name           = name;
            field.MinLength      = attr.MinLength;
            field.MaxLength      = attr.MaxLength;
            field.IsEnabled      = true;

            field.Options = new List <EnumDescription>();
            if (attr.EnumType != null)
            {
                var values = Enum.GetValues(attr.EnumType);
                for (var idx = 0; idx < values.GetLength(0); ++idx)
                {
                    var value = values.GetValue(idx).ToString();

                    var enumMember = attr.EnumType.GetTypeInfo().DeclaredMembers.Where(mbr => mbr.Name == value.ToString()).FirstOrDefault();
                    var enumAttr   = enumMember.GetCustomAttribute <EnumLabelAttribute>();

                    field.Options.Add(EnumDescription.Create(enumAttr, value));
                }
            }

            if (attr.FieldType == FieldTypes.NameSpace)
            {
                field.RegEx        = @"^[a-z0-9]{6,30}$";
                field.RegExMessage = ValidationResource.Validation_RegEx_Namespace;
            }
            else if (attr.FieldType == FieldTypes.Key)
            {
                field.RegEx        = @"^[a-z0-9]{3,30}$";
                field.RegExMessage = ValidationResource.Common_Key_Validation;
            }
            else
            {
                field.RegEx = attr.RegExValidation;
                if (!String.IsNullOrEmpty(attr.RegExValidationMessageResource))
                {
                    if (attr.ResourceType == null)
                    {
                        throw new Exception($"Building Metadata - Reg Ex Validation has a resource nae, but no resource type on {name} {attr.LabelDisplayResource}");
                    }

                    var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RegExValidationMessageResource);
                    field.RegExMessage = (string)validationProperty.GetValue(validationProperty.DeclaringType, null);
                }
            }

            if (!String.IsNullOrEmpty(attr.WaterMark))
            {
                if (attr.ResourceType == null)
                {
                    throw new Exception($"Building Metadata - watermark is defined, but Resource Type is not defined on {name} {attr.WaterMark}");
                }

                var placeholderProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.WaterMark);
                field.Watermark = placeholderProperty == null ? String.Empty : (string)placeholderProperty.GetValue(placeholderProperty.DeclaringType, null);
            }

            if (!String.IsNullOrEmpty(attr.HelpResource))
            {
                if (attr.ResourceType == null)
                {
                    throw new Exception($"Building Metaata - watermark is defined, but Resource Type is not defined on {name} {attr.HelpResource}");
                }

                var helpProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.HelpResource);
                field.Help = helpProperty == null ? String.Empty : (string)helpProperty.GetValue(helpProperty.DeclaringType, null);
            }

            field.IsVisible = true;

            return(field);
        }
Example #25
0
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="attribute">表单字段的属性</param>
 public FormField(FormFieldAttribute attribute)
 {
     Attribute            = attribute;
     ValidationAttributes = new List <Attribute>();
     Value = null;
 }
Example #26
0
        public static FormField Create(String name, FormFieldAttribute attr, PropertyInfo property)
        {
            var field = new FormField();

            field.Name      = name;
            field.FieldType = attr.FieldType.ToString();

            if (!String.IsNullOrEmpty(attr.LabelDisplayResource))
            {
                if (attr.ResourceType == null)
                {
                    throw new Exception($"Building Metadata - label is defined, but Resource Type is not defined on {name} {attr.LabelDisplayResource}");
                }

                var labelProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.LabelDisplayResource);
                field.Label = (string)labelProperty.GetValue(labelProperty.DeclaringType, null);
            }

            if (field.FieldType == FormField.FieldType_ChildView)
            {
                field.FormFields = new Dictionary <string, FormField>();

                var childProperties = property.PropertyType.GetRuntimeProperties();
                foreach (var childProperty in childProperties)
                {
                    var fieldAttributes = childProperty.GetCustomAttributes <FormFieldAttribute>();
                    if (fieldAttributes.Any())
                    {
                        var camelCaseName = childProperty.Name.Substring(0, 1).ToLower() + childProperty.Name.Substring(1);
                        var childField    = FormField.Create(camelCaseName, fieldAttributes.First(), childProperty);
                        field.FormFields.Add(camelCaseName, childField);
                    }
                }
                return(field);
            }

            field.IsRequired = attr.IsRequired;
            if (field.IsRequired)
            {
                if (!String.IsNullOrEmpty(attr.RequiredMessageResource))
                {
                    if (attr.ResourceType == null)
                    {
                        throw new Exception($"Building Metadata - required message is defined, but Resource Type is not defined on {name} {attr.LabelDisplayResource}");
                    }

                    var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RequiredMessageResource);
                    field.RequiredMessage = (string)validationProperty.GetValue(validationProperty.DeclaringType, null);
                }
                else
                {
                    field.RequiredMessage = ValidationResource.PropertyIsRequired.Replace(Tokens.PROPERTY_LABEL, field.Label);
                }
            }

            field.IsUserEditable = attr.IsUserEditable;
            field.MinLength      = attr.MinLength;
            field.MaxLength      = attr.MaxLength;
            field.IsEnabled      = true;
            field.IsMarkDown     = attr.IsMarkDown;

            field.Options = new List <EnumDescription>();
            if (attr.EnumType != null)
            {
                var options = new List <EnumDescription>();
                var values  = Enum.GetValues(attr.EnumType);
                for (var idx = 0; idx < values.GetLength(0); ++idx)
                {
                    var value = values.GetValue(idx).ToString();

                    var enumMember = attr.EnumType.GetTypeInfo().DeclaredMembers.Where(mbr => mbr.Name == value.ToString()).FirstOrDefault();
                    var enumAttr   = enumMember.GetCustomAttribute <EnumLabelAttribute>();

                    if (enumAttr.IsActive)
                    {
                        options.Add(EnumDescription.Create(enumAttr, value, idx));
                    }
                }

                field.Options = options.OrderBy(opt => opt.SortOrder).ToList();
            }

            if (attr.FieldType == FieldTypes.NameSpace)
            {
                field.RegEx        = @"^[a-z][a-z0-9]{5,30}$";
                field.RegExMessage = ValidationResource.Validation_RegEx_Namespace;
            }
            else if (attr.FieldType == FieldTypes.Key)
            {
                field.RegEx        = @"^[a-z][a-z0-9]{2,50}$";
                field.RegExMessage = ValidationResource.Common_Key_Validation;
            }
            else
            {
                field.RegEx = attr.RegExValidation;
                if (!String.IsNullOrEmpty(attr.RegExValidationMessageResource))
                {
                    if (attr.ResourceType == null)
                    {
                        throw new Exception($"Building Metadata - Reg Ex Validation has a resource nae, but no resource type on {name} {attr.LabelDisplayResource}");
                    }

                    var validationProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.RegExValidationMessageResource);
                    field.RegExMessage = (string)validationProperty.GetValue(validationProperty.DeclaringType, null);
                }
            }

            if (!String.IsNullOrEmpty(attr.WaterMark))
            {
                if (attr.ResourceType == null)
                {
                    throw new Exception($"Building Metadata - watermark is defined, but Resource Type is not defined on {name} {attr.WaterMark}");
                }

                var placeholderProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.WaterMark);
                field.Watermark = placeholderProperty == null ? String.Empty : (string)placeholderProperty.GetValue(placeholderProperty.DeclaringType, null);
            }

            if (!String.IsNullOrEmpty(attr.HelpResource))
            {
                if (attr.ResourceType == null)
                {
                    throw new Exception($"Building Metaata - watermark is defined, but Resource Type is not defined on {name} {attr.HelpResource}");
                }

                var helpProperty = attr.ResourceType.GetTypeInfo().GetDeclaredProperty(attr.HelpResource);
                field.Help = helpProperty == null ? String.Empty : (string)helpProperty.GetValue(helpProperty.DeclaringType, null);
            }

            field.IsVisible = true;

            return(field);
        }