/// <summary> /// Returns an array split along the separator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="str"></param> /// <param name="separator"></param> /// <returns></returns> public static T[] Split <T>(this string str, params char[] separator) { if (string.IsNullOrEmpty(str)) { return new T[] { } } ; var vals = str.Split(separator, StringSplitOptions.RemoveEmptyEntries); int i = -1; try { var retVals = new T[vals.Length]; for (i = 0; i < vals.Length; i++) { retVals[i] = ConvertEx.ChangeType <T>(vals[i].Trim()); } return(retVals); } catch (Exception ex) { if (i < 0) { throw; } throw new FormatException(string.Format("Cannot convert value '{0}'", vals[i]), ex); } }
public void InheritanceConversionTest() { var test = new ConvertTest(); var btest = ConvertEx.ChangeType <ConvertTestBase>(test); Assert.AreSame(test, btest); }
public void TestEnumConversions() { ConvertEx.ChangeType <LongEnum?>("First").ShouldBe(LongEnum.First); ConvertEx.ChangeType <LongEnum?>((short)2).ShouldBe(LongEnum.Second); ConvertEx.ChangeType <ShortEnum?>(2L).ShouldBe(ShortEnum.Second); ConvertEx.ChangeType <LongEnum?>(null).ShouldBeNull(); ConvertEx.ChangeType <int>(LongEnum.First).ShouldBe(1); }
public void TypeCtorTest() { var pt = new Point(5, 10); var test = ConvertEx.ChangeType <ConvertTest>(pt); Assert.AreEqual(pt.X, test.X); Assert.AreEqual(pt.Y, test.Y); }
/// <summary> /// Gets the number of bytes for an image. /// </summary> /// <param name="img"></param> /// <returns></returns> public static long SizeOf(this Image img) { //var sz = img.Height * img.Width; //return sz*4; var imgBytes = ConvertEx.ChangeType <byte[]>(img); return(imgBytes.LongLength); }
/// <summary> /// Returns the field value as the specified type. Uses ConvertEx to convert the value to the correct type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <param name="fieldName"></param> /// <param name="dfltVal">The value to return if the value is DBNull</param> /// <returns></returns> public static T GetValue <T>(this DataRowView row, string fieldName, T dfltVal) { if (row.IsNull(fieldName)) { return(dfltVal); } return(ConvertEx.ChangeType <T>(row[fieldName])); }
public static ConvertTest Parse(string s) { var test = new ConvertTest(); var vals = s.Split(','); test.X = ConvertEx.ChangeType <int>(vals[0]); test.Y = ConvertEx.ChangeType <int>(vals[1]); return(test); }
/// <summary> /// Returns the field value as the specified type. Uses ConvertEx to convert the value to the correct type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <param name="fieldName"></param> /// <param name="dfltVal">The value to return if the value is DBNull</param> /// <returns></returns> public static T GetValue <T>(this IDataReader row, string fieldName, T dfltVal) { var i = row.GetOrdinal(fieldName); if (row.IsDBNull(i)) { return(dfltVal); } return(ConvertEx.ChangeType <T>(row[i])); }
public static object Convert(object obj, Type convertionType) { return(obj switch { double d => convertionType switch { Type _ when convertionType == typeof(char) => (char)(int)d, Type _ when convertionType == typeof(char?) => (char?)(int)d, _ => ConvertEx.ChangeType(obj, convertionType), },
public void TestBigIntegerConversions() { ConvertEx.ChangeType <int>((BigInteger)100).ShouldBe(100); ConvertEx.ChangeType <int?>((BigInteger)100).ShouldBe(100); ConvertEx.ChangeType <string>((BigInteger)100).ShouldBe("100"); ConvertEx.ChangeType <LongEnum?>((BigInteger)2).ShouldBe(LongEnum.Second); ConvertEx.ChangeType <BigInteger?>(null).ShouldBeNull(); ConvertEx.ChangeType <BigInteger>((BigInteger)100).ShouldBe(new BigInteger(100)); ConvertEx.ChangeType <BigInteger>(LongEnum.First).ShouldBe(new BigInteger(1)); ConvertEx.ChangeType <BigInteger>(100).ShouldBe(new BigInteger(100)); }
public void SqlDbTypeConversionTest() { var val = ConvertEx.ChangeType <SqlDbType>(typeof(int)); Assert.AreEqual(SqlDbType.Int, val); val = ConvertEx.ChangeType <SqlDbType>(typeof(bool)); Assert.AreEqual(SqlDbType.Bit, val); val = ConvertEx.ChangeType <SqlDbType>(typeof(byte[])); Assert.AreEqual(SqlDbType.Binary, val); }
public bool RestoreFromXml(string path) { string xmlStr = GetXml(path); // No point in throwing an exception, just return; if (string.IsNullOrEmpty(xmlStr)) { return(false); } if (Properties == null) { Initialize_Internal(); } var xml = new XmlDocument(); xml.LoadXml(xmlStr); XmlNode propsNode = xml.SelectSingleNode("CmdLineObject/Properties"); foreach (XmlNode propNode in propsNode.ChildNodes) { CmdLineProperty prop = Properties[propNode.Name]; if (prop == null) { continue; } if (prop.PropertyType.IsArray) { var vals = new List <object>(); Type elementType = prop.PropertyType.GetElementType(); foreach (XmlNode elementNode in propNode.ChildNodes) { vals.Add(ConvertEx.ChangeType(elementNode.InnerXml, elementType)); } Array arr = Array.CreateInstance(elementType, vals.Count); for (int i = 0; i < vals.Count; i++) { arr.SetValue(vals[i], i); } prop.Value = arr; } else { prop.Value = ConvertEx.ChangeType(propNode.InnerXml, prop.PropertyType); } } return(true); }
public void Test1() { DateTime?ndt, expected; ndt = ConvertEx.ChangeType("2019/12/11 8:58:57", typeof(DateTime?)) as DateTime?; expected = (DateTime?)DateTime.Parse("2019/12/11 8:58:57"); Assert.Equal(expected, ndt); ndt = ConvertEx.ChangeType(null, typeof(DateTime?)) as DateTime?; Assert.Null(ndt); Assert.Throws <InvalidCastException>(() => Convert.ChangeType("2019/12/11 8:58:57", typeof(DateTime?))); }
public void TestGuidToBigIntConversion() { for (var i = 0; i < 1000; i++) { var guid = Guid.NewGuid(); var bigInt = ConvertEx.ChangeType <BigInteger>(guid); bigInt.Sign.ShouldBe(1); var convertedGuid = ConvertEx.ChangeType <Guid>(bigInt); convertedGuid.ShouldBe(guid); } }
protected T GetSetting <T>(Expression <Func <T> > settingProperty, T defaultValue = default(T)) { var accessor = new PropertyAccessor <T>(settingProperty); if (_appSettings.AllKeys.Contains(accessor.Name)) { var textValue = _appSettings[accessor.Name]; return((T)ConvertEx.ChangeType <T>(textValue)); } else { return(defaultValue); } }
/// <summary> /// Converts the array to a different type. /// </summary> /// <param name="arr"></param> /// <param name="elementType"></param> /// <returns></returns> public static Array Convert(this Array arr, Type elementType) { if (arr.GetType().GetElementType() == elementType) { return(arr.Copy()); } Array retArr = Array.CreateInstance(elementType, arr.Length); for (int i = 0; i < arr.Length; i++) { retArr.SetValue(ConvertEx.ChangeType(arr.GetValue(i), elementType), i); } return(retArr); }
/// <summary> /// Executes the command and returns the first column of the first row. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmd"></param> /// <param name="dflt">The value to return if the database value is DBNull.</param> /// <returns></returns> public T ExecuteScalar <T>(DbCommand cmd, T dflt) { T value = dflt; ExecuteCommand(cmd, () => { var res = cmd.ExecuteScalar(); if (res != DBNull.Value) { value = ConvertEx.ChangeType <T>(res); } }); return(value); }
public TEntity[] UnsafeSqlQuery <TEntity>(DbTransaction transaction, string sql, TDbParameter[] parameters = null) where TEntity : class, new() { var ret = new List <TEntity>(); using var command = new TDbCommand { Transaction = transaction, CommandText = sql, Connection = Connection, }; if (parameters != null) { command.Parameters.AddRange(parameters); } var columns = Common.EntityPropertiesCache[typeof(TEntity)].Value; using var reader = command.ExecuteReader(); while (reader.Read()) { var entity = new TEntity(); for (var i = 0; i < reader.FieldCount; i++) { var fieldName = reader.GetName(i); var column = columns.FirstOrDefault(x => string.Equals(x.ColumnName, fieldName, StringComparison.InvariantCultureIgnoreCase)); if (column != null) { var ovalue = reader.GetValue(i); var value = ovalue is DBNull ? null : ConvertEx.ChangeType(ovalue, column.Property.PropertyType); try { column.Property.SetValue(entity, value); } catch (Exception ex) { throw new ArgumentException($"Can not set value for field({fieldName}).", ex); } } } ret.Add(entity); } reader.Close(); OnExecuted?.Invoke(command); return(ret.ToArray()); }
static object ConvertTo(string value, Type type) { if (type == typeof(string)) { return(value); } else if (type == typeof(bool) && value.IsNullOrWhiteSpace()) { return(true); } else { try { return(ConvertEx.ChangeType(value, type)); } catch { throw new ArgumentException($"The value ({value}) can not convert to {type.FullName}."); } } }
/// <summary> /// Implements ProcessRowDelegate[T]. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <returns></returns> private T ProcessRow <T>(IDataReader row) { var obj = Activator.CreateInstance <T>(); var props = TypeDescriptor.GetProperties(obj); for (int i = 0; i < row.FieldCount; i++) { var fieldName = row.GetName(i); var prop = props.Find(fieldName, true); if (prop != null) { prop.SetValue(obj, ConvertEx.ChangeType(row[i], prop.PropertyType)); } } return(obj); }
private RegionBoundedTileStack LoadRegionBoundedTileStack(TileSet tileSet, XElement tileStackElem) { var outlineColor = ConvertEx.ChangeType <Color>(tileStackElem.Attribute <string>("outlineColor")); var tiles = new List <Tile>(); foreach (var tileElem in tileStackElem.Elements("Tile")) { tiles.Add(LoadTile(tileSet, tileElem)); } var northWall = tileStackElem.Attribute <string>("northWall"); var eastWall = tileStackElem.Attribute <string>("eastWall"); var southWall = tileStackElem.Attribute <string>("southWall"); var westWall = tileStackElem.Attribute <string>("westWall"); return(new RegionBoundedTileStack(tiles, tileSet, outlineColor, northWall, eastWall, southWall, westWall)); }
public void ChangeTypeTest() { object value; value = ConvertEx.ChangeType <DateTime>("7/4/2008"); Assert.AreEqual(DateTime.Parse("7/4/2008"), value); var test = ConvertEx.ChangeType <ConvertTest>("1,2"); Assert.AreEqual(1, test.X); Assert.AreEqual(2, test.Y); var testPt = ConvertEx.To <Point>(test); Assert.AreEqual(1, testPt.X); Assert.AreEqual(2, testPt.Y); test = ConvertEx.To <ConvertTest>(testPt); Assert.AreEqual(1, test.X); Assert.AreEqual(2, test.Y); }
/// <summary> /// Reads destination exponentValue from the ConfigNode and magically converts it to the type you ask. Tested for float, boolean and double[]. Anything else is at your own risk. /// </summary> /// <typeparam name="T">The type to convert to. Usually inferred from <paramref name="defaultValue"/>.</typeparam> /// <param name="config">ScaleType node from which to read values.</param> /// <param name="name">Name of the ConfigNode's field.</param> /// <param name="defaultValue">The exponentValue to use when the ConfigNode doesn't contain what we want.</param> /// <returns>The exponentValue in the ConfigNode, or <paramref name="defaultValue"/> if no decent exponentValue is found there.</returns> public static T ConfigValue <T>(ConfigNode config, string name, T defaultValue) { if (!config.HasValue(name)) { return(defaultValue); } string cfgValue = config.GetValue(name); try { var result = ConvertEx.ChangeType <T>(cfgValue); return(result); } catch (Exception ex) { if (ex is InvalidCastException || ex is FormatException || ex is OverflowException || ex is ArgumentNullException) { LogWf("Failed to convert string value \"{0}\" to type {1}", cfgValue, typeof(T).Name); return(defaultValue); } throw; } }
protected override void RenderContent(ITessellator tessellator) { base.RenderContent(tessellator); // TODO: Item.Renderer.Color = ModifyColorByState(_itemColor); tessellator.Translate(UI_ASCII.Width * 1.5f, UI_ASCII.Height * 1.5f); Scale(tessellator, 8.0f * 2.0f); if (Renderable != null) { tessellator.BindColor(Color.White); Renderable.Render(tessellator); } if (Hotkey.HasValue) { tessellator.BindColor(Color.White); Scale(tessellator, 8f); tessellator.Translate(16, 16, -1); ASCII.RenderText(tessellator, ConvertEx.ChangeType <char>(Hotkey.Value).ToString()); tessellator.Translate(-16, -16, 1); } }
public T GetProperty <T>(string propertyName) { return(ConvertEx.ChangeType <T>(_properties[propertyName])); }
public void TestVariousConversions() { ConvertEx.ChangeType <ushort?>(null).ShouldBeNull(); ConvertEx.ChangeType <int>(100L).ShouldBe(100); ConvertEx.ChangeType <int>(new long?(100L)).ShouldBe(100); }
/// <summary> /// Returns the field value as the specified type. Uses ConvertEx to convert the value to the correct type. /// </summary> /// <param name="row"></param> /// <param name="fieldName"></param> /// <param name="type"></param> /// <returns></returns> public static object GetValue(this IDataReader row, string fieldName, Type type) { var i = row.GetOrdinal(fieldName); return(ConvertEx.ChangeType(row[i], type)); }
/// <summary> /// Converts the result to an image. /// </summary> /// <returns></returns> public Image ResultToImage() { return(ConvertEx.ChangeType <Image>(Result)); }
/// <summary> /// Returns the field value as the specified type. Uses ConvertEx to convert the value to the correct type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <param name="fieldName"></param> /// <returns></returns> public static T GetValue <T>(this IDataReader row, string fieldName) { return(ConvertEx.ChangeType <T>(row[fieldName])); }
public void Intercept(IInvocation invocation) { var proxy = (TKvEntityAgent)invocation.Proxy; string property; string value; KvEntity store; PropertyInfo proxyProperty; if (proxy.IsProxyLoaded()) { switch (invocation.Method.Name) { case string name when name.StartsWith("set_"): property = invocation.Method.Name.Substring(4); value = invocation.Arguments[0]?.ToString(); store = proxy.GetColumnStores().FirstOrDefault(x => x.Key == property); proxyProperty = proxy.GetType().GetProperty(property); if (store != null) { store.Value = value; } else { throw new KeyNotFoundException(); } break; case string name when name.StartsWith("get_"): property = invocation.Method.Name.Substring(4); store = proxy.GetColumnStores().FirstOrDefault(x => x.Key == property); proxyProperty = proxy.GetType().GetProperty(property); if (store != null) { if (store.Value is null) { invocation.ReturnValue = proxyProperty.PropertyType.CreateDefault(); } else { try { var ret = ConvertEx.ChangeType(store.Value, proxyProperty.PropertyType); invocation.ReturnValue = ret; } catch { invocation.ReturnValue = proxyProperty.PropertyType.CreateDefault(); } } } else { invocation.Proceed(); } break; default: invocation.Proceed(); break; } } else { invocation.Proceed(); } }