Example #1
0
        /// <include file='doc\ValidationSummary.uex' path='docs/doc[@for="ValidationSummary.AddAttributesToRender"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    AddAttributesToRender method.
        /// </devdoc>
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);

            if (renderUplevel)
            {
                // We always want validation cotnrols to have an id on the client, so if it's null, write it here.
                // Otherwise, base.RenderAttributes takes care of it.
                // REVIEW: this is a bit hacky.
                if (ID == null)
                {
                    writer.AddAttribute("id", ClientID);
                }

                if (HeaderText.Length > 0)
                {
                    writer.AddAttribute("headertext", HeaderText, true);
                }
                if (ShowMessageBox)
                {
                    writer.AddAttribute("showmessagebox", "True");
                }
                if (!ShowSummary)
                {
                    writer.AddAttribute("showsummary", "False");
                }
                if (DisplayMode != ValidationSummaryDisplayMode.BulletList)
                {
                    writer.AddAttribute("displaymode", PropertyConverter.EnumToString(typeof(ValidationSummaryDisplayMode), DisplayMode));
                }
            }
        }
Example #2
0
        static PropertyConverter[] GetPropertyConverters(Type type)
        {
            var props  = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var result = new PropertyConverter[props.Length];

            for (int i = 0, length = props.Length; i < length; ++i)
            {
                var prop = props[i];
                var attr = prop.GetCustomAttribute <JSONKeyAttribute>(true);
                var key  = attr != null ? attr.KeyName : prop.Name;
                var conv = GetConverter(prop.PropertyType);
                if (conv != null)
                {
                    result[i] = new PropertyConverter
                    {
                        Key         = key,
                        TryLower    = attr == null && Char.IsUpper(key[0]),
                        SetProperty = (value, obj) => prop.SetValue(obj, conv(value))
                    };
                }
                else // happens when the type definition has recursion
                {
                    var propConv = result[i] = new PropertyConverter();
                    propConv.Key         = key;
                    propConv.TryLower    = attr == null && Char.IsUpper(key[0]);
                    propConv.SetProperty = (value, obj) =>
                    {
                        var newConv = GetConverter(prop.PropertyType);
                        prop.SetValue(obj, newConv(value));
                        propConv.SetProperty = (value2, obj2) => prop.SetValue(obj2, newConv(value2));
                    };
                }
            }
            return(result);
        }
 protected override void AddAttributesToRender(HtmlTextWriter writer)
 {
     base.AddAttributesToRender(writer);
     if (base.RenderUplevel)
     {
         string         clientID = this.ClientID;
         HtmlTextWriter writer2  = base.EnableLegacyRendering ? writer : null;
         base.AddExpandoAttribute(writer2, clientID, "evaluationfunction", "CompareValidatorEvaluateIsValid", false);
         if (this.ControlToCompare.Length > 0)
         {
             string controlRenderID = base.GetControlRenderID(this.ControlToCompare);
             base.AddExpandoAttribute(writer2, clientID, "controltocompare", controlRenderID);
             base.AddExpandoAttribute(writer2, clientID, "controlhookup", controlRenderID);
         }
         if (this.ValueToCompare.Length > 0)
         {
             string valueToCompare = this.ValueToCompare;
             if (base.CultureInvariantValues)
             {
                 valueToCompare = base.ConvertCultureInvariantToCurrentCultureFormat(valueToCompare, base.Type);
             }
             base.AddExpandoAttribute(writer2, clientID, "valuetocompare", valueToCompare);
         }
         if (this.Operator != ValidationCompareOperator.Equal)
         {
             base.AddExpandoAttribute(writer2, clientID, "operator", PropertyConverter.EnumToString(typeof(ValidationCompareOperator), this.Operator), false);
         }
     }
 }
Example #4
0
        /// <include file='doc\CompareValidator.uex' path='docs/doc[@for="CompareValidator.ControlPropertiesValid"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para> Checks the properties of a the control for valid values.</para>
        /// </devdoc>
        protected override bool ControlPropertiesValid()
        {
            // Check the control id references
            if (ControlToCompare.Length > 0)
            {
                CheckControlValidationProperty(ControlToCompare, "ControlToCompare");

                if (string.Compare(ControlToValidate, ControlToCompare, true, CultureInfo.InvariantCulture) == 0)
                {
                    throw new HttpException(HttpRuntime.FormatResourceString(SR.Validator_bad_compare_control,
                                                                             ID,
                                                                             ControlToCompare));
                }
            }
            else
            {
                // Check Values
                if (Operator != ValidationCompareOperator.DataTypeCheck &&
                    !CanConvert(ValueToCompare, Type))
                {
                    throw new HttpException(
                              HttpRuntime.FormatResourceString(
                                  SR.Validator_value_bad_type,
                                  new string [] {
                        ValueToCompare,
                        "ValueToCompare",
                        ID,
                        PropertyConverter.EnumToString(typeof(ValidationDataType), Type),
                    }));
                }
            }
            return(base.ControlPropertiesValid());
        }
Example #5
0
        /// <summary>
        /// Get the JSON RPC response for the given HTTP request.
        /// </summary>
        /// <typeparam name="T">The type to deserialize the response result to.</typeparam>
        /// <param name="httpWebRequest">The web request.</param>
        /// <returns>A JSON RPC response with the result deserialized as the given type.</returns>
        private DaemonResponse <T> GetRpcResponse <T>(HttpWebRequest httpWebRequest)
        {
            try
            {
                string json = GetJsonResponse(httpWebRequest);

                // process response with converter. needed for all coin wallets which gives non-standard info.
                string jsonLC = PropertyConverter.DeserializeWithLowerCasePropertyNames(json).ToString();

                _logger.Verbose("rx: {0}", jsonLC.PrettifyJson());

                return(JsonConvert.DeserializeObject <DaemonResponse <T> >(jsonLC));
            }
            catch (RpcException rpcEx) {
                httpWebRequest = null;
                throw rpcEx;
            }
            catch (JsonException jsonEx)
            {
                httpWebRequest = null;
                throw new Exception("There was a problem deserializing the response from the coin wallet.", jsonEx);
            }
            catch (Exception exception)
            {
                httpWebRequest = null;
                throw _rpcExceptionFactory.GetRpcException("An unknown exception occured while reading json response.", exception);
            }
        }
Example #6
0
        public virtual string[] GetStringArray(string key)
        {
            string[] array;
            var      raw = GetProperty(key);

            if (raw is IList)
            {
                var rawList = (IList)raw;
                array = new string[rawList.Count];
                for (var i = 0; i < rawList.Count; ++i)
                {
                    array[i] = Interpolate(PropertyConverter.ToString(raw));
                }
            }
            else if (raw is string)
            {
                array = new[] { Interpolate((string)raw) };
            }
            else if (raw != null)
            {
                array = new[] { Interpolate(raw.ToString()) };
            }
            else
            {
                array = new string[0];
            }
            return(array);
        }
Example #7
0
        public void Convert_DepthLimitZero_ReturnsStructureToken()
        {
            var logger    = Mock.Of <ILogger>();
            var config    = new DefaultConversionConfig(logger);
            var converter = new PropertyConverter(config, logger);
            var value     = new Nested
            {
                Value = 1,
                Next  = new Nested
                {
                    Value = 10,
                    Next  = new Nested
                    {
                        Value = 100
                    }
                }
            };

            var structure = converter.Convert(value, 0) as StructureToken;

            Assert.NotNull(structure);
            Assert.Equal(2, structure.Properties.Count);
            Assert.Equal(nameof(Nested.Next), structure.Properties[0].Name);
            Assert.Equal(nameof(Nested.Value), structure.Properties[1].Name);

            var scalar = structure.Properties[0].Value as ScalarToken;

            Assert.NotNull(scalar);
            Assert.Null(scalar.Value);
        }
Example #8
0
        /// <internalonly/>
        /// <devdoc>
        ///    <para> Checks the properties of a the control for valid values.</para>
        /// </devdoc>
        protected override bool ControlPropertiesValid()
        {
            // Check the control id references
            if (ControlToCompare.Length > 0)
            {
                CheckControlValidationProperty(ControlToCompare, "ControlToCompare");

                if (StringUtil.EqualsIgnoreCase(ControlToValidate, ControlToCompare))
                {
                    throw new HttpException(SR.GetString(SR.Validator_bad_compare_control,
                                                         ID,
                                                         ControlToCompare));
                }
            }
            else
            {
                // Check Values
                if (Operator != ValidationCompareOperator.DataTypeCheck &&
                    !CanConvert(ValueToCompare, Type, CultureInvariantValues))
                {
                    throw new HttpException(
                              SR.GetString(SR.Validator_value_bad_type,
                                           new string [] {
                        ValueToCompare,
                        "ValueToCompare",
                        ID,
                        PropertyConverter.EnumToString(typeof(ValidationDataType), Type),
                    }));
                }
            }
            return(base.ControlPropertiesValid());
        }
Example #9
0
 public void EnumToString()
 {
     Assert.AreEqual(PropertyConverter.EnumToString(typeof(TestEnum), 1),
                     "Normal", "Normal");
     Assert.AreEqual(PropertyConverter.EnumToString(typeof(TestEnum), 25),
                     "25", "Decimal");
 }
Example #10
0
        /////////////////////////////////////////////////////////////////////
        // Helper function adopted from WebForms CompareValidator
        /////////////////////////////////////////////////////////////////////

        /// <include file='doc\CompareValidator.uex' path='docs/doc[@for="CompareValidator.ControlPropertiesValid"]/*' />
        protected override bool ControlPropertiesValid()
        {
            // Check the control id references
            if (ControlToCompare.Length > 0)
            {
                CheckControlValidationProperty(ControlToCompare, "ControlToCompare");
                if (String.Compare(ControlToValidate, ControlToCompare, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    throw new ArgumentException(SR.GetString(
                                                    SR.CompareValidator_BadCompareControl, ID, ControlToCompare));
                }
            }
            else
            {
                // Check Values
                if (Operator != ValidationCompareOperator.DataTypeCheck &&
                    !WebCntrls.BaseCompareValidator.CanConvert(ValueToCompare, Type))
                {
                    throw new ArgumentException(SR.GetString(
                                                    SR.Validator_ValueBadType,
                                                    ValueToCompare,
                                                    "ValueToCompare",
                                                    ID,
                                                    PropertyConverter.EnumToString(
                                                        typeof(ValidationDataType), Type)
                                                    ));
                }
            }
            return(base.ControlPropertiesValid());
        }
Example #11
0
        // <summary>
        //  AddAttributesToRender method
        // </summary>

        /// <internalonly/>
        /// <devdoc>
        ///    <para>Adds the attributes of this control to the output stream for rendering on the
        ///       client.</para>
        /// </devdoc>
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            if (RenderUplevel)
            {
                string         id = ClientID;
                HtmlTextWriter expandoAttributeWriter = (EnableLegacyRendering || IsUnobtrusive) ? writer : null;
                AddExpandoAttribute(expandoAttributeWriter, id, "evaluationfunction", "CompareValidatorEvaluateIsValid", false);
                if (ControlToCompare.Length > 0)
                {
                    string controlToCompareID = GetControlRenderID(ControlToCompare);
                    AddExpandoAttribute(expandoAttributeWriter, id, "controltocompare", controlToCompareID);
                    AddExpandoAttribute(expandoAttributeWriter, id, "controlhookup", controlToCompareID);
                }
                if (ValueToCompare.Length > 0)
                {
                    string valueToCompareString = ValueToCompare;
                    if (CultureInvariantValues)
                    {
                        valueToCompareString = ConvertCultureInvariantToCurrentCultureFormat(valueToCompareString, Type);
                    }
                    AddExpandoAttribute(expandoAttributeWriter, id, "valuetocompare", valueToCompareString);
                }
                if (Operator != ValidationCompareOperator.Equal)
                {
                    AddExpandoAttribute(expandoAttributeWriter, id, "operator", PropertyConverter.EnumToString(typeof(ValidationCompareOperator), Operator), false);
                }
            }
        }
Example #12
0
        public void TestObjectFromStringCantConvert()
        {
            MemberInfo mi = this.GetType().GetProperty("NotAllowedConverterProperty");

            PropertyConverter.ObjectFromString(typeof(int),               // can't be string
                                               mi, "foobar");
        }
        public string ToString(IFormatProvider formatProvider)
        {
            string str = string.Empty;

            if (this.IsEmpty)
            {
                return(str);
            }
            switch (this.type)
            {
            case FontSize.AsUnit:
                return(this.value.ToString(formatProvider));

            case FontSize.XXSmall:
                return("XX-Small");

            case FontSize.XSmall:
                return("X-Small");

            case FontSize.XLarge:
                return("X-Large");

            case FontSize.XXLarge:
                return("XX-Large");
            }
            return(PropertyConverter.EnumToString(typeof(FontSize), this.type));
        }
Example #14
0
 public void EnumToStringFlags()
 {
     Assert.AreEqual(PropertyConverter.EnumToString(typeof(TestFlags), 0),
                     "A", "A");
     Assert.AreEqual(PropertyConverter.EnumToString(typeof(TestFlags), 3),
                     "B, C", "Multiple");
 }
Example #15
0
        internal Control CreateControl()
        {
            Debug.Assert(FieldTemplate == null);

            FieldTemplate = (Control)IMetaColumn.Model.FieldTemplateFactory.CreateFieldTemplate(Column, Mode, UIHint);
            if (FieldTemplate != null)
            {
                ((IFieldTemplate)FieldTemplate).SetHost(this);

                // If we got some extra attributes declared on the tag, assign them to the user control if it has matching properties
                if (_attributes != null)
                {
                    var ucType = FieldTemplate.GetType();
                    foreach (var entry in _attributes)
                    {
                        // Look for a public property by that name on th user control
                        var propInfo = ucType.GetProperty(entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        if (propInfo != null)
                        {
                            // Convert the value to the type of the property and set it
                            var value = PropertyConverter.ObjectFromString(propInfo.PropertyType, propInfo, entry.Value);
                            propInfo.SetValue(FieldTemplate, value, null);
                        }
                    }
                }

                // Give it the column name as its ID, unless there is already a control by that name
                string id = GetControlIDFromColumnName(IMetaColumn.Name);
                if (FindControl(id) == null)
                {
                    FieldTemplate.ID = id;
                }
            }
            return(FieldTemplate);
        }
Example #16
0
        /// <summary>Enumerates get mappings in this collection.</summary>
        /// <returns>
        ///     An enumerator that allows foreach to be used to process get mappings in this collection.
        /// </returns>
        protected internal override IEnumerable <MemberMappingInfo <TSource, TTarget> > GetMappings()
        {
            PropertyConverter checker = GetPropertyConverter();

            return(from p in PropertyExplorer.GetMatches <TSource, TTarget>(checker.CanConvert)
                   select CreateInfo(p.Key, p.Value));
        }
        protected override void ConvertProperty(
            PropertyConverter propertyConverter, IPropertyDeclaration propertyDeclaration)
        {
            Argument.IsNotNull(() => propertyConverter);

            propertyConverter.Convert(propertyDeclaration);
        }
Example #18
0
        public static void Start(IApplicationBuilder app)
        {
            if (started)
            {
                return;
            }

            started = true;

            SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod());
            ReflectionServer.RegisterLike(typeof(QueryTokenEmbedded), () => UserAssetPermission.UserAssetsToXML.IsAuthorized() ||
                                          TypeAuthLogic.GetAllowed(typeof(UserQueryEntity)).MaxUI() > Entities.Authorization.TypeAllowedBasic.None ||
                                          TypeAuthLogic.GetAllowed(typeof(UserChartEntity)).MaxUI() > Entities.Authorization.TypeAllowedBasic.None
                                          );
            //EntityJsonConverter.DefaultPropertyRoutes.Add(typeof(QueryFilterEmbedded), PropertyRoute.Construct((UserQueryEntity e) => e.Filters.FirstEx()));
            //EntityJsonConverter.DefaultPropertyRoutes.Add(typeof(PinnedQueryFilterEmbedded), PropertyRoute.Construct((UserQueryEntity e) => e.Filters.FirstEx().Pinned));

            var pcs = PropertyConverter.GetPropertyConverters(typeof(QueryTokenEmbedded));

            pcs.Add("token", new PropertyConverter()
            {
                CustomWriteJsonProperty = ctx =>
                {
                    var qte = (QueryTokenEmbedded)ctx.Entity;

                    ctx.JsonWriter.WritePropertyName(ctx.LowerCaseName);
                    ctx.JsonSerializer.Serialize(ctx.JsonWriter, qte.TryToken == null ? null : new QueryTokenTS(qte.TryToken, true));
                },
                AvoidValidate          = true,
                CustomReadJsonProperty = ctx =>
                {
                    var result = ctx.JsonSerializer.Deserialize(ctx.JsonReader);
                    //Discard
                }
            });
            pcs.Add("parseException", new PropertyConverter()
            {
                CustomWriteJsonProperty = ctx =>
                {
                    var qte = (QueryTokenEmbedded)ctx.Entity;

                    ctx.JsonWriter.WritePropertyName(ctx.LowerCaseName);
                    ctx.JsonSerializer.Serialize(ctx.JsonWriter, qte.ParseException?.Message);
                },
                AvoidValidate          = true,
                CustomReadJsonProperty = ctx =>
                {
                    var result = ctx.JsonSerializer.Deserialize(ctx.JsonReader);
                    //Discard
                }
            });
            pcs.GetOrThrow("tokenString").CustomWriteJsonProperty = ctx =>
            {
                var qte = (QueryTokenEmbedded)ctx.Entity;

                ctx.JsonWriter.WritePropertyName(ctx.LowerCaseName);
                ctx.JsonWriter.WriteValue(qte.TryToken?.FullKey() ?? qte.TokenString);
            };
        }
 public ReadJsonPropertyContext(JsonSerializerOptions jsonSerializerOptions, PropertyConverter propertyConverter, ModifiableEntity entity, PropertyRoute parentPropertyRoute, EntityJsonConverterFactory factory)
 {
     JsonSerializerOptions = jsonSerializerOptions;
     PropertyConverter     = propertyConverter;
     Entity = entity;
     ParentPropertyRoute = parentPropertyRoute;
     Factory             = factory;
 }
Example #20
0
        /// <summary>
        /// Adds the HTML attributes and styles of a <see cref="T:System.Web.UI.WebControls.Label"/> control to render to the specified output stream.
        /// </summary>
        /// <param name="writer">An <see cref="T:System.Web.UI.HtmlTextWriter"/> that represents the output stream to render HTML content on the client.</param>
        /// <exception cref="T:System.Web.HttpException">The control specified in the <see cref="P:System.Web.UI.WebControls.Label.AssociatedControlID"/> property cannot be found.</exception>
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            bool flag = !Enabled;

            if (flag)
            {
                Enabled = true;
            }
            try
            {
                if (RenderUplevel)
                {
                    base.EnsureID();
                    string clientID = ClientID;
                    //HtmlTextWriter writer2 = base.EnableLegacyRendering ? writer : null;
                    HtmlTextWriter writer2 = writer;
                    if (ControlToValidate.Length > 0)
                    {
                        AddExpandoAttribute(writer2, clientID, "controltovalidate",
                                            GetControlRenderID(ControlToValidate));
                    }
                    if (SetFocusOnError)
                    {
                        AddExpandoAttribute(writer2, clientID, "focusOnError", "t", false);
                    }
                    if (ErrorMessage.Length > 0)
                    {
                        AddExpandoAttribute(writer2, clientID, "errormessage", ErrorMessage);
                    }
                    ValidatorDisplay enumValue = Display;
                    if (enumValue != ValidatorDisplay.Static)
                    {
                        AddExpandoAttribute(writer2, clientID, "display",
                                            PropertyConverter.EnumToString(typeof(ValidatorDisplay), enumValue), false);
                    }
                    if (!IsValid)
                    {
                        AddExpandoAttribute(writer2, clientID, "isvalid", "False", false);
                    }
                    if (flag)
                    {
                        AddExpandoAttribute(writer2, clientID, "enabled", "False", false);
                    }
                    if (ValidationGroup.Length > 0)
                    {
                        AddExpandoAttribute(writer2, clientID, "validationGroup", ValidationGroup);
                    }
                }
                base.AddAttributesToRender(writer);
            }
            finally
            {
                if (flag)
                {
                    Enabled = false;
                }
            }
        }
        /// <summary>
        ///		Adds the HTML attributes and styles that need to be rendered for the control to the specified <see cref='System.Web.UI.HtmlTextWriter'/> object.
        /// </summary>
        /// <param name="writer">A <see cref='System.Web.UI.HtmlTextWriter'/> that contains the output stream for rendering on the client.</param>
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            if (RenderUplevel)
            {
                WebControls.ValidationDataType type = Type;
                if (type != WebControls.ValidationDataType.String)
                {
                    string         id = ClientID;
                    HtmlTextWriter expandoAttributeWriter = (EnableLegacyRendering) ? writer : null;

                    AddExpandoAttribute(expandoAttributeWriter, id, "type", PropertyConverter.EnumToString(typeof(WebControls.ValidationDataType), type), false);

                    NumberFormatInfo info = NumberFormatInfo.CurrentInfo;
                    if (type == WebControls.ValidationDataType.Double)
                    {
                        string decimalChar = info.NumberDecimalSeparator;
                        AddExpandoAttribute(expandoAttributeWriter, id, "decimalchar", decimalChar);
                    }
                    else if (type == WebControls.ValidationDataType.Currency)
                    {
                        string decimalChar = info.CurrencyDecimalSeparator;
                        AddExpandoAttribute(expandoAttributeWriter, id, "decimalchar", decimalChar);

                        string groupChar = info.CurrencyGroupSeparator;
                        // Map non-break space onto regular space for parsing
                        if (groupChar[0] == 160)
                        {
                            groupChar = " ";
                        }
                        AddExpandoAttribute(expandoAttributeWriter, id, "groupchar", groupChar);

                        int digits = info.CurrencyDecimalDigits;
                        AddExpandoAttribute(expandoAttributeWriter, id, "digits", digits.ToString(NumberFormatInfo.InvariantInfo), false);

                        // VSWhidbey 83165
                        int groupSize = GetCurrencyGroupSize(info);
                        if (groupSize > 0)
                        {
                            AddExpandoAttribute(expandoAttributeWriter, id, "groupsize", groupSize.ToString(NumberFormatInfo.InvariantInfo), false);
                        }
                    }
                    else if (type == WebControls.ValidationDataType.Date)
                    {
                        AddExpandoAttribute(expandoAttributeWriter, id, "dateorder", GetDateElementOrder(), false);
                        AddExpandoAttribute(expandoAttributeWriter, id, "cutoffyear", CutoffYear.ToString(NumberFormatInfo.InvariantInfo), false);

                        // VSWhidbey 504553: The changes of this bug make client-side script not
                        // using the century attribute anymore, but still generating it for
                        // backward compatibility with Everett pages.
                        int currentYear = DateTime.Today.Year;
                        int century     = currentYear - (currentYear % 100);
                        AddExpandoAttribute(expandoAttributeWriter, id, "century", century.ToString(NumberFormatInfo.InvariantInfo), false);
                    }
                }
            }
        }
Example #22
0
        protected void AddPropertyValues(string key, object value, char delimiter)
        {
            var values = PropertyConverter.Flatten(value, delimiter);

            foreach (var elem in values)
            {
                AddPropertyDirect(key, elem);
            }
        }
 public WriteJsonPropertyContext(ModifiableEntity entity, string lowerCaseName, PropertyConverter propertyConverter, PropertyRoute parentPropertyRoute, JsonSerializerOptions jsonSerializerOptions, EntityJsonConverterFactory factory)
 {
     Entity                = entity;
     LowerCaseName         = lowerCaseName;
     PropertyConverter     = propertyConverter;
     ParentPropertyRoute   = parentPropertyRoute;
     JsonSerializerOptions = jsonSerializerOptions;
     Factory               = factory;
 }
Example #24
0
        private void TestMatch(string fromProp, string toProp, bool expected)
        {
            var target = new PropertyConverter();
            var from   = typeof(TestClassA).GetProperty(fromProp);
            var to     = typeof(TestClassB).GetProperty(toProp);
            var actual = target.CanConvert(@from, to);

            Assert.AreEqual(expected, actual);
        }
Example #25
0
        public RangeClientValidationRule(string errorMessage, object minValue, object maxValue, Type operandType)
        {
            // Since standard aps.net validation library supports only Int32, Double, String and DateTime types
            // then we will not try to validate other types on client side
            ValidationDataType?validationDataType = GetValidationDataType(operandType);

            if (!validationDataType.HasValue)
            {
                return;
            }

            ErrorMessage = errorMessage;

            EvaluationFunction = "RangeValidatorEvaluateIsValid";

            Parameters["maximumvalue"] = maxValue;
            Parameters["minimumvalue"] = minValue;

            Parameters["type"] = PropertyConverter.EnumToString(typeof(ValidationDataType), validationDataType.Value);

            NumberFormatInfo numberFormat = NumberFormatInfo.CurrentInfo;

            if (validationDataType.Value == ValidationDataType.Double)
            {
                Parameters["decimalchar"] = numberFormat.NumberDecimalSeparator;
            }
            else if (validationDataType.Value == ValidationDataType.Date)
            {
                int currentYear = DateTime.Today.Year;
                int century     = currentYear - (currentYear % 100);

                DateTimeFormatInfo dateFormat = DateTimeFormatInfo.CurrentInfo;
                Debug.Assert(dateFormat != null, "dateFormat != null");

                string shortPattern = dateFormat.ShortDatePattern;
                string dateElementOrder;
                string cutoffYear = dateFormat.Calendar.TwoDigitYearMax.ToString(NumberFormatInfo.InvariantInfo);
                if (shortPattern.IndexOf('y') < shortPattern.IndexOf('M'))
                {
                    dateElementOrder = "ymd";
                }
                else if (shortPattern.IndexOf('M') < shortPattern.IndexOf('d'))
                {
                    dateElementOrder = "mdy";
                }
                else
                {
                    dateElementOrder = "dmy";
                }

                Parameters["dateorder"]  = dateElementOrder;
                Parameters["cutoffyear"] = cutoffYear;
                Parameters["century"]    = century.ToString(NumberFormatInfo.InvariantInfo);
            }
        }
Example #26
0
        //public static void DoBaseCompareValidatorAddAttributes(WhidbeyBaseCompareValidator validator, IBaseCompareValidatorAccessor validatorAccessor) {
        //    if (validatorAccessor.RenderUpLevel) {
        //        ValidationDataType type = validator.Type;
        //        if (type != ValidationDataType.String) {
        //            string id = validator.ClientID;

        //            ValidatorHelper.AddExpandoAttribute(validator, id, "type", PropertyConverter.EnumToString(typeof(ValidationDataType), type), false);

        //            NumberFormatInfo info = NumberFormatInfo.CurrentInfo;
        //            if (type == ValidationDataType.Double) {
        //                string decimalChar = info.NumberDecimalSeparator;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "decimalchar", decimalChar);
        //            }
        //            else if (type == ValidationDataType.Currency) {
        //                string decimalChar = info.CurrencyDecimalSeparator;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "decimalchar", decimalChar);

        //                string groupChar = info.CurrencyGroupSeparator;
        //                if (groupChar[0] == 160)
        //                    groupChar = " ";
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "groupchar", groupChar);

        //                int digits = info.CurrencyDecimalDigits;
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "digits", digits.ToString(NumberFormatInfo.InvariantInfo), false);

        //                int groupSize = GetCurrencyGroupSize(info);
        //                if (groupSize > 0) {
        //                    ValidatorHelper.AddExpandoAttribute(validator, id, "groupsize", groupSize.ToString(NumberFormatInfo.InvariantInfo), false);
        //                }
        //            }
        //            else if (type == ValidationDataType.Date) {
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "dateorder", validatorAccessor.GetDateElementOrder(), false);
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "cutoffyear", validatorAccessor.CutoffYear.ToString(NumberFormatInfo.InvariantInfo), false);

        //                int currentYear = DateTime.Today.Year;
        //                int century = currentYear - (currentYear % 100);
        //                ValidatorHelper.AddExpandoAttribute(validator, id, "century", century.ToString(NumberFormatInfo.InvariantInfo), false);
        //            }
        //        }
        //    }
        //}

        public static void DoBaseValidatorAddAttributes(WhidbeyBaseValidator validator, IBaseValidatorAccessor validatorAccessor, HtmlTextWriter writer)
        {
            bool disabled = !validator.Enabled;

            if (disabled)
            {
                validator.Enabled = true;
            }

            try {
                if (validatorAccessor.RenderUpLevel)
                {
                    validatorAccessor.EnsureID();
                    string id = validator.ClientID;

                    if (validator.ControlToValidate.Length > 0)
                    {
                        AddExpandoAttribute(validator, id, "controltovalidate", validatorAccessor.GetControlRenderID(validator.ControlToValidate));
                    }
                    if (validator.SetFocusOnError)
                    {
                        AddExpandoAttribute(validator, id, "focusOnError", "t", false);
                    }
                    if (validator.ErrorMessage.Length > 0)
                    {
                        AddExpandoAttribute(validator, id, "errormessage", validator.ErrorMessage);
                    }
                    ValidatorDisplay display = validator.Display;
                    if (display != ValidatorDisplay.Static)
                    {
                        AddExpandoAttribute(validator, id, "display", PropertyConverter.EnumToString(typeof(ValidatorDisplay), display), false);
                    }
                    if (!validator.IsValid)
                    {
                        AddExpandoAttribute(validator, id, "isvalid", "False", false);
                    }
                    if (disabled)
                    {
                        AddExpandoAttribute(validator, id, "enabled", "False", false);
                    }
                    if (validator.ValidationGroup.Length > 0)
                    {
                        AddExpandoAttribute(validator, id, "validationGroup", validator.ValidationGroup);
                    }
                }

                DoWebControlAddAttributes(validator, validatorAccessor, writer);
            }
            finally {
                if (disabled)
                {
                    validator.Enabled = false;
                }
            }
        }
Example #27
0
        public static void Start(HttpConfiguration config)
        {
            if (started)
            {
                return;
            }

            started = true;

            SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod());
            ReflectionServer.RegisterLike(typeof(QueryTokenEmbedded));


            var pcs = PropertyConverter.GetPropertyConverters(typeof(QueryTokenEmbedded));

            pcs.Add("token", new PropertyConverter()
            {
                CustomWriteJsonProperty = ctx =>
                {
                    var qte = (QueryTokenEmbedded)ctx.Entity;

                    ctx.JsonWriter.WritePropertyName(ctx.LowerCaseName);
                    ctx.JsonSerializer.Serialize(ctx.JsonWriter, qte.TryToken == null ? null : new QueryTokenTS(qte.TryToken, true));
                },
                AvoidValidate          = true,
                CustomReadJsonProperty = ctx =>
                {
                    var result = ctx.JsonSerializer.Deserialize(ctx.JsonReader);
                    //Discard
                }
            });
            pcs.Add("parseException", new PropertyConverter()
            {
                CustomWriteJsonProperty = ctx =>
                {
                    var qte = (QueryTokenEmbedded)ctx.Entity;

                    ctx.JsonWriter.WritePropertyName(ctx.LowerCaseName);
                    ctx.JsonSerializer.Serialize(ctx.JsonWriter, qte.ParseException?.Message);
                },
                AvoidValidate          = true,
                CustomReadJsonProperty = ctx =>
                {
                    var result = ctx.JsonSerializer.Deserialize(ctx.JsonReader);
                    //Discard
                }
            });
            pcs.GetOrThrow("tokenString").CustomWriteJsonProperty = ctx =>
            {
                var qte = (QueryTokenEmbedded)ctx.Entity;

                ctx.JsonWriter.WritePropertyName(ctx.LowerCaseName);
                ctx.JsonWriter.WriteValue(qte.TryToken?.FullKey() ?? qte.TokenString);
            };
        }
Example #28
0
        private bool ValidateModifiableEntity(ModifiableEntity mod)
        {
            using (Validator.ModelBinderScope())
            {
                bool isValid = true;

                var entity = mod as Entity;
                using (entity == null ? null : entity.Mixins.OfType <CorruptMixin>().Any(c => c.Corrupt) ? Corruption.AllowScope() : Corruption.DenyScope())
                {
                    foreach (var kvp in PropertyConverter.GetPropertyConverters(mod.GetType()))
                    {
                        if (kvp.Value.AvoidValidate)
                        {
                            continue;
                        }

                        string?error = kvp.Value.PropertyValidator !.PropertyCheck(mod);
                        if (error != null)
                        {
                            isValid = false;
                            ModelState.AddModelError(this.Key + "." + kvp.Key, error);
                        }

                        var val = kvp.Value.GetValue !(mod);
                        if (val != null && this.CurrentPath.Push(val))
                        {
                            using (StateManager.Recurse(this, this.Key + "." + kvp.Key, null, val, null))
                            {
                                if (this.SignumValidate() == false)
                                {
                                    isValid = false;
                                }
                            }
                        }
                    }
                }

                if (entity != null && entity.Mixins.Any())
                {
                    foreach (var mixin in entity.Mixins)
                    {
                        if (this.CurrentPath.Push(mixin))
                        {
                            using (StateManager.Recurse(this, "mixins[" + mixin.GetType().Name + "].element", null, mixin, null))
                            {
                                isValid &= ValidateModifiableEntity(mixin);
                            }
                        }
                    }
                }

                return(isValid);
            }
        }
Example #29
0
        public void Convert_SystemType_ReturnsScalarToken()
        {
            var logger    = Mock.Of <ILogger>();
            var config    = new DefaultConversionConfig(logger);
            var converter = new PropertyConverter(config, logger);

            var token = converter.Convert(typeof(string));

            Assert.NotNull(token);
            Assert.IsType <ScalarToken>(token);
        }
Example #30
0
        public void Convert_Array_ReturnsSequenceToken()
        {
            var logger    = Mock.Of <ILogger>();
            var config    = new DefaultConversionConfig(logger);
            var converter = new PropertyConverter(config, logger);

            var token = converter.Convert(new[] { 1, 2, 3 });

            Assert.NotNull(token);
            Assert.IsType <SequenceToken>(token);
        }
Example #31
0
        public void TestObjectFromString()
        {
            Assert.AreEqual(PropertyConverter.ObjectFromString(
                                typeof(string), null, "value"),
                            "value", "String Type");
            MemberInfo mi = this.GetType().GetProperty("AllowedConverterProperty");

            Assert.AreEqual(PropertyConverter.ObjectFromString(
                                typeof(int), mi, "ConverterValue"),
                            "ConverterValue", "Converter Value");
        }
	void Awake()
	{
		converter_ = GetComponent<PropertyConverter>();

       // source_.Bind();
       // target_.Bind();


       // converter_.Bind(source_, target_);

//        var converted = converter_.ConvertProp<int>(55.55f); 
            
            //converter_.ConvertProp<Vector3, float>(Vector3.zero, 15.5f );

       // Debug.Log(converted.ToString());


		//converter_ = new ConverterVec3ToInt();
		//source_.Bind ();
		//target_.Bind ();
	}
        /// <exception cref="System.ArgumentNullException">The <paramref name="context"/> is <c>null</c>.</exception>
        protected override void Process(CSharpGeneratorContext context)
        {
            Argument.IsNotNull(() => context);

            var factory = CSharpElementFactory.GetInstance(context.Root.GetPsiModule());
            var typeOwners = context.InputElements.OfType<GeneratorDeclaredElement<ITypeOwner>>().ToList();

            var includeInSerialization = bool.Parse(context.GetGlobalOptionValue(OptionIds.IncludePropertyInSerialization));
            var notificationMethod = bool.Parse(context.GetGlobalOptionValue(OptionIds.ImplementPropertyChangedNotificationMethod));
            var forwardEventArgument = bool.Parse(context.GetGlobalOptionValue(OptionIds.ForwardEventArgumentToImplementedPropertyChangedNotificationMethod));

            var propertyConverter = new PropertyConverter(factory, context.PsiModule, (IClassDeclaration)context.ClassDeclaration);
            foreach (var typeOwner in typeOwners)
            {
                var propertyDeclaredElement = typeOwner.DeclaredElement;
                var propertyDeclaration = (IPropertyDeclaration)propertyDeclaredElement.GetDeclarations().FirstOrDefault();
                if (propertyDeclaration != null)
                {
                    propertyConverter.Convert(propertyDeclaration, includeInSerialization, notificationMethod, forwardEventArgument);
                }
            }
        }
 protected abstract void ConvertProperty(
     PropertyConverter propertyConverter, IPropertyDeclaration propertyDeclaration);
Example #35
0
 internal PropertyTypeInfo(PropertyConverter converter, AutomationIdentifier id, Type type)
 {
     this._id = id;
     this._type = type;
     this._converter = converter;
 }
        protected override void Process(CSharpGeneratorContext context)
        {
            Argument.IsNotNull(() => context);

            var factory = CSharpElementFactory.GetInstance(context.Root.GetPsiModule());
            var viewModelToModelAttributeClrType = TypeHelper.CreateTypeByCLRName(CatelMVVM.ViewModelToModelAttribute, context.PsiModule, UniversalModuleReferenceContext.Instance);

            var declaredElements = context.InputElements.OfType<GeneratorDeclaredElement>().ToList();
            var classLikeDeclaration = context.ClassDeclaration;
            if (classLikeDeclaration != null)
            {
                var includeInSerialization = bool.Parse(context.GetGlobalOptionValue(OptionIds.IncludePropertyInSerialization));
                var notificationMethod = bool.Parse(context.GetGlobalOptionValue(OptionIds.ImplementPropertyChangedNotificationMethod));
                var forwardEventArgument = bool.Parse(context.GetGlobalOptionValue(OptionIds.ForwardEventArgumentToImplementedPropertyChangedNotificationMethod));
                var propertyConverter = new PropertyConverter(factory, context.PsiModule, (IClassDeclaration)classLikeDeclaration);
                foreach (var declaredElement in declaredElements)
                {
                    var model = (IProperty)declaredElement.GetGroupingObject();
                    var modelProperty = (IProperty)declaredElement.DeclaredElement;
                    if (model != null)
                    {
                        Log.Debug("Computing property name");
                        string propertyName = string.Empty;

                        var cSharpTypeMemberDeclarations = new List<ICSharpTypeMemberDeclaration>();

                        IClassLikeDeclaration currentClassDeclaration = classLikeDeclaration;

                        do
                        {
                            cSharpTypeMemberDeclarations.AddRange(currentClassDeclaration.MemberDeclarations);
                            var superType = currentClassDeclaration.SuperTypes.FirstOrDefault(type => type.IsClassType());
                            if (superType != null)
                            {
                                var superTypeTypeElement = superType.GetTypeElement();
                                if (superTypeTypeElement != null)
                                {
                                    currentClassDeclaration = (IClassLikeDeclaration)superTypeTypeElement.GetDeclarations().FirstOrDefault();
                                }
                            }
                        }
                        while (currentClassDeclaration != null);

                        if (!cSharpTypeMemberDeclarations.Exists(declaration => declaration.DeclaredName == modelProperty.ShortName))
                        {
                            propertyName = modelProperty.ShortName;
                        }

                        if (string.IsNullOrEmpty(propertyName) && !cSharpTypeMemberDeclarations.Exists(declaration => declaration.DeclaredName == model.ShortName + modelProperty.ShortName))
                        {
                            propertyName = model.ShortName + modelProperty.ShortName;
                        }

                        int idx = 0;
                        while (string.IsNullOrEmpty(propertyName))
                        {
                            if (!cSharpTypeMemberDeclarations.Exists(declaration => declaration.DeclaredName == model.ShortName + modelProperty.ShortName + idx.ToString(CultureInfo.InvariantCulture)))
                            {
                                propertyName = model.ShortName + modelProperty.ShortName + idx.ToString(CultureInfo.InvariantCulture);
                            }

                            idx++;
                        }

                        Log.Debug("Adding property '{0}'", propertyName);
                        var propertyDeclaration = (IPropertyDeclaration)factory.CreateTypeMemberDeclaration(ImplementationPatterns.AutoProperty, modelProperty.Type, propertyName);

                        var modelMemberDeclaration = model.GetDeclarations().FirstOrDefault();
                        if (modelMemberDeclaration != null && modelMemberDeclaration.Parent != null)
                        {
                            var modelClassDeclaration = modelMemberDeclaration.Parent.Parent;
                            if (modelClassDeclaration == classLikeDeclaration)
                            {
                                propertyDeclaration = ModificationUtil.AddChildAfter(modelClassDeclaration, modelMemberDeclaration, propertyDeclaration);
                            }
                            else if (classLikeDeclaration.Body != null && classLikeDeclaration.Body.FirstChild != null)
                            {

                                propertyDeclaration = ModificationUtil.AddChildAfter(classLikeDeclaration.Body.FirstChild, propertyDeclaration);
                            }
                        }

                        var fixedArguments = new List<AttributeValue> { new AttributeValue(ConstantValueHelper.CreateStringValue(model.ShortName, context.PsiModule, UniversalModuleReferenceContext.Instance)) };

                        if (propertyName != modelProperty.ShortName)
                        {
                            fixedArguments.Add(new AttributeValue(ConstantValueHelper.CreateStringValue(modelProperty.ShortName, context.PsiModule, UniversalModuleReferenceContext.Instance)));
                        }

                        Log.Debug("Adding attribute ViewModelToModel to property '{0}'", propertyName);
                        IAttribute attribute = factory.CreateAttribute(viewModelToModelAttributeClrType.GetTypeElement(), fixedArguments.ToArray(), new Pair<string, AttributeValue>[] { });
                        propertyDeclaration.AddAttributeAfter(attribute, null);
                        propertyConverter.Convert(propertyDeclaration, includeInSerialization, notificationMethod, forwardEventArgument);
                    }
                }
            }
        }