private void SetPropertyValue(CmdLineProperty prop, string val, IEnumerable <string> arrayVals) { if (prop == null) { return; } object value = null; // Array conversion. if (arrayVals != null) { value = arrayVals.ToArray().Convert(prop.PropertyType.GetElementType()); } // Standard type conversion. else if (val != null) { value = ConvertEx.To(val, prop.PropertyType); } // Flag with no additional values is true. else if (prop.PropertyType == typeof(bool)) { value = true; } // Name defined, but no value. Set to default for type. else if (prop.PropertyType.IsValueType) { value = Activator.CreateInstance(prop.PropertyType); } prop.Value = value; }
public void InheritanceConversionTest() { var test = new ConvertTest(); var btest = ConvertEx.To <ConvertTestBase>(test); Assert.AreSame(test, btest); }
/// <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.To <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 TypeCtorTest() { var pt = new Point(5, 10); var test = ConvertEx.To <ConvertTest>(pt); Assert.AreEqual(pt.X, test.X); Assert.AreEqual(pt.Y, test.Y); }
/// <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 = default(T)) { if (row.IsNull(fieldName)) { return(dfltVal); } return(ConvertEx.To <T>(row[fieldName])); }
/// <summary> /// Gets the number of bytes for an image. /// </summary> /// <param name="img"></param> /// <returns></returns> public static MemSize SizeOf(this Image img) { //var sz = img.Height * img.Width; //return sz*4; var imgBytes = ConvertEx.To <byte[]>(img); return(imgBytes.LongLength); }
public static ConvertTest Parse(string s) { var test = new ConvertTest(); var vals = s.Split(','); test.X = ConvertEx.To <int>(vals[0]); test.Y = ConvertEx.To <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 = default(T)) { var i = row.GetOrdinal(fieldName); if (row.IsDBNull(i)) { return(dfltVal); } return(ConvertEx.To <T>(row[i])); }
/// <summary> /// Gets the value from the object with the given name. Uses . notation to find values in object graphs. Supports array syntax as well, but does not support method calls. If any of the properties in the chain are null, dflt is returned. Uses ConvertEx to return the value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="key"></param> /// <param name="dflt"></param> /// <returns></returns> public static T GetValue <T>(object obj, string key, T dflt = default(T)) { var val = GetValue(obj, key); if (val == null) { return(dflt); } else { return(ConvertEx.To <T>(val)); } }
/// <summary> /// Executes the query, and returns the first column of the first row in the result /// set returned by the query. Additional columns or rows are ignored. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmd"></param> /// <param name="dflt"></param> /// <returns></returns> public T ExecuteScalar <T>(DbCommand cmd, T dflt = default(T)) { var result = ExecuteScalar(cmd); if (result == null) { return(dflt); } if (result == DBNull.Value) { return(dflt); } return(ConvertEx.To <T>(result)); }
/// <summary> /// Executes the query, and returns the first column of the first row in the result /// set returned by the query. Additional columns or rows are ignored. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmd"></param> /// <param name="dflt"></param> /// <returns></returns> public async Task <T> ExecuteScalarAsync <T>(DbCommand cmd, T dflt = default(T)) { var result = await ExecuteScalarAsync(cmd).ConfigureAwait(false); if (result == null) { return(dflt); } if (result == DBNull.Value) { return(dflt); } return(ConvertEx.To <T>(result)); }
/// <summary> /// Gets the specified value from the dictionary. Converts to the given type. /// </summary> /// <typeparam name="TKey">Key type for the dictionary.</typeparam> /// <typeparam name="TVal">Value type for the dictionary.</typeparam> /// <typeparam name="TRet">Type to convert the value to.</typeparam> /// <param name="dict"></param> /// <param name="key">The key to the dictionary.</param> /// <param name="dflt">Returned if the key is not found or if the dictionary is null.</param> /// <returns></returns> public static TRet TryGetValue <TKey, TVal, TRet>(this IDictionary <TKey, TVal> dict, TKey key, TRet dflt = default(TRet)) { if (dict == null) { return(dflt); } if (!dict.ContainsKey(key)) { return(dflt); } var val = dict[key]; return(ConvertEx.To <TRet>(val)); }
/// <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.To(arr.GetValue(i), elementType), i); } return(retArr); }
/// <summary> /// Tries to get the value. Returns false if the key is not valid. If we simply can't reach the object in question, returns true, but value will be null. /// </summary> /// <param name="obj"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="dflt">Default value if unable to get the value.</param> /// <returns></returns> public static bool TryGetValue <T>(object obj, string key, out T value, T dflt = default(T)) { value = dflt; object objVal; if (!TryGetValue(obj, key, out objVal)) { return(false); } if (objVal != null) { value = ConvertEx.To <T>(objVal); } return(true); }
/// <summary> /// Fills the object and sets properties based on the field name. Assumes that the DataReader is on the correct row. /// </summary> /// <param name="row"></param> /// <param name="obj"></param> /// <param name="props"></param> /// <returns>True if the object was filled, false if the data reader didn't contain any data.</returns> private static void FillObject(DbDataReader row, object obj, PropertyDescriptorCollection props) { for (var i = 0; i < row.FieldCount; i++) { var name = row.GetName(i); if (name.IsEmpty()) { continue; } var prop = props.Find(name, false); if (prop == null) { continue; } var value = ConvertEx.To(row[i], prop.PropertyType); prop.SetValue(obj, value); } }
/// <summary> /// Converts the array to a different type. /// </summary> /// <param name="values"></param> /// <param name="elementType"></param> /// <returns></returns> public static IEnumerable Convert(this IEnumerable values, Type elementType) { if (values.GetType().GetElementType() == elementType) { return(values.Copy(elementType)); } var count = 0; Array retArr = Array.CreateInstance(elementType, count); var idx = 0; foreach (var val in values) { var newVal = ConvertEx.To(val, elementType); retArr.SetValue(newVal, idx); idx++; } return(retArr); }
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> /// Changes the type of the value. /// </summary> /// <param name="value">The object to convert.</param> /// <param name="to">The type to convert the value to.</param> /// <param name="convertedValue">Return the value if converted.</param> /// <returns>True if able to convert the value.</returns> public bool TryConvert(object value, Type to, out object convertedValue) { convertedValue = null; if (value == null) { return(false); } if (to.IsEnum) { var str = value as string; if (str != null) { str = str.Trim(); var name = GetName(to, str); if (name == null) { // Check to see if we can convert the string to a numeric value. Use a long // since that has the best chance of catching any of the valid enum types. // We do this because string parsing is very common and we want to ensure we // can convert to the enumerated value. long longVal; if (long.TryParse(str, out longVal)) { value = longVal; // Set the value so it can be checked below. } else { return(false); } } else { convertedValue = Enum.Parse(to, name); return(true); } } var enumType = Enum.GetUnderlyingType(to); convertedValue = ConvertEx.To(value, enumType); if (Enum.IsDefined(to, convertedValue)) { convertedValue = Enum.ToObject(to, convertedValue); return(true); } } var from = value.GetType(); if (from.IsEnum) { if (to == typeof(string)) { convertedValue = Enum.GetName(from, value); return(true); } try { convertedValue = (value as IConvertible).ToType(to, null); return(true); } catch (InvalidCastException) { } // Ignore exceptions, keep searching for a successful strategy. //if (to == typeof(int)) //{ // convertedValue = (int)value; // return true; //} //if (to == typeof(byte)) //{ // convertedValue = (byte)value; // return true; //} //if (to == typeof(long)) //{ // convertedValue = (long)value; // return true; //} } return(false); }
/// <summary> /// Converts the value to the specified type. /// Checks for a TypeConverter, conversion methods, /// and the IConvertible interface. Uses <see cref="BizArk.Core.ConvertEx.To(object, Type, IFormatProvider)"/>. /// </summary> /// <typeparam name="T">The type to convert to.</typeparam> /// <param name="obj">The value to convert from.</param> /// <returns></returns> /// <exception cref="System.InvalidCastException">This conversion is not supported. -or-value is null and conversionType is a value type.</exception> /// <exception cref="System.ArgumentNullException">conversionType is null.</exception> public static T To <T>(this object obj) { return(ConvertEx.To <T>(obj)); }
public void MemSizeTest() { Assert.AreEqual(1024, MemSize.cNumBytesInKibibyte); Assert.AreEqual(Math.Pow(2, 20), MemSize.cNumBytesInMebibyte); Assert.AreEqual(Math.Pow(2, 30), MemSize.cNumBytesInGibibyte); Assert.AreEqual(Math.Pow(2, 40), MemSize.cNumBytesInTebibyte); Assert.AreEqual(1_000, MemSize.cNumBytesInKilobyte); Assert.AreEqual(1_000_000, MemSize.cNumBytesInMegabyte); Assert.AreEqual(1_000_000_000, MemSize.cNumBytesInGigabyte); Assert.AreEqual(1_000_000_000_000, MemSize.cNumBytesInTerabyte); var sz = new MemSize(0); Assert.AreEqual(0, sz.TotalBytes); Assert.AreEqual(0, sz.TotalKibibytes); Assert.AreEqual(0, sz.TotalMebibytes); Assert.AreEqual(0, sz.TotalGibibytes); Assert.AreEqual(0, sz.TotalTebibytes); Assert.AreEqual(0, sz.TotalKilobytes); Assert.AreEqual(0, sz.TotalMegabytes); Assert.AreEqual(0, sz.TotalGigabytes); Assert.AreEqual(0, sz.TotalTerabytes); Assert.AreEqual("0 bytes", sz.ToString("bytes")); Assert.AreEqual("0 bytes", sz.ToString("SI")); Assert.AreEqual("0.0 KB", sz.ToString("KB")); Assert.AreEqual("0.0 MB", sz.ToString("MB")); Assert.AreEqual("0.0 GB", sz.ToString("GB")); Assert.AreEqual("0.0 TB", sz.ToString("TB")); Assert.AreEqual("0 bytes", sz.ToString("IEC")); Assert.AreEqual("0.0 KiB", sz.ToString("KiB")); Assert.AreEqual("0.0 MiB", sz.ToString("MiB")); Assert.AreEqual("0.0 GiB", sz.ToString("GiB")); Assert.AreEqual("0.0 TiB", sz.ToString("TiB")); sz = new MemSize(1000); Assert.AreEqual(1000, sz.TotalBytes); Assert.AreEqual(1000.0 / 1024, sz.TotalKibibytes); Assert.AreEqual(1000.0 / Math.Pow(2, 20), sz.TotalMebibytes); Assert.AreEqual(1000.0 / Math.Pow(2, 30), sz.TotalGibibytes); Assert.AreEqual(1000.0 / Math.Pow(2, 40), sz.TotalTebibytes); Assert.AreEqual(1, sz.TotalKilobytes); Assert.AreEqual(.001, sz.TotalMegabytes); Assert.AreEqual(.000001, sz.TotalGigabytes); Assert.AreEqual(.000000001, sz.TotalTerabytes); Assert.AreEqual("1,000 bytes", sz.ToString("bytes")); Assert.AreEqual("1.0 KB", sz.ToString("SI")); Assert.AreEqual("1.0 KB", sz.ToString("KB")); Assert.AreEqual("0.0 MB", sz.ToString("MB")); Assert.AreEqual("0.0 GB", sz.ToString("GB")); Assert.AreEqual("0.0 TB", sz.ToString("TB")); Assert.AreEqual("1.0 KiB", sz.ToString("IEC")); Assert.AreEqual("1.0 KiB", sz.ToString("KiB")); Assert.AreEqual("0.0 MiB", sz.ToString("MiB")); Assert.AreEqual("0.0 GiB", sz.ToString("GiB")); Assert.AreEqual("0.0 TiB", sz.ToString("TiB")); sz = new MemSize(MemSize.cNumBytesInTebibyte); Assert.AreEqual(1.0, sz.TotalTebibytes); Assert.AreEqual($"{MemSize.cNumBytesInTebibyte:N0} bytes", sz.ToString("bytes")); Assert.AreEqual("1.0 TiB", sz.ToString()); Assert.AreEqual("1.0 TiB", sz.ToString("IEC")); Assert.AreEqual($"{(MemSize.cNumBytesInTebibyte / MemSize.cNumBytesInKibibyte):N1} KiB", sz.ToString("KiB")); Assert.AreEqual($"{(MemSize.cNumBytesInTebibyte / MemSize.cNumBytesInMebibyte):N1} MiB", sz.ToString("MiB")); Assert.AreEqual($"{(MemSize.cNumBytesInTebibyte / MemSize.cNumBytesInGibibyte):N1} GiB", sz.ToString("GiB")); Assert.AreEqual("1.0 TiB", sz.ToString("TiB")); Assert.AreEqual("1.0 TB", sz.ToString("IEC*")); Assert.AreEqual($"{(MemSize.cNumBytesInTebibyte / MemSize.cNumBytesInKibibyte):N1} KB", sz.ToString("KiB*")); Assert.AreEqual($"{(MemSize.cNumBytesInTebibyte / MemSize.cNumBytesInMebibyte):N1} MB", sz.ToString("MiB*")); Assert.AreEqual($"{(MemSize.cNumBytesInTebibyte / MemSize.cNumBytesInGibibyte):N1} GB", sz.ToString("GiB*")); Assert.AreEqual("1.0 TB", sz.ToString("TiB*")); sz = new MemSize(123456789); Assert.AreEqual("Size is 123,456,789 bytes!", $"Size is {sz:bytes}!"); Assert.AreEqual("Size is 123,456.8 KB!", $"Size is {sz:KB}!"); Assert.AreEqual("Size is 123,456.789 KB!", $"Size is {sz:KB3}!"); sz = MemSize.Parse("1MiB"); Assert.AreEqual(MemSize.cNumBytesInMebibyte, sz.TotalBytes); Assert.AreEqual("1.0 MiB", sz.ToString("MiB")); sz = MemSize.Parse("1024MiB"); Assert.AreEqual(MemSize.cNumBytesInGibibyte, sz.TotalBytes); Assert.AreEqual("1,024.0 MiB", sz.ToString("MiB")); sz = MemSize.Parse("1024"); Assert.AreEqual(MemSize.cNumBytesInKibibyte, sz.TotalBytes); sz = MemSize.Parse("1MB"); Assert.AreEqual(MemSize.cNumBytesInMegabyte, sz.TotalBytes); sz = MemSize.Parse("1MB", true); Assert.AreEqual(MemSize.cNumBytesInMebibyte, sz.TotalBytes); Assert.IsTrue(MemSize.TryParse("1MB", out sz)); Assert.IsFalse(MemSize.TryParse("ASDF", out sz)); Assert.IsFalse(MemSize.TryParse("NOT", out sz)); Assert.IsFalse(MemSize.TryParse("1NOT", out sz)); sz = ConvertEx.To <MemSize>("1MB"); Assert.AreEqual(MemSize.cNumBytesInMegabyte, sz.TotalBytes); }