Ejemplo n.º 1
0
        public void ShouldParseRegisteredType()
        {
            var parsers = new TypeParsers();

            parsers.RegisterTypeParser <int>(new HexParser());
            Assert.That(parsers.Parse <int>("10"), Is.EqualTo(16));
        }
Ejemplo n.º 2
0
        public ValidatorFluent NotIn <T>(params object[] vals)
        {
            if (!this._checkCondition)
            {
                return(this);
            }
            if (vals == null || vals.Length == 0)
            {
                return(this);
            }
            T    t       = TypeParsers.ConvertTo <T>(this._target);
            bool isValid = true;

            for (int i = 0; i < vals.Length; i++)
            {
                object input = vals[i];
                T      t2    = TypeParsers.ConvertTo <T>(input);
                if (t.Equals(t2))
                {
                    isValid = false;
                    break;
                }
            }
            return(this.IsValid(isValid, "不是一个有效值"));
        }
Ejemplo n.º 3
0
        public void ShouldGenerateRegisteredType()
        {
            var parsers = new TypeParsers();

            parsers.RegisterTypeParser <int>(new HexParser());
            Assert.That(parsers.Generate(16), Is.EqualTo("10"));
        }
Ejemplo n.º 4
0
        public static TType Scalar <TType>(this DataBase db, IDbTransaction tran, string strSql, params IDataParameter[] parameters)
        {
            TType  tType = default(TType);
            object input = db.ExecuteScalar(tran, CommandType.Text, strSql, parameters);

            return(TypeParsers.ConvertTo <TType>(input));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get the value at the row/column name.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="row"></param>
        /// <param name="colName"></param>
        /// <returns></returns>
        public T Get <T>(int row, string colName)
        {
            string result      = (string)_records[row][colName];
            T      typedResult = (T)TypeParsers.Convert <T>(result);

            return(typedResult);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Get typed root setting by string key.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public virtual T Get <T>(string key)
        {
            object result    = this[key];
            T      converted = (T)TypeParsers.Convert <T>(result);

            return(converted);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Get typed section key value.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="section"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get <T>(string section, string key)
        {
            object result    = this[section, key];
            T      converted = (T)TypeParsers.Convert <T>(result);

            return(converted);
        }
Ejemplo n.º 8
0
        public static T Get <T>(string key)
        {
            T result;

            try
            {
                string      text    = string.Empty;
                HttpRequest request = HttpContext.Current.Request;
                if (request.HttpMethod.ToUpper() == "GET")
                {
                    text = request.QueryString[key];
                }
                else
                {
                    text = request[key];
                }
                text = HttpUtility.UrlDecode(text, Encoding.UTF8);
                T t = TypeParsers.ConvertTo <T>(text);
                result = t;
            }
            catch
            {
                throw;
            }
            return(result);
        }
Ejemplo n.º 9
0
        public static IList <IScheduledRule> LoadRules(string strRules)
        {
            IList <IScheduledRule> list = new List <IScheduledRule>();

            foreach (Match match in ScheduledUtils.regex.Matches(strRules))
            {
                ScheduledRule scheduledRule = new ScheduledRule();
                scheduledRule.Rule = new TaskRule
                {
                    Type   = match.Groups["Type"].Value,
                    Offest = match.Groups["Offset"].Value
                };
                string value = match.Groups["Count"].Value;
                scheduledRule.Count = (string.IsNullOrEmpty(value) ? 0 : TypeParsers.ConvertTo <int>(value));
                string value2 = match.Groups["EndDate"].Value;
                scheduledRule.End = (string.IsNullOrEmpty(value2) ? DateTime.MinValue : TypeParsers.ConvertTo <DateTime>(value2));
                if (Enum.IsDefined(ScheduledUtils.type, scheduledRule.Rule.Type))
                {
                    list.Add(scheduledRule);
                }
            }
            foreach (Match match2 in ScheduledUtils.regexBlockInterval.Matches(strRules))
            {
                ScheduledBlockIntervalRule scheduledBlockIntervalRule = new ScheduledBlockIntervalRule();
                scheduledBlockIntervalRule.Begin    = match2.Groups["Begin"].Value;
                scheduledBlockIntervalRule.Interval = match2.Groups["Interval"].Value;
                scheduledBlockIntervalRule.Region   = new TaskRegion
                {
                    Type        = match2.Groups["RegionType"].Value,
                    StartOffest = match2.Groups["StartOffset"].Value,
                    StopOffest  = match2.Groups["StopOffset"].Value
                };
                if (Enum.IsDefined(ScheduledUtils.type, scheduledBlockIntervalRule.Region.Type))
                {
                    list.Add(scheduledBlockIntervalRule);
                }
            }
            foreach (Match match3 in ScheduledUtils.regexBlockTimer.Matches(strRules))
            {
                ScheduledBlockTimerRule scheduledBlockTimerRule = new ScheduledBlockTimerRule();
                scheduledBlockTimerRule.Begin = match3.Groups["Begin"].Value;
                scheduledBlockTimerRule.Rule  = new TaskRule
                {
                    Type   = match3.Groups["RuleType"].Value,
                    Offest = match3.Groups["RuleOffset"].Value
                };
                scheduledBlockTimerRule.Region = new TaskRegion
                {
                    Type        = match3.Groups["RegionType"].Value,
                    StartOffest = match3.Groups["StartOffset"].Value,
                    StopOffest  = match3.Groups["StopOffset"].Value
                };
                if (Enum.IsDefined(ScheduledUtils.type, scheduledBlockTimerRule.Rule.Type) && Enum.IsDefined(ScheduledUtils.type, scheduledBlockTimerRule.Region.Type))
                {
                    list.Add(scheduledBlockTimerRule);
                }
            }
            return(list);
        }
        public bool TypeSupported(Type targetType)
        {
            if (TypeParsers.ContainsKey(targetType))
            {
                return(true);
            }

            return(ExtraParsers.Any(x => x.Parses(targetType)));
        }
Ejemplo n.º 11
0
        public static T Get <T>(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new Exception("Key is null...");
            }
            string input = ConfigurationManager.AppSettings[key];

            return(TypeParsers.ConvertTo <T>(input));
        }
Ejemplo n.º 12
0
        public static BoolResult <TType> Scalar <TType>(this DataBase db, string strSql, params IDataParameter[] parameters)
        {
            ValidationResults validationResults = new ValidationResults();
            TType             item = default(TType);

            try
            {
                object input = db.ExecuteScalar(db.ConnectionString, CommandType.Text, strSql, parameters);
                item = TypeParsers.ConvertTo <TType>(input);
            }
            catch (Exception ex)
            {
                validationResults.Add(ex.Message);
            }
            return(new BoolResult <TType>(item, validationResults.IsValid, string.Empty, validationResults));
        }
        public object ReadValue(string rawValue, Type targetType, string fieldOrParameterName)
        {
            IParser parser;

            if (TypeParsers.TryGetValue(targetType, out parser))
            {
                return(parser.ReadValue(rawValue, fieldOrParameterName));
            }

            var extra = ExtraParsers.FirstOrDefault(x => x.Parses(targetType));

            if (extra != null)
            {
                return(extra.ReadValue(targetType, rawValue, fieldOrParameterName));
            }

            MvxTrace.Error("Parameter {0} is invalid targetType {1}", fieldOrParameterName,
                           targetType.Name);
            return(null);
        }
Ejemplo n.º 14
0
 public static Dictionary<string, StringValues> Parse(TParameters parameters)
 {
     var nvc = QueryHelpers.ParseQuery("");
     var properties = typeof(TParameters).GetProperties();
     foreach (var prop in properties.OrderBy(o => o.Name))
     {
         if (Converters.ContainsKey(prop.PropertyType))
         {
             var o = prop.GetValue(parameters);
             if (o != null)
             {
                 var defaultValue = GetDefaultValue(prop);
                 if (defaultValue == null || o.ToString() != defaultValue.ToString())
                 {
                     Converters[prop.PropertyType](nvc, o, GetParameterName(prop).Camelize());
                 }
             }
         }
     }
     return TypeParsers.Sort(nvc);
 }
Ejemplo n.º 15
0
        public static NameValueCollection Parse(TParameters parameters)
        {
            var nvc        = HttpUtility.ParseQueryString("");
            var properties = typeof(TParameters).GetProperties();

            foreach (var prop in properties.OrderBy(o => o.Name))
            {
                if (Converters.ContainsKey(prop.PropertyType))
                {
                    var o = prop.GetValue(parameters);
                    if (o != null)
                    {
                        var defaultValue = GetDefaultValue(prop);
                        if (defaultValue == null || o.ToString() != defaultValue.ToString())
                        {
                            Converters[prop.PropertyType](nvc, o, GetParameterName(prop).Camelize());
                        }
                    }
                }
            }
            return(TypeParsers.Sort(nvc));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Load settings for a specific tenant
        /// </summary>
        /// <typeparam name="TSetting"></typeparam>
        /// <param name="tenantKey"></param>
        /// <returns></returns>
        public static TSetting Get <TSetting>(string tenantKey)
        {
            TSetting setting = new AppCfgTypeMixer <object>().ExtendWith <TSetting>();

            var props = setting.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var prop in props)
            {
                if (TypeParsers.Get(prop.PropertyType) == null)
                {
                    object settingObj = null;

                    if (prop.PropertyType.IsInterface)
                    {
                        var myMethod = typeof(MyAppCfg)
                                       .GetMethods()
                                       .Where(m => m.Name == "Get")
                                       .Select(m => new
                        {
                            Method = m,
                            Params = m.GetParameters(),
                            Args   = m.GetGenericArguments()
                        })
                                       .Where(x => x.Params.Length == 1 && x.Params[0].Name == "tenantKey")
                                       .Select(x => x.Method)
                                       .First();

                        MethodInfo genericMethod = myMethod.MakeGenericMethod(prop.PropertyType);
                        settingObj = genericMethod.Invoke(null, new[] { tenantKey });
                        prop.SetValue(setting, settingObj);
                        continue;
                    }
                    else
                    {
                        settingObj = Activator.CreateInstance(prop.PropertyType);

                        if (settingObj is IJsonDataType) // auto register json parser for types which inherited from IJsonDataType
                        {
                            var jsParser = Activator.CreateInstance(typeof(JsonParser <>).MakeGenericType(prop.PropertyType));
                            TypeParsers.Register(prop.PropertyType, jsParser);
                        }
                    }
                }

                if (TypeParsers.Get(prop.PropertyType) != null)
                {
                    try
                    {
                        ITypeParserOptions parserOpt = (ITypeParserOptions)prop.GetCustomAttribute <OptionAttribute>() ?? new OptionAttribute();
                        ISettingStore      storeOpt  = (ISettingStore)prop.GetCustomAttribute <StoreOptionAttribute>() ?? new StoreOptionAttribute();

                        string rawValue = null;

                        if (parserOpt?.RawValue != null)
                        {
                            rawValue = parserOpt.RawValue;
                        }
                        else
                        {
                            var settingKey = parserOpt?.Alias ?? prop.Name;
                            if (typeof(ITypeParserRawBuilder <>).MakeGenericType(prop.PropertyType).IsAssignableFrom(TypeParsers.Get(prop.PropertyType).GetType()))
                            {
                                rawValue = (string)typeof(ITypeParserRawBuilder <>).MakeGenericType(prop.PropertyType).GetMethod("GetRawValue").Invoke(TypeParsers.Get(prop.PropertyType), new[] { settingKey });
                            }
                            else
                            {
                                rawValue = GetRawValue(prop.PropertyType, tenantKey, settingKey, parserOpt, storeOpt);
                            }
                        }

                        if (rawValue != null)
                        {
                            prop.SetValue(setting, typeof(ITypeParser <>).MakeGenericType(prop.PropertyType).GetMethod("Parse").Invoke(TypeParsers.Get(prop.PropertyType), new[] { rawValue, (object)parserOpt }), null);
                        }
                        else
                        {
                            prop.SetValue(setting, parserOpt?.DefaultValue);
                        }
                    }
                    catch (Exception ex)
                    {
                        var tParserType = TypeParsers.Get(prop.PropertyType) != null?TypeParsers.Get(prop.PropertyType).GetType().ToString() : "null";

                        throw new AppCfgException($"{ex.InnerException?.Message ?? ex.Message}\n - Setting: {typeof(TSetting)}\n - Property Name: {prop.Name}\n - Property Type: {prop.PropertyType}\n - Parser: {tParserType}", ex);
                    }
                }
                else
                {
                    throw new AppCfgException($"There is no type parser for type [{prop.PropertyType}]. You maybe need to create a custom type parser for it");
                }
            }

            return(setting);
        }
Ejemplo n.º 17
0
        public static string ConvertToJsonString <T>(PagedList <T> result, IList <PropertyInfo> _columnProps, bool convertBoolToYesNo = false)
        {
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < result.Count; i++)
            {
                T      t        = result[i];
                string arg_1A_0 = string.Empty;
                string text     = string.Empty;
                stringBuilder.Append("{ ");
                for (int j = 0; j < _columnProps.Count; j++)
                {
                    PropertyInfo propertyInfo = _columnProps[j];
                    object       value        = _columnProps[j].GetValue(t, null);
                    Type         propertyType = propertyInfo.PropertyType;
                    bool         flag         = false;
                    if (propertyType == typeof(string))
                    {
                        text = ((value == null) ? string.Empty : value.ToString());
                        text = text.Replace("\\", "\\\\");
                        text = text.Replace("\"", "\\\"");
                        flag = true;
                    }
                    else
                    {
                        if (propertyType == typeof(bool))
                        {
                            text = ((value == null) ? "false" : value.ToString().ToLower());
                            if (convertBoolToYesNo)
                            {
                                text = ((text == "true") ? "\"yes\"" : "\"no\"");
                            }
                        }
                        else
                        {
                            if (propertyType == typeof(DateTime))
                            {
                                if (value == null)
                                {
                                    text = "0";
                                }
                                else
                                {
                                    text = ((DateTime)value).ToShortDateString();
                                    flag = true;
                                }
                            }
                            else
                            {
                                if (propertyType == typeof(int) || propertyType == typeof(long) || propertyType == typeof(float) || propertyType == typeof(double))
                                {
                                    text = TypeParsers.ConvertTo <double>(value).ToString();
                                }
                            }
                        }
                    }
                    if (flag)
                    {
                        stringBuilder.Append(string.Concat(new string[]
                        {
                            "\"",
                            _columnProps[j].Name,
                            "\": \"",
                            text,
                            "\""
                        }));
                    }
                    else
                    {
                        stringBuilder.Append("\"" + _columnProps[j].Name + "\": " + text);
                    }
                    if (j != _columnProps.Count - 1)
                    {
                        stringBuilder.Append(", ");
                    }
                }
                stringBuilder.Append(" }");
                if (i != result.Count - 1)
                {
                    stringBuilder.Append(",");
                }
            }
            return(stringBuilder.ToString());
        }
Ejemplo n.º 18
0
        public static TType SPScalar <TType>(this DataBase db, IDbTransaction tran, string spName, params IDataParameter[] parameters)
        {
            object input = db.ExecuteScalar(tran, spName, parameters);

            return(TypeParsers.ConvertTo <TType>(input));
        }
Ejemplo n.º 19
0
 public T GetValue <T>()
 {
     return(TypeParsers.ConvertTo <T>(this.m_sValue));
 }