public XamlSetTypeConverterEventArgs (XamlMember member, TypeConverter typeConverter, object value, ITypeDescriptorContext serviceProvider, CultureInfo cultureInfo) : base (member, value) { CultureInfo = cultureInfo; ServiceProvider = serviceProvider; TypeConverter = typeConverter; }
public void TypeConverterListBool_CanConvert(object value, bool isConvertable) { var converter = new TypeConverter<IEnumerable<bool>>(); var list = new List<bool> {false, true}; var canConvert = converter.CanConvert(list.GetType()); Assert.True(canConvert); }
public DataCompiler(ILGenerator body, Type[] genericMethodParameters, IRuntimeContainer runtimeContainer) { this.body = body; this.genericMethodParameters = genericMethodParameters; this.runtimeContainer = runtimeContainer; this.typeConverter = new TypeConverter(runtimeContainer, genericMethodParameters); }
public void TypeConverter_CanConvertImageList_IsTrue() { var converter = new TypeConverter<IEnumerable<Image>>(); var list = new List<Image> {new Image(), new Image()}; var canConvert = converter.CanConvert(list.GetType()); Assert.IsTrue(canConvert); }
public void TypeConverter_CanConvertImage_IsTrue() { var converter = new TypeConverter<Image>(); var image = new Image(); var canConvert = converter.CanConvert(image.GetType()); Assert.IsTrue(canConvert); }
public void TypeConverter_CanConvertCommentList_IsTrue() { var converter = new TypeConverter<IEnumerable<Comment>>(); var list = new List<Comment> {new Comment(), new Comment()}; var canConvert = converter.CanConvert(list.GetType()); Assert.IsTrue(canConvert); }
public void TypeConverter_CanConvertComment_IsTrue() { var converter = new TypeConverter<Comment>(); var comment = new Comment(); var canConvert = converter.CanConvert(comment.GetType()); Assert.IsTrue(canConvert); }
// Method required to make the Progress Cell consistent with the default Image Cell. // The default Image Cell assumes an Image as a value, although the value of the Progress Cell is an int. protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { return emptyImage; }
// The user must not create a configuration directly. internal Configuration(Type configType, DataStore dataStore, IReadOnlyDictionary<string, object> attributes, TypeConverter converter) { Type = configType; DataStore = dataStore; Attributes = attributes; Converter = converter; }
public static void CanConvertTo_WithContext(object[,] data, TypeConverter converter) { for (int i = 0; i < data.GetLength(0); i++) { Type destinationType = (Type)data[i, 0]; bool result = (bool)data[i, 1]; Assert.Equal(result, converter.CanConvertTo(TypeConverterTests.s_context, destinationType)); } }
public static void CanConvertFrom_WithContext(object[,] data, TypeConverter converter) { for (int i = 0; i < data.GetLength(0); i++) { Type sourceType = data[i, 0] as Type; bool expected = (bool)data[i, 1]; Assert.Equal(expected, converter.CanConvertFrom(TypeConverterTests.s_context, sourceType)); } }
public void convert_throws_if_target_type_is_null() { var converter = new TypeConverter { SourceType = typeof(int) }; var ex = Assert.Throws<InvalidOperationException>(() => converter.Convert("123", null, null, null)); Assert.Equal("No TargetType has been specified.", ex.Message); }
public void convert_returns_null_if_value_is_null() { var converter = new TypeConverter { SourceType = typeof(int), TargetType = typeof(string) }; Assert.Null(converter.Convert(null, null, null, null)); }
public void convert_converts_the_value_to_the_target_type_where_possible() { var converter = new TypeConverter { SourceType = typeof(int), TargetType = typeof(string) }; Assert.Equal("123", converter.Convert(123, null, null, null)); }
public void convert_uses_specified_culture_during_conversion() { var converter = new TypeConverter { SourceType = typeof(double), TargetType = typeof(string) }; var cultureInfo = new CultureInfo("de-DE"); Assert.Equal("123,1", converter.Convert(123.1, null, null, cultureInfo)); }
public static void ConvertFrom_WithContext(object[,] data, TypeConverter converter) { for (int i = 0; i < data.GetLength(0); i++) { object source = data[i, 0]; object expected = data[i, 1]; CultureInfo culture = data[i, 2] as CultureInfo; Assert.Equal(expected, converter.ConvertFrom(TypeConverterTests.s_context, culture, source)); } }
/// <summary> /// Gets a value from the underlying data store to be used in an outbound /// field mapping operation /// </summary> /// <param name="fieldName"> The field name that is mapped to a SIFElement</param> /// <param name="typeConverter">The converter class for the requested SIF data type</param> /// <param name="mapping">The FieldMapping this value was generated from or null</param> /// <returns>The value to set to the SIF element. This value must contain the /// SIFSimpleType subclass represented by the SIFTypeConverter passed in to the /// method.</returns> public SifSimpleType GetSifValue(string fieldName, TypeConverter typeConverter, FieldMapping mapping) { int ordinal = SafeGetOrdinal(fieldName); if( ordinal == -1 ) { return null; } object value = fReader.GetValue(ordinal); return typeConverter.GetSifSimpleType(value); }
/// <summary> /// Gets a value from the underlying data store to be used in an outbound /// field mapping operation /// </summary> /// <param name="fieldName"> The field name that is mapped to a SIFElement</param> /// <param name="typeConverter">The converter class for the requested SIF data type</param> /// <param name="mapping">The FieldMapping this value was generated from or null</param> /// <returns>The value to set to the SIF element. This value must contain the /// SIFSimpleType subclass represented by the SIFTypeConverter passed in to the /// method.</returns> public override SifSimpleType GetSifValue(string fieldName, TypeConverter typeConverter, FieldMapping mapping) { int ordinal = SafeGetOrdinal(fieldName); if (ordinal == -1) { return null; } object value = fDataRow[ordinal]; return typeConverter.GetSifSimpleType(value); }
//------------------------------------------------------ // // Constructors // //------------------------------------------------------ protected DefaultValueConverter(TypeConverter typeConverter, Type sourceType, Type targetType, bool shouldConvertFrom, bool shouldConvertTo, DataBindEngine engine) { _typeConverter = typeConverter; _sourceType = sourceType; _targetType = targetType; _shouldConvertFrom = shouldConvertFrom; _shouldConvertTo = shouldConvertTo; _engine = engine; }
public static void ConvertTo_WithContext(object[,] data, TypeConverter converter) { Assert.Throws<ArgumentNullException>( () => converter.ConvertTo(TypeConverterTests.s_context, null, "", null)); // This type converter should had thrown ArgumentNullException in ConvertTo, because the destination type is null."); for (int i = 0; i < data.GetLength(0); i++) { object source = data[i, 0]; object expected = data[i, 1]; CultureInfo culture = data[i, 2] as CultureInfo; Assert.Equal(expected, converter.ConvertTo(TypeConverterTests.s_context, culture, source, expected.GetType())); } }
public void convert_uses_type_converters_if_necessary() { var converter = new TypeConverter { SourceType = typeof(Type1), TargetType = typeof(Type2) }; Assert.True(converter.Convert(new Type1(), null, null, null) is Type2); converter = new TypeConverter { SourceType = typeof(Type2), TargetType = typeof(Type1) }; Assert.True(converter.Convert(new Type2(), null, null, null) is Type1); }
public MvxDependencyPropertyTargetBinding(object target, string targetName, DependencyProperty targetDependencyProperty, Type actualPropertyType) : base(target) { _targetDependencyProperty = targetDependencyProperty; _actualPropertyType = actualPropertyType; _targetName = targetName; #if WINDOWS_WPF _typeConverter = _actualPropertyType.TypeConverter(); #endif // if we return TwoWay for ImageSource then we end up in // problems with WP7 not doing the auto-conversion // see some of my angst in http://stackoverflow.com/questions/16752242/how-does-xaml-create-the-string-to-bitmapimage-value-conversion-when-binding-to/16753488#16753488 // Note: if we discover other issues here, then we should make a more flexible solution if (_actualPropertyType == typeof(ImageSource)) { _defaultBindingMode = MvxBindingMode.OneWay; } }
// Methods internal static object DoConversionFrom(TypeConverter converter, object value) { object obj2 = value; try { if (((converter != null) && (value != null)) && converter.CanConvertFrom(value.GetType())) { obj2 = converter.ConvertFrom(value); } } catch (Exception exception) { if (!ShouldEatException(exception)) { throw; } } return obj2; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { // If we have a converter, use it if (this.Converter != null) { return this.Converter.Convert(value, targetType, parameter, culture); } // If the type is compatible, use it if (value != null && targetType.IsAssignableFrom(value.GetType())) { return value; } // We only know how to convert from text... var text = value as string; if (text != null) { if (this.typeConverter == null) { if (this.TargetType == typeof(string)) return text; this.typeConverter = TypeDescriptor.GetConverter(this.TargetType); } return typeConverter.ConvertFromString(null, CultureInfo.InvariantCulture, text); } } catch (Exception ex) { Debug.WriteLine("ThemeBinding exception: {0}", ex.Message); } return value; }
public static void Compile(string name, TypeBuilder dataClass, ConstructorInfo ctor, IType type, string[] typeParameters, IMetadataContainer container, IRuntimeContainer runtimeContainer) { var method = dataClass.DefineMethod(name, MethodAttributes.Public | MethodAttributes.Static, null, Type.EmptyTypes); if (typeParameters.Any()) { method.DefineGenericParameters(typeParameters.ToArray()); } var converter = new TypeConverter(runtimeContainer, method.GetGenericArguments()); var converted = converter.Convert(type); method.SetReturnType(converted); var body = method.GetILGenerator(); if (typeParameters.Any()) { body.Emit(OpCodes.Newobj, TypeBuilder.GetConstructor(ctor.DeclaringType.MakeGenericType(method.GetGenericArguments()), ctor)); } else { body.Emit(OpCodes.Newobj, ctor); } body.Emit(OpCodes.Ret); runtimeContainer.Add(name, method); var dataDecl = new DataDeclaration(type, null); dataDecl.TypeParameters = typeParameters; container.Add(name, dataDecl); RemoveFirstParameter(name, dataClass, method, new IType[0], type, typeParameters, runtimeContainer); }
public static void Compile(string name, TypeBuilder dataClass, ITypedExpression typedExpression, DataDeclaration data, IMetadataContainer container, IRuntimeContainer runtimeContainer) { var method = dataClass.DefineMethod(name, MethodAttributes.Public | MethodAttributes.Static, null, Type.EmptyTypes); if (data.TypeParameters.Any()) { method.DefineGenericParameters(data.TypeParameters.ToArray()); } var converter = new TypeConverter(runtimeContainer, method.GetGenericArguments()); var converted = converter.Convert(data.Type); method.SetReturnType(converted); var body = method.GetILGenerator(); typedExpression.AcceptVisitor(new DataCompiler(body, method.GetGenericArguments(), runtimeContainer)); body.Emit(OpCodes.Ret); container.Add(name, data); runtimeContainer.Add(name, method); RemoveFirstParameter(name, dataClass, method, new IType[0], data.Type, data.TypeParameters, runtimeContainer); }
protected override T InnerEvaluate <T>(string expression, string documentName) { object result = InnerEvaluate(expression, documentName); return(TypeConverter.ConvertToType <T>(result)); }
protected string ProcessAttributes(XmlNode node, object ret, Type t) { string refName = String.Empty; // process attributes foreach (XmlAttribute attr in node.Attributes) { string pname = attr.Name; string pvalue = attr.Value; // it's either a property or an event. Allow assignment to protected / private properties. PropertyInfo pi = t.GetProperty(pname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); EventInfo ei = t.GetEvent(pname); if (pi != null) { // it's a property! if (pvalue.StartsWith("{") && pvalue.EndsWith("}")) { // And the value is a reference to an instance! // Get the referenced object. Late binding is not supported! OnAssignReference(pi, StringHelpers.Between(pvalue, '{', '}'), ret); } else { // it's string, so use a type converter. if (pi.PropertyType.FullName == "System.Object") { OnAssignProperty(pi, ret, pvalue, pvalue); } else { TypeConverter tc = TypeDescriptor.GetConverter(pi.PropertyType); if (tc.CanConvertFrom(typeof(string))) { object val = tc.ConvertFrom(pvalue); try { OnAssignProperty(pi, ret, val, pvalue); } catch (Exception e) { Trace.Fail("Property setter for " + pname + " failed:\r\n" + e.Message); } } else { if (!OnCustomAssignProperty(pi, ret, pvalue)) { Trace.Fail("Property setter for " + pname + " cannot be converted to property type " + pi.PropertyType.FullName + "."); } } } } // auto-add to our object collection if ((pname == "Name") || (pname == "def:Name")) { refName = pvalue; // AddInstance(pvalue, ret); } } else if (ei != null) { // it's an event! string src = pvalue; string methodName = String.Empty; object sink = eventSink; if ((StringHelpers.BeginsWith(src, '{')) && (StringHelpers.EndsWith(src, '}'))) { src = StringHelpers.Between(src, '{', '}'); } if (src.IndexOf('.') != -1) { string[] handler = src.Split('.'); src = handler[0]; methodName = handler[1]; sink = GetInstance(src); } else { methodName = src; } OnAssignEvent(ei, ret, sink, src, methodName); } else { // auto-add to our object collection if ((pname == "Name") || (pname == "def:Name")) { refName = pvalue; // AddInstance(pvalue, ret); } else if (pname == "ref:Name") { // Do nothing. } else { if (!OnUnknownProperty(pname, ret, pvalue)) { // who knows what it is??? Trace.Fail("Failed acquiring property information for '" + pname + "' with value '" + pvalue + "'"); } } } } return(refName); }
/// <summary> /// 验证帖子信息 /// </summary> /// <param name="admininfo"></param> /// <param name="user"></param> /// <param name="ishtmlon"></param> private void SetPostInfo(AdminGroupInfo admininfo, ShortUserInfo user, bool ishtmlon) { if (postinfo.Layer == 0 && forum.Applytopictype == 1 && forum.Postbytopictype == 1 && topictypeselectoptions != string.Empty) { if (Utils.StrIsNullOrEmpty(DNTRequest.GetString("typeid")) || DNTRequest.GetString("typeid").Trim() == "0") { AddErrLine("主题类型不能为空"); return; } if (!Forums.IsCurrentForumTopicType(DNTRequest.GetString("typeid").Trim(), forum.Topictypes)) { AddErrLine("错误的主题类型"); return; } } //这段代码有什么作用,和下面的SetAttachmentInfo方法做的事情是否有重复?能否拿掉? ///删除附件 if (DNTRequest.GetInt("isdeleteatt", 0) == 1) { if (DNTRequest.GetFormInt("aid", 0) > 0 && Attachments.DeleteAttachment(DNTRequest.GetFormInt("aid", 0)) > 0) { attachmentlist = Attachments.GetAttachmentListByPid(postinfo.Pid); attachmentcount = Attachments.GetAttachmentCountByPid(postinfo.Pid); } AddLinkCss(BaseConfigs.GetForumPath + "templates/" + templatepath + "/editor.css", "css"); // 帖子内容 message = postinfo.Message; ispost = false; return; } // #region 检查标题和内容信息 if (string.IsNullOrEmpty(postTitle.Trim().Replace(" ", "")) && postinfo.Layer == 0) { AddErrLine("标题不能为空"); } else if (postTitle.Length > 60) { AddErrLine("标题最大长度为60个字符,当前为 " + postTitle.Length.ToString() + " 个字符"); } //string postmessage = DNTRequest.GetString("message"); if (postMessage.Equals("") || postMessage.Replace(" ", "").Equals("")) { AddErrLine("内容不能为空"); } if (admininfo != null && disablepostctrl != 1) { if (postMessage.Length < config.Minpostsize) { AddErrLine("您发表的内容过少, 系统设置要求帖子内容不得少于 " + config.Minpostsize.ToString() + " 字多于 " + config.Maxpostsize.ToString() + " 字"); } else if (postMessage.Length > config.Maxpostsize) { AddErrLine("您发表的内容过多, 系统设置要求帖子内容不得少于 " + config.Minpostsize.ToString() + " 字多于 " + config.Maxpostsize.ToString() + " 字"); } } //新用户广告强力屏蔽检查 if ((config.Disablepostad == 1) && useradminid < 1) //如果开启新用户广告强力屏蔽检查或是游客 { if ((config.Disablepostadpostcount != 0 && user.Posts <= config.Disablepostadpostcount) || (config.Disablepostadregminute != 0 && DateTime.Now.AddMinutes(-config.Disablepostadregminute) <= Convert.ToDateTime(user.Joindate))) { foreach (string regular in config.Disablepostadregular.Replace("\r", "").Split('\n')) { if (Posts.IsAD(regular, postTitle, postMessage)) { AddErrLine("发帖失败,内容中有不符合新用户强力广告屏蔽规则的字符,请检查标题和内容,如有疑问请与管理员联系"); return; } } } } #endregion string[] pollitem = Utils.SplitString(DNTRequest.GetString("PollItemname"), "\r\n"); int topicprice = 0; string tmpprice = DNTRequest.GetString("topicprice"); if (postinfo.Layer == 0) { #region 投票信息 //string[] pollitem = Utils.SplitString(DNTRequest.GetString("PollItemname"), "\r\n"); if (!Utils.StrIsNullOrEmpty(DNTRequest.GetString("updatepoll")) && topic.Special == 1) { pollinfo.Multiple = DNTRequest.GetInt("multiple", 0); // 验证用户是否有发布投票的权限 if (usergroupinfo.Allowpostpoll != 1) { AddErrLine("您当前的身份 \"" + usergroupinfo.Grouptitle + "\" 没有发布投票的权限"); return; } if (pollitem.Length < 2) { AddErrLine("投票项不得少于2个"); } else if (pollitem.Length > config.Maxpolloptions) { AddErrLine("系统设置为投票项不得多于" + config.Maxpolloptions + "个"); } else { for (int i = 0; i < pollitem.Length; i++) { if (Utils.StrIsNullOrEmpty(pollitem[i])) { AddErrLine("投票项不能为空"); } } } } #endregion #region 悬赏信息 //int topicprice = 0; //string tmpprice = DNTRequest.GetString("topicprice"); if (Regex.IsMatch(tmpprice, "^[0-9]*[0-9][0-9]*$") || tmpprice == string.Empty) { topicprice = Utils.StrToInt(tmpprice, 0) > 32767 ? 32767 : Utils.StrToInt(tmpprice, 0); //当不是正在进行的悬赏... if (topic.Special != 2) { if (topicprice > usergroupinfo.Maxprice && usergroupinfo.Maxprice > 0) { if (userextcreditsinfo.Unit.Equals("")) { AddErrLine(string.Format("主题售价不能高于 {0} {1}", usergroupinfo.Maxprice, userextcreditsinfo.Name)); } else { AddErrLine(string.Format("主题售价不能高于 {0} {1}({2})", usergroupinfo.Maxprice, userextcreditsinfo.Name, userextcreditsinfo.Unit)); } } else if (topicprice > 0 && usergroupinfo.Maxprice <= 0) { AddErrLine(string.Format("您当前的身份 \"{0}\" 未被允许出售主题", usergroupinfo.Grouptitle)); } else if (topicprice < 0) { AddErrLine("主题售价不能为负数"); } } else { if (usergroupinfo.Radminid != 1) { if (usergroupinfo.Allowbonus == 0) { AddErrLine(string.Format("您当前的身份 \"{0}\" 未被允许进行悬赏", usergroupinfo.Grouptitle)); } if (topicprice < usergroupinfo.Minbonusprice || topicprice > usergroupinfo.Maxbonusprice) { AddErrLine(string.Format("悬赏价格超出范围, 您应在 {0} - {1} {2}{3} 范围内进行悬赏", usergroupinfo.Minbonusprice, usergroupinfo.Maxbonusprice, userextcreditsinfo.Unit, userextcreditsinfo.Name)); } } } } else { if (topic.Special != 2) { AddErrLine("主题售价只能为整数"); } else { AddErrLine("悬赏价格只能为整数"); } } #endregion #region 辩论信息 if (!Utils.StrIsNullOrEmpty(DNTRequest.GetString("updatedebate")) && topic.Special == 4) { if (usergroupinfo.Allowdebate != 1) { AddErrLine("您当前的身份 \"" + usergroupinfo.Grouptitle + "\" 没有发布辩论的权限"); return; } if (Utils.StrIsNullOrEmpty(DNTRequest.GetString("positiveopinion"))) { AddErrLine("正方观点不能为空"); return; } if (Utils.StrIsNullOrEmpty(DNTRequest.GetString("negativeopinion"))) { AddErrLine("反方观点不能为空"); return; } if (Utils.StrIsNullOrEmpty(DNTRequest.GetString("terminaltime"))) { AddErrLine("辩论的结束日期不能为空"); return; } if (!Utils.IsDateString(DNTRequest.GetString("terminaltime"))) { AddErrLine("结束日期格式不正确"); return; } } #endregion } #region 绑定并检查主题和帖子信息 if (useradminid == 1) { postinfo.Title = Utils.HtmlEncode(postTitle); if (usergroupinfo.Allowhtml == 0) { postinfo.Message = Utils.HtmlEncode(postMessage); } else { postinfo.Message = ishtmlon ? postMessage : Utils.HtmlEncode(postMessage); } } else { postinfo.Title = Utils.HtmlEncode(ForumUtils.BanWordFilter(postTitle)); if (usergroupinfo.Allowhtml == 0) { postinfo.Message = Utils.HtmlEncode(ForumUtils.BanWordFilter(postMessage)); } else { postinfo.Message = ishtmlon ? ForumUtils.BanWordFilter(postMessage) : Utils.HtmlEncode(ForumUtils.BanWordFilter(postMessage)); } } postinfo.Title = postinfo.Title.Length > 60 ? postinfo.Title.Substring(0, 60) : postinfo.Title; if (useradminid != 1 && (ForumUtils.HasBannedWord(postTitle) || ForumUtils.HasBannedWord(postMessage))) { string bannedWord = ForumUtils.GetBannedWord(postTitle) == string.Empty ? ForumUtils.GetBannedWord(postMessage) : ForumUtils.GetBannedWord(postTitle); AddErrLine(string.Format("对不起, 您提交的内容包含不良信息 <font color=\"red\">{0}</font>, 请返回修改!", bannedWord)); return; } if (useradminid != 1 && (ForumUtils.HasAuditWord(postinfo.Title) || ForumUtils.HasAuditWord(postinfo.Message))) { AddErrLine("对不起, 管理员设置了需要对发帖进行审核, 您没有权力编辑已通过审核的帖子, 请返回修改!"); return; } #endregion // 检察上面验证是否有错误 if (IsErr()) { return; } //如果是不是管理员组,或者编辑间隔超过60秒,则附加编辑信息 if (Utils.StrDateDiffSeconds(postinfo.Postdatetime, 60) > 0 && config.Editedby == 1 && useradminid != 1) { postinfo.Lastedit = username + " 最后编辑于 " + Utils.GetDateTime(); } postinfo.Usesig = Utils.StrToInt(DNTRequest.GetString("usesig"), 0); postinfo.Htmlon = (usergroupinfo.Allowhtml == 1 && ishtmlon ? 1 : 0); postinfo.Smileyoff = smileyoff == 0 ? TypeConverter.StrToInt(DNTRequest.GetString("smileyoff")) : smileyoff; postinfo.Bbcodeoff = (usergroupinfo.Allowcusbbcode == 1 ? TypeConverter.StrToInt(DNTRequest.GetString("bbcodeoff")) : 1); postinfo.Parseurloff = TypeConverter.StrToInt(DNTRequest.GetString("parseurloff")); //如果当前用户就是作者或所在管理组有编辑的权限 if (userid == postinfo.Posterid || (admininfo != null && admininfo.Alloweditpost == 1 && Moderators.IsModer(useradminid, userid, forumid))) { alloweditpost = true; } else { AddErrLine("您当前的身份不是作者"); return; } if (!alloweditpost) { AddErrLine("您当前的身份没有编辑帖子的权限"); return; } if (alloweditpost) { SetTopicInfo(pollitem, topicprice, postMessage); } }
/// <summary> /// 获得指定表单参数的int类型值 /// </summary> /// <param name="strName">表单参数</param> /// <param name="defValue">缺省值</param> /// <returns>表单参数的int类型值</returns> public static int GetFormInt(string strName, int defValue) { return(TypeConverter.StrToInt(HttpContext.Current.Request.Form[strName], defValue)); }
internal override void Inititalize(Type memberType, string memberName, Cache cache) { base.Inititalize(memberType, memberName, cache); _typeConverter = InitializeTypeConverter(TypeConverter); }
private JsValue UpdateIdentifier(EvaluationContext context) { var strict = StrictModeScope.IsStrictModeCode; var name = _leftIdentifier._expressionName; var engine = context.Engine; var env = engine.ExecutionContext.LexicalEnvironment; if (JintEnvironment.TryGetIdentifierEnvironmentWithBindingValue( env, name, strict, out var environmentRecord, out var value)) { if (strict && _evalOrArguments) { ExceptionHelper.ThrowSyntaxError(engine.Realm); } var isInteger = value._type == InternalTypes.Integer; JsValue newValue = null; var operatorOverloaded = false; if (context.OperatorOverloadingAllowed) { if (JintUnaryExpression.TryOperatorOverloading(context, _argument.GetValue(context).Value, _change > 0 ? "op_Increment" : "op_Decrement", out var result)) { operatorOverloaded = true; newValue = result; } } if (!operatorOverloaded) { if (isInteger) { newValue = JsNumber.Create(value.AsInteger() + _change); } else if (value._type != InternalTypes.BigInt) { newValue = JsNumber.Create(TypeConverter.ToNumber(value) + _change); } else { newValue = JsBigInt.Create(TypeConverter.ToBigInt(value) + _change); } } environmentRecord.SetMutableBinding(name.Key.Name, newValue, strict); if (_prefix) { return(newValue); } if (!value.IsBigInt() && !value.IsNumber() && !operatorOverloaded) { return(JsNumber.Create(TypeConverter.ToNumber(value))); } return(value); } return(null); }
private JsValue UpdateNonIdentifier(EvaluationContext context) { var engine = context.Engine; var reference = _argument.Evaluate(context).Value as Reference; if (reference is null) { ExceptionHelper.ThrowTypeError(engine.Realm, "Invalid left-hand side expression"); } reference.AssertValid(engine.Realm); var value = engine.GetValue(reference, false); var isInteger = value._type == InternalTypes.Integer; JsValue newValue = null; var operatorOverloaded = false; if (context.OperatorOverloadingAllowed) { if (JintUnaryExpression.TryOperatorOverloading(context, _argument.GetValue(context).Value, _change > 0 ? "op_Increment" : "op_Decrement", out var result)) { operatorOverloaded = true; newValue = result; } } if (!operatorOverloaded) { if (isInteger) { newValue = JsNumber.Create(value.AsInteger() + _change); } else if (!value.IsBigInt()) { newValue = JsNumber.Create(TypeConverter.ToNumber(value) + _change); } else { newValue = JsBigInt.Create(TypeConverter.ToBigInt(value) + _change); } } engine.PutValue(reference, newValue); engine._referencePool.Return(reference); if (_prefix) { return(newValue); } else { if (isInteger || operatorOverloaded) { return(value); } if (!value.IsBigInt()) { return(JsNumber.Create(TypeConverter.ToNumber(value))); } return(JsBigInt.Create(value)); } }
/// <summary> /// Registers the converter for the specific Type /// </summary> /// <typeparam name="TFor">The type to register the converter for.</typeparam> /// <param name="converters"></param> /// <param name="converter">The converter to register</param> public static void RegisterTypeConverter <TFor>(this Dictionary <Type, TypeConverter> converters, TypeConverter converter) { converters[typeof(TFor)] = converter; }
public override void Visit(BinaryExpression expression) { Func <object> left = () => { expression.Left.Accept(this); var leftValue = _result; return(leftValue); }; Func <object> right = () => { expression.Right.Accept(this); var rightValue = _result; return(rightValue); }; switch (expression.Operator) { case OperatorType.Add: if (expression.Left.ResultType == PrimitiveType.String || expression.Right.ResultType == PrimitiveType.String) { _result = TypeConverter.ToString(left()) + TypeConverter.ToString(right()); } else { _result = TypeConverter.ToNumber(left()) + TypeConverter.ToNumber(right()); } break; case OperatorType.Subtract: _result = TypeConverter.ToNumber(left()) - TypeConverter.ToNumber(right()); break; case OperatorType.Multiply: _result = TypeConverter.ToNumber(left()) * TypeConverter.ToNumber(right()); break; case OperatorType.Divide: _result = TypeConverter.ToNumber(left()) / TypeConverter.ToNumber(right()); break; case OperatorType.Modulo: _result = TypeConverter.ToNumber(left()) % TypeConverter.ToNumber(right()); break; case OperatorType.Equality: _result = TypeConverter.ToNumber(left()) == TypeConverter.ToNumber(right()); break; case OperatorType.Inequality: _result = TypeConverter.ToNumber(left()) != TypeConverter.ToNumber(right()); break; case OperatorType.GreaterThan: _result = TypeConverter.ToNumber(left()) > TypeConverter.ToNumber(right()); break; case OperatorType.LessThan: _result = TypeConverter.ToNumber(left()) < TypeConverter.ToNumber(right()); break; case OperatorType.GreaterThanOrEqual: _result = TypeConverter.ToNumber(left()) >= TypeConverter.ToNumber(right()); break; case OperatorType.LessThanOrEqual: _result = TypeConverter.ToNumber(left()) <= TypeConverter.ToNumber(right()); break; default: throw new EvaluatorException("Invalid binary operator type."); } }
/// <summary> /// Converts a type to string if possible. This method supports an optional culture generically on any value. /// It calls the ToString() method on common types and uses a type converter on all other objects /// if available /// </summary> /// <param name="rawValue">The Value or Object to convert to a string</param> /// <param name="culture">Culture for numeric and DateTime values</param> /// <param name="unsupportedReturn">Return string for unsupported types</param> /// <returns>string</returns> public static string TypedValueToString(object rawValue, CultureInfo culture = null, string unsupportedReturn = null) { if (rawValue == null) { return(string.Empty); } if (culture == null) { culture = CultureInfo.CurrentCulture; } Type valueType = rawValue.GetType(); string returnValue = null; if (valueType == typeof(string)) { returnValue = rawValue as string; } else if (valueType == typeof(int) || valueType == typeof(decimal) || valueType == typeof(double) || valueType == typeof(float) || valueType == typeof(Single)) { returnValue = string.Format(culture.NumberFormat, "{0}", rawValue); } else if (valueType == typeof(DateTime)) { returnValue = string.Format(culture.DateTimeFormat, "{0}", rawValue); } else if (valueType == typeof(bool) || valueType == typeof(Byte) || valueType.IsEnum) { returnValue = rawValue.ToString(); } else if (valueType == typeof(Guid?)) { if (rawValue == null) { returnValue = string.Empty; } else { return(rawValue.ToString()); } } else { // Any type that supports a type converter TypeConverter converter = TypeDescriptor.GetConverter(valueType); if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) { returnValue = converter.ConvertToString(null, culture, rawValue); } else { // Last resort - just call ToString() on unknown type if (!string.IsNullOrEmpty(unsupportedReturn)) { returnValue = unsupportedReturn; } else { returnValue = rawValue.ToString(); } } } return(returnValue); }
/// <summary> /// Turns a string into a typed value generically. /// Explicitly assigns common types and falls back /// on using type converters for unhandled types. /// /// Common uses: /// * UI -> to data conversions /// * Parsers /// <seealso>Class ReflectionUtils</seealso> /// </summary> /// <param name="sourceString"> /// The string to convert from /// </param> /// <param name="targetType"> /// The type to convert to /// </param> /// <param name="culture"> /// Culture used for numeric and datetime values. /// </param> /// <returns>object. Throws exception if it cannot be converted.</returns> public static object StringToTypedValue(string sourceString, Type targetType, CultureInfo culture = null) { object result = null; bool isEmpty = string.IsNullOrEmpty(sourceString); if (culture == null) { culture = CultureInfo.CurrentCulture; } if (targetType == typeof(string)) { result = sourceString; } else if (targetType == typeof(Int32) || targetType == typeof(int)) { if (isEmpty) { result = 0; } else { result = Int32.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } } else if (targetType == typeof(Int64)) { if (isEmpty) { result = (Int64)0; } else { result = Int64.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } } else if (targetType == typeof(Int16)) { if (isEmpty) { result = (Int16)0; } else { result = Int16.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } } else if (targetType == typeof(decimal)) { if (isEmpty) { result = 0M; } else { result = decimal.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } } else if (targetType == typeof(DateTime)) { if (isEmpty) { result = DateTime.MinValue; } else { result = Convert.ToDateTime(sourceString, culture.DateTimeFormat); } } else if (targetType == typeof(byte)) { if (isEmpty) { result = 0; } else { result = Convert.ToByte(sourceString); } } else if (targetType == typeof(double)) { if (isEmpty) { result = 0F; } else { result = Double.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } } else if (targetType == typeof(Single)) { if (isEmpty) { result = 0F; } else { result = Single.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } } else if (targetType == typeof(bool)) { if (!isEmpty && sourceString.ToLower() == "true" || sourceString.ToLower() == "on" || sourceString == "1") { result = true; } else { result = false; } } else if (targetType == typeof(Guid)) { if (isEmpty) { result = Guid.Empty; } else { result = new Guid(sourceString); } } else if (targetType.IsEnum) { result = Enum.Parse(targetType, sourceString); } else if (targetType == typeof(byte[])) { // TODO: Convert HexBinary string to byte array result = null; } // Handle nullables explicitly since type converter won't handle conversions // properly for things like decimal separators currency formats etc. // Grab underlying type and pass value to that else if (targetType.Name.StartsWith("Nullable`")) { if (sourceString.ToLower() == "null" || sourceString == string.Empty) { result = null; } else { targetType = Nullable.GetUnderlyingType(targetType); result = StringToTypedValue(sourceString, targetType); } } else { TypeConverter converter = TypeDescriptor.GetConverter(targetType); if (converter != null && converter.CanConvertFrom(typeof(string))) { result = converter.ConvertFromString(null, culture, sourceString); } else { Debug.Assert(false, string.Format("Type Conversion not handled in StringToTypedValue for {0} {1}", targetType.Name, sourceString)); throw (new InvalidCastException(targetType.Name)); } } return(result); }
// Clear value-related things that this class caches public void ClearValueRelatedCacheItems() { _subProperties = null; _collection = null; _standardValues = null; _standardValuesExclusive = null; _converter = null; _commonValueType = null; _source = null; _isReadOnly = null; _valueSerializer = null; ClearSubValueRelatedCacheItems(); _parent.OnPropertyChanged("StandardValues"); _parent.OnPropertyChanged("StandardValuesExclusive"); _parent.OnPropertyChanged("Converter"); _parent.OnPropertyChanged("CommonValueType"); _parent.OnPropertyChanged("IsReadOnly"); // The following properties are only exposed by ModelPropertyEntry, not PropertyEntry. // People should bind to these properties through the PropertyValue. // However, if they ---- up in Xaml, the binding will still work and if that happens // we should try to update them when things change. _parent.OnPropertyChanged("SubProperties"); _parent.OnPropertyChanged("Collection"); _parent.OnPropertyChanged("Source"); }
private static ObjectInstance __STUB__Construct(ScriptEngine engine, object thisObj, object[] args) { thisObj = TypeConverter.ToObject(engine, thisObj); if (!(thisObj is RegExpConstructor)) { throw new JavaScriptException(engine, ErrorType.TypeError, "The method 'Construct' is not generic."); } switch (args.Length) { case 0: return(((RegExpConstructor)thisObj).Construct(Undefined.Value, null)); case 1: return(((RegExpConstructor)thisObj).Construct(args[0], null)); default: return(((RegExpConstructor)thisObj).Construct(args[0], TypeUtilities.IsUndefined(args[1]) ? null : TypeConverter.ToString(args[1]))); } }
/// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.2.1 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public ObjectInstance Construct(JsValue[] arguments) { return Construct(arguments.Length > 0 ? TypeConverter.ToNumber(arguments[0]) : 0); }
// colcon.fromhtml is weirdly slow, so we cache its result private static object ConvertXmlStringToObject(string valueName, string valueText, Type type) { if (type == typeof(bool)) { if (string.Compare(valueText, "off", true) == 0 || string.Compare(valueText, "no", true) == 0 || string.Compare(valueText, "disabled", true) == 0) { return(false); } return(true); } try { if (type == typeof(double)) { double result = 0; if (double.TryParse(valueText, NumberStyles.Number, null, out result)) { return(result); } return(1); } if (type == typeof(int) || type == typeof(long)) { if (string.Compare(valueName, "textcolor", true) == 0 || string.Compare(valueName, "colorkey", true) == 0 || string.Compare(valueName, "colordiffuse", true) == 0) { if (valueText.Length > 0) { bool isNamedColor = false; foreach (char ch in valueText) { if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f') { continue; } isNamedColor = true; break; } if (isNamedColor) { int index = valueText.IndexOf(':'); if (index != -1) { // FromHTML is strangly and unnessesarily slow, simple cache //Color color = ColorTranslator.FromHtml(valueText.Substring(0, index)); Color color = colCache.TryGetOrAdd(valueText.Substring(0, index), col => ColorTranslator.FromHtml(col)); int alpha = 255; if (index < valueText.Length) { if (valueText[index + 1] == '#') { alpha = int.Parse(valueText.Substring(index + 2), NumberStyles.HexNumber); } else { alpha = int.Parse(valueText.Substring(index + 1)); } } return(Color.FromArgb(alpha, color).ToArgb()); } return(colCache.TryGetOrAdd(valueText, col => Color.FromName(valueText)).ToArgb()); //return Color.FromName(valueText).ToArgb(); } try { Color color = colCache.TryGetOrAdd('#' + valueText, col => ColorTranslator.FromHtml(col)); //Color color = ColorTranslator.FromHtml('#' + valueText); return(color.ToArgb()); } catch { Log.Info("GUIControlFactory.ConvertXmlStringToObject: Invalid color format '#{0}' reverting to White", valueText); return(Color.White.ToArgb()); } } } } if (type == typeof(int)) { if (valueText.CompareTo("-") == 0) { return(0); } if (valueText.CompareTo("") == 0) { return(0); } int res; if (int.TryParse(valueText, out res)) { return(res); } if (int.TryParse(valueText, NumberStyles.HexNumber, null, out res)) { return(res); } } if (type == typeof(long)) { if (valueText.CompareTo("-") == 0) { return(0); } if (valueText.CompareTo("") == 0) { return(0); } long res; if (Int64.TryParse(valueText, NumberStyles.HexNumber, null, out res)) { return(res); } return(0); } } catch (Exception) { return(0); } if (type == typeof(ILayout) || type == typeof(ILayoutDetail)) { return(ParseLayout(valueText)); } // much of the above could be changed to use the following, needs time for thorough testing though //TypeConverter converter = TypeDescriptor.GetConverter(type); TypeConverter converter = convCache.TryGetOrAdd(type, t => TypeDescriptor.GetConverter(t)); if (converter.CanConvertFrom(typeof(string))) { return(converter.ConvertFromString(null, CultureInfo.InvariantCulture, valueText)); } return(null); }
/// <summary> /// 获得指定Url参数的int类型值 /// </summary> /// <param name="strName">Url参数</param> /// <returns>Url参数的int类型值</returns> public static int GetQueryInt(string strName) { return(TypeConverter.StrToInt(HttpContext.Current.Request.QueryString[strName], 0)); }
/// <summary> /// 获取序列或自动增长值的当前值 /// </summary> /// <returns>当前值</returns> public int GetCurrentValue() { return(TypeConverter.ToInt(ExecuteScalar("SELECT @@identity"))); }
public static string Replace(string thisObject, object substrOrRegExp, object replaceTextOrFunction) { // The built-in function binding system is not powerful enough to bind the replace // function properly, so we bind to the correct function manually. if (substrOrRegExp is RegExpInstance) { if (replaceTextOrFunction is FunctionInstance) { return(Replace(thisObject, (RegExpInstance)substrOrRegExp, (FunctionInstance)replaceTextOrFunction)); } else { return(Replace(thisObject, (RegExpInstance)substrOrRegExp, TypeConverter.ToString(replaceTextOrFunction))); } } else { if (replaceTextOrFunction is FunctionInstance) { return(Replace(thisObject, TypeConverter.ToString(substrOrRegExp), (FunctionInstance)replaceTextOrFunction)); } else { return(Replace(thisObject, TypeConverter.ToString(substrOrRegExp), TypeConverter.ToString(replaceTextOrFunction))); } } }
public override bool ApplyChanges() { WebPart webPart = WebPartToEdit; Debug.Assert(webPart != null); if (webPart != null) { EnsureChildControls(); bool allowLayoutChange = webPart.Zone.AllowLayoutChange; try { webPart.Title = _title.Text; } catch (Exception e) { _titleErrorMessage = CreateErrorMessage(e.Message); } if (allowLayoutChange) { try { TypeConverter chromeTypeConverter = TypeDescriptor.GetConverter(typeof(PartChromeType)); webPart.ChromeType = (PartChromeType)chromeTypeConverter.ConvertFromString(_chromeType.SelectedValue); } catch (Exception e) { _chromeTypeErrorMessage = CreateErrorMessage(e.Message); } } try { TypeConverter directionConverter = TypeDescriptor.GetConverter(typeof(ContentDirection)); webPart.Direction = (ContentDirection)directionConverter.ConvertFromString(_direction.SelectedValue); } catch (Exception e) { _directionErrorMessage = CreateErrorMessage(e.Message); } if (allowLayoutChange) { Unit height = Unit.Empty; string heightValueString = _height.Value; if (!String.IsNullOrEmpty(heightValueString)) { double heightValue; if (Double.TryParse(_height.Value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out heightValue)) { if (heightValue < MinUnitValue) { _heightErrorMessage = SR.GetString(SR.EditorPart_PropertyMinValue, MinUnitValue.ToString(CultureInfo.CurrentCulture)); } else if (heightValue > MaxUnitValue) { _heightErrorMessage = SR.GetString(SR.EditorPart_PropertyMaxValue, MaxUnitValue.ToString(CultureInfo.CurrentCulture)); } else { height = new Unit(heightValue, _height.Type); } } else { _heightErrorMessage = SR.GetString(SR.EditorPart_PropertyMustBeDecimal); } } if (_heightErrorMessage == null) { try { webPart.Height = (Unit)height; } catch (Exception e) { _heightErrorMessage = CreateErrorMessage(e.Message); } } } if (allowLayoutChange) { Unit width = Unit.Empty; string widthValueString = _width.Value; if (!String.IsNullOrEmpty(widthValueString)) { double widthValue; if (Double.TryParse(_width.Value, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out widthValue)) { if (widthValue < MinUnitValue) { _widthErrorMessage = SR.GetString(SR.EditorPart_PropertyMinValue, MinUnitValue.ToString(CultureInfo.CurrentCulture)); } else if (widthValue > MaxUnitValue) { _widthErrorMessage = SR.GetString(SR.EditorPart_PropertyMaxValue, MaxUnitValue.ToString(CultureInfo.CurrentCulture)); } else { width = new Unit(widthValue, _width.Type); } } else { _widthErrorMessage = SR.GetString(SR.EditorPart_PropertyMustBeDecimal); } } if (_widthErrorMessage == null) { try { webPart.Width = (Unit)width; } catch (Exception e) { _widthErrorMessage = CreateErrorMessage(e.Message); } } } if (allowLayoutChange && webPart.AllowHide) { try { webPart.Hidden = _hidden.Checked; } catch (Exception e) { _hiddenErrorMessage = CreateErrorMessage(e.Message); } } } return(!HasError); }
//------------------------------------------------------ // // Constructors // //------------------------------------------------------ public TargetDefaultValueConverter(TypeConverter typeConverter, Type sourceType, Type targetType, bool shouldConvertFrom, bool shouldConvertTo) : base(typeConverter, sourceType, targetType, shouldConvertFrom, shouldConvertTo) { }
/// <summary> /// 获得指定表单参数的float类型值 /// </summary> /// <param name="strName">表单参数</param> /// <param name="defValue">缺省值</param> /// <returns>表单参数的float类型值</returns> public static float GetFormFloat(string strName, float defValue) { return(TypeConverter.StrToFloat(HttpContext.Current.Request.Form[strName], defValue)); }
//------------------------------------------------------ // // Internal static API // //------------------------------------------------------ // static constructor - returns a ValueConverter suitable for converting between // the source and target. The flag indicates whether targetToSource // conversions are actually needed. // if no Converter is needed, return DefaultValueConverter.ValueConverterNotNeeded marker. // if unable to create a DefaultValueConverter, return null to indicate error. internal static IValueConverter Create(Type sourceType, Type targetType, bool targetToSource) { TypeConverter typeConverter; Type innerType; bool canConvertTo, canConvertFrom; bool sourceIsNullable = false; bool targetIsNullable = false; // sometimes, no conversion is necessary if (sourceType == targetType || (!targetToSource && targetType.IsAssignableFrom(sourceType))) { return(ValueConverterNotNeeded); } // the type convert for System.Object is useless. It claims it can // convert from string, but then throws an exception when asked to do // so. So we work around it. if (targetType == typeof(object)) { // The sourceType here might be a Nullable type: consider using // NullableConverter when appropriate. (uncomment following lines) //Type innerType = Nullable.GetUnderlyingType(sourceType); //if (innerType != null) //{ // return new NullableConverter(new ObjectTargetConverter(innerType), // innerType, targetType, true, false); //} // BUG: 1109257 ObjectTargetConverter is not the best converter possible. return(new ObjectTargetConverter(sourceType)); } else if (sourceType == typeof(object)) { // The targetType here might be a Nullable type: consider using // NullableConverter when appropriate. (uncomment following lines) //Type innerType = Nullable.GetUnderlyingType(targetType); // if (innerType != null) // { // return new NullableConverter(new ObjectSourceConverter(innerType), // sourceType, innerType, false, true); // } // BUG: 1109257 ObjectSourceConverter is not the best converter possible. return(new ObjectSourceConverter(targetType)); } // use System.Convert for well-known base types if (SystemConvertConverter.CanConvert(sourceType, targetType)) { return(new SystemConvertConverter(sourceType, targetType)); } // Need to check for nullable types first, since NullableConverter is a bit over-eager; // TypeConverter for Nullable can convert e.g. Nullable<DateTime> to string // but it ends up doing a different conversion than the TypeConverter for the // generic's inner type, e.g. bug 1361977 innerType = Nullable.GetUnderlyingType(sourceType); if (innerType != null) { sourceType = innerType; sourceIsNullable = true; } innerType = Nullable.GetUnderlyingType(targetType); if (innerType != null) { targetType = innerType; targetIsNullable = true; } if (sourceIsNullable || targetIsNullable) { // single-level recursive call to try to find a converter for basic value types return(Create(sourceType, targetType, targetToSource)); } #if NETSTANDARD // special case for converting IListSource to IList if (typeof(IListSource).IsAssignableFrom(sourceType) && targetType.IsAssignableFrom(typeof(IList))) { return(new ListSourceConverter()); } #endif // Interfaces are best handled on a per-instance basis. The type may // not implement the interface, but an instance of a derived type may. if (sourceType.IsInterface || targetType.IsInterface) { return(new InterfaceConverter(sourceType, targetType)); } // try using the source's type converter typeConverter = GetConverter(sourceType); canConvertTo = (typeConverter != null) ? typeConverter.CanConvertTo(targetType) : false; canConvertFrom = (typeConverter != null) ? typeConverter.CanConvertFrom(targetType) : false; if ((canConvertTo || targetType.IsAssignableFrom(sourceType)) && (!targetToSource || canConvertFrom || sourceType.IsAssignableFrom(targetType))) { return(new SourceDefaultValueConverter(typeConverter, sourceType, targetType, targetToSource && canConvertFrom, canConvertTo)); } // if that doesn't work, try using the target's type converter typeConverter = GetConverter(targetType); canConvertTo = (typeConverter != null) ? typeConverter.CanConvertTo(sourceType) : false; canConvertFrom = (typeConverter != null) ? typeConverter.CanConvertFrom(sourceType) : false; if ((canConvertFrom || targetType.IsAssignableFrom(sourceType)) && (!targetToSource || canConvertTo || sourceType.IsAssignableFrom(targetType))) { return(new TargetDefaultValueConverter(typeConverter, sourceType, targetType, canConvertFrom, targetToSource && canConvertTo)); } // if nothing worked and the target type is String, use a new TypeConverter (which will // simply call ToString) if (targetType == typeof(string)) { typeConverter = new TypeConverter(); canConvertTo = true; canConvertFrom = false; return(new SourceDefaultValueConverter(typeConverter, sourceType, targetType, false, true)); } // nothing worked, give up return(null); }
protected EnumValueRouteConstraintBase() { var valueType = Enum.GetUnderlyingType(typeof(T)); _converter = TypeDescriptor.GetConverter(valueType); }
public JsValue Call(JsValue thisObject, JsValue[] arguments, bool directCall) { if (arguments.At(0).Type != Types.String) { return(arguments.At(0)); } var code = TypeConverter.ToString(arguments.At(0)); try { var parser = new JavaScriptParser(StrictModeScope.IsStrictModeCode); var program = parser.Parse(code); using (new StrictModeScope(program.Strict)) { using (new EvalCodeScope()) { LexicalEnvironment strictVarEnv = null; try { if (!directCall) { Engine.EnterExecutionContext(Engine.GlobalEnvironment, Engine.GlobalEnvironment, Engine.Global); } if (StrictModeScope.IsStrictModeCode) { strictVarEnv = LexicalEnvironment.NewDeclarativeEnvironment(Engine, Engine.ExecutionContext.LexicalEnvironment); Engine.EnterExecutionContext(strictVarEnv, strictVarEnv, Engine.ExecutionContext.ThisBinding); } Engine.DeclarationBindingInstantiation(DeclarationBindingType.EvalCode, program.FunctionDeclarations, program.VariableDeclarations, this, arguments); var result = _engine.ExecuteStatement(program); if (result.Type == Completion.Throw) { throw new JavaScriptException(result.GetValueOrDefault()); } else { return(result.GetValueOrDefault()); } } finally { if (strictVarEnv != null) { Engine.LeaveExecutionContext(); } if (!directCall) { Engine.LeaveExecutionContext(); } } } } } catch (ParserError) { throw new JavaScriptException(Engine.SyntaxError); } }
protected override T InnerCallFunction <T>(string functionName, params object[] args) { object result = InnerCallFunction(functionName, args); return(TypeConverter.ConvertToType <T>(result)); }
protected override T InnerGetVariableValue <T>(string variableName) { object result = InnerGetVariableValue(variableName); return(TypeConverter.ConvertToType <T>(result)); }
/// <summary> /// 设置相关主题信息 /// </summary> /// <param name="pollitem"></param> /// <param name="topicprice"></param> /// <param name="postmessage"></param> private void SetTopicInfo(string[] pollitem, int topicprice, string postmessage) { if (postinfo.Layer == 0) { ///修改投票信息 StringBuilder itemvaluelist = new StringBuilder(""); if (topic.Special == 1) { string pollItemname = Utils.HtmlEncode(DNTRequest.GetFormString("PollItemname").Trim()); if (!Utils.StrIsNullOrEmpty(pollItemname)) { int multiple = DNTRequest.GetString("multiple") == "on" ? 1 : 0; int maxchoices = DNTRequest.GetInt("maxchoices", 0); if (multiple == 1 && maxchoices > pollitem.Length) { maxchoices = pollitem.Length; } if (!Polls.UpdatePoll(topic.Tid, multiple, pollitem.Length, DNTRequest.GetFormString("PollOptionID").Trim(), pollItemname, DNTRequest.GetFormString("PollOptionDisplayOrder").Trim(), DNTRequest.GetString("enddatetime"), maxchoices, DNTRequest.GetString("visiblepoll") == "on" ? 1 : 0, DNTRequest.GetString("allowview") == "on" ? 1 : 0)) { AddErrLine("投票错误,请检查显示顺序"); return; } } else { AddErrLine("投票项为空"); return; } } //修改辩论信息 if (topic.Special == 4) { debateinfo.Positiveopinion = DNTRequest.GetString("positiveopinion"); debateinfo.Negativeopinion = DNTRequest.GetString("negativeopinion"); debateinfo.Terminaltime = TypeConverter.StrToDateTime(DNTRequest.GetString("terminaltime")); if (!Debates.UpdateDebateTopic(debateinfo)) { AddErrLine("辩论修改选择了无效的主题"); return; } } int iconid = DNTRequest.GetInt("iconid", 0); topic.Iconid = (iconid > 15 || iconid < 0) ? 0 : iconid; topic.Title = postinfo.Title; //悬赏差价处理 if (topic.Special == 2) { int pricediff = topicprice - topic.Price; if (pricediff > 0) { if (bonusCreditsTrans < 1 || bonusCreditsTrans > 8) { AddErrLine("系统未设置\"交易积分设置\", 无法判断当前要使用的(扩展)积分字段, 暂时无法发布悬赏"); return; } //扣分 if (usergroupinfo.Radminid != 1 && Users.GetUserExtCredits(topic.Posterid, bonusCreditsTrans) < pricediff) { AddErrLine("主题作者 " + Scoresets.GetValidScoreName()[bonusCreditsTrans] + " 不足, 无法追加悬赏"); return; } else { topic.Price = topicprice; Users.UpdateUserExtCredits(topic.Posterid, bonusCreditsTrans, -pricediff * (Scoresets.GetCreditsTax() + 1)); //计算税后的实际支付 } } else if (pricediff < 0 && usergroupinfo.Radminid != 1) { AddErrLine("不能降低悬赏价格"); return; } } else if (topic.Special == 0)//普通主题,出售 { topic.Price = topicprice; } if (usergroupinfo.Allowsetreadperm == 1) { topic.Readperm = DNTRequest.GetInt("topicreadperm", 0) > 255 ? 255 : DNTRequest.GetInt("topicreadperm", 0); } if (ForumUtils.IsHidePost(postmessage) && usergroupinfo.Allowhidecode == 1) { topic.Hide = 1; } topic.Typeid = DNTRequest.GetFormInt("typeid", 0); htmltitle = DNTRequest.GetString("htmltitle").Trim(); if (!Utils.StrIsNullOrEmpty(htmltitle) && Utils.HtmlDecode(htmltitle).Trim() != topic.Title) { //按照 附加位/htmltitle(1位)/magic(3位)/以后扩展(未知位数) 的方式来存储, 11001 topic.Magic = 11000; } else { topic.Magic = 0; } ForumTags.DeleteTopicTags(topic.Tid); Topics.DeleteRelatedTopics(topic.Tid); string tags = DNTRequest.GetString("tags").Trim(); if (enabletag && !Utils.StrIsNullOrEmpty(tags)) { if (ForumUtils.InBanWordArray(tags)) { AddErrLine("标签中含有系统禁止词语,请修改"); return; } string[] tagArray = Utils.SplitString(tags, " ", true, 2, 10); if (tagArray.Length > 0 && tagArray.Length <= 5) { topic.Magic = Topics.SetMagicValue(topic.Magic, MagicType.TopicTag, 1); ForumTags.CreateTopicTags(tagArray, topic.Tid, userid, Utils.GetDateTime()); } else { AddErrLine("超过标签数的最大限制或单个标签长度没有介于2-10之间,最多可填写 5 个标签"); return; } } Topics.UpdateTopic(topic); //保存htmltitle if (canhtmltitle && !Utils.StrIsNullOrEmpty(htmltitle) && htmltitle != topic.Title) { Topics.WriteHtmlTitleFile(Utils.RemoveUnsafeHtml(htmltitle), topic.Tid); } } else { if (ForumUtils.IsHidePost(postmessage) && usergroupinfo.Allowhidecode == 1) { topic.Hide = 1; Topics.UpdateTopic(topic); } } }
/// <summary> /// Adds a value <see cref="PropertyTranslator"/> to the current <see cref="ModelTranslator"/>. /// </summary> /// <param name="sourceExpression">The source expression</param> /// <param name="destinationPath">The destination path</param> /// <param name="valueConverter">The optional value converter to use</param> public void AddPropertyTranslation(string sourceExpression, string destinationPath, TypeConverter valueConverter = null) { // Create translator var translator = CreatePropertyTranslator(sourceExpression, destinationPath); translator.ValueConverter = valueConverter ?? getValueConverter(translator.DestinationProperty); // Add the new value property translation Properties.Add(translator); }
public void convert_returns_unset_value_if_conversion_is_not_supported() { var converter = new TypeConverter { SourceType = typeof(TypeConverterFixture), TargetType = typeof(TypeCode) }; Assert.Same(DependencyProperty.UnsetValue, converter.Convert(new TypeConverterFixture(), null, null, null)); }
internal static bool TryParse(string s, Type type, CultureInfo culture, bool tryKnownTypes, out object value, out Exception error) { if (type == null) { Throw.ArgumentNullException(Argument.type); } error = null; value = null; if (s == null) { if (type.CanAcceptValue(null)) { return(true); } Throw.ArgumentNullException(Argument.s); } type = Nullable.GetUnderlyingType(type) ?? type; if (type.IsByRef) { type = type.GetElementType(); } if (culture == null) { culture = CultureInfo.InvariantCulture; } try { // ReSharper disable once PossibleNullReferenceException if (type.IsEnum) { #if NET35 || NET40 || NET45 || NET472 || NETSTANDARD2_0 value = Enum.Parse(type, s); return(true); #else return(Enum.TryParse(type, s, out value)); #endif } if (type.IsInstanceOfType(s)) { value = s; return(true); } if (tryKnownTypes && knownTypes.TryGetValue(type, out var tryParseMethod)) { return(tryParseMethod.Invoke(s, culture, out value)); } if (type.In(Reflector.Type, Reflector.RuntimeType #if !NET35 && !NET40 , Reflector.TypeInfo #endif )) { value = Reflector.ResolveType(s); return(value != null); } // a registered converter from string switch (Reflector.StringType.GetConversions(type, true).ElementAtOrDefault(0)) { case ConversionAttempt conversionAttempt: if (conversionAttempt.Invoke(s, type, culture, out value) && type.CanAcceptValue(value)) { return(true); } break; case Conversion conversion: value = conversion.Invoke(s, type, culture); if (type.CanAcceptValue(value)) { return(true); } break; } // Trying type converter as a fallback TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(Reflector.StringType)) { // ReSharper disable once AssignNullToNotNullAttribute - false alarm, context can be null value = converter.ConvertFrom(null, culture, s); return(true); } return(false); } catch (Exception e) when(!e.IsCritical()) { error = e; value = null; return(false); } }
/// <summary> /// The real constructor /// </summary> /// <param name="parent"></param> /// <param name="name"></param> /// <param name="tag"></param> /// <param name="sequence"></param> /// <param name="localPackage"></param> /// <param name="variant"></param> /// <param name="flags"></param> /// <param name="earliestVersion"></param> /// <param name="latestVersion"></param> /// <param name="typeConverter"></param> public ElementDefImpl(IElementDef parent, string name, string tag, int sequence, string localPackage, string variant, int flags, SifVersion earliestVersion, SifVersion latestVersion, TypeConverter typeConverter) { fName = name; if ((flags & FD_ATTRIBUTE) != 0) { // If this is an attribute, it is also a simple field flags |= FD_FIELD; } fFlags = flags; fPackage = localPackage; fVariant = variant; fParent = (ElementDefImpl) parent; fTypeConverter = typeConverter; DefineVersionInfo(earliestVersion, tag == null ? name : tag, sequence, flags); fLatestVersion = latestVersion; if (fParent != null) { fParent.addChild(this); } }
public static string ConvertToString(Enum value) { TypeConverter converter = TypeDescriptor.GetConverter(value.GetType()); return(converter.ConvertToString(value)); }
protected XamlPropertySetter (XamlObjectElement element, string name, TypeConverter converter) { Element = element; Name = name; Converter = converter; }
private static void CreateNumberControl(DisplayNameAttribute control, DescriptionAttribute descriptionAttr, PropertyInfo prop, Vector2 anchorPosition, RectTransform container) { UIRangeAttribute rangeAttr = prop.GetCustomAttribute <UIRangeAttribute>(); bool sliderControl = rangeAttr != null && rangeAttr.Slider; RectTransform element = Object.Instantiate(sliderControl ? sliderTemplate : inputTemplate, container, false); SetupUIElement(element, control, descriptionAttr, prop, anchorPosition); bool isFloatingPoint = prop.PropertyType == typeof(float) || prop.PropertyType == typeof(double); if (sliderControl) { Slider slider = element.GetComponentInChildren <Slider>(); slider.minValue = rangeAttr.Min; slider.maxValue = rangeAttr.Max; slider.wholeNumbers = !isFloatingPoint; Text sliderThumbText = slider.GetComponentInChildren <Text>(); slider.onValueChanged.RemoveAllListeners(); slider.onValueChanged.AddListener((value) => { prop.SetValue(tempMultiplayerOptions, value, null); sliderThumbText.text = value.ToString(isFloatingPoint ? "0.00" : "0"); }); tempToUICallbacks[prop.Name] = () => { slider.value = (float)prop.GetValue(tempMultiplayerOptions, null); sliderThumbText.text = slider.value.ToString(isFloatingPoint ? "0.00" : "0"); }; } else { InputField input = element.GetComponentInChildren <InputField>(); input.onValueChanged.RemoveAllListeners(); input.onValueChanged.AddListener((str) => { try { TypeConverter converter = TypeDescriptor.GetConverter(prop.PropertyType); System.IComparable value = (System.IComparable)converter.ConvertFromString(str); if (rangeAttr != null) { System.IComparable min = (System.IComparable)System.Convert.ChangeType(rangeAttr.Min, prop.PropertyType); System.IComparable max = (System.IComparable)System.Convert.ChangeType(rangeAttr.Max, prop.PropertyType); if (value.CompareTo(min) < 0) { value = min; } if (value.CompareTo(max) > 0) { value = max; } input.text = value.ToString(); } prop.SetValue(tempMultiplayerOptions, value, null); } catch { // If the char is not a number, rollback to previous value input.text = prop.GetValue(tempMultiplayerOptions, null).ToString(); } }); tempToUICallbacks[prop.Name] = () => { input.text = prop.GetValue(tempMultiplayerOptions, null).ToString(); }; } }