Here are the examples of the csharp api System.ComponentModel.TypeDescriptor.GetConverter(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
44 Examples
19
Source : ObjectExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static object To([MaybeNull] this object @this, Type type)
{
if (@this != null)
{
var targetType = type;
if (@this.GetType() == targetType)
{
return @this;
}
var converter = TypeDescriptor.GetConverter(@this);
if (converter != null&& converter.CanConvertTo(targetType))
return converter.ConvertTo(@this, targetType);
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null&& converter.CanConvertFrom(@this.GetType()))
return converter.ConvertFrom(@this);
if (@this == DBNull.Value)
return null;
return Convert.ChangeType(@this, targetType);
}
return @this;
}
19
Source : ObjectExtension.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public static T To<T>(this object @this)
{
if (@this == null)
{
return (T)(object)null;
}
var targetType = typeof(T);
if (@this.GetType() == targetType)
{
return (T)@this;
}
var converter = TypeDescriptor.GetConverter(@this);
if (converter != null && converter.CanConvertTo(targetType))
return (T)converter.ConvertTo(@this, targetType);
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null&& converter.CanConvertFrom(@this.GetType()))
return (T)converter.ConvertFrom(@this);
if (@this == DBNull.Value)
{
return (T)(object)null;
}
return (T)Convert.ChangeType(@this, targetType);
}
19
Source : ComparisonBinding.cs
with MIT License
from ay2015
with MIT License
from ay2015
public object Convert(
object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// Simple check for null
if (value == null || _styleBinding.Comparand == null)
{
return ReturnHelper(value == _styleBinding.Comparand);
}
// Convert the comparand so that it matches the value
object convertedComparand = _styleBinding.Comparand;
try
{
// Only support simple conversions in here.
convertedComparand = System.Convert.ChangeType(_styleBinding.Comparand, value.GetType());
}
catch (InvalidCastException)
{
// If Convert.ChangeType didn’t work, try a type converter
TypeConverter typeConverter = TypeDescriptor.GetConverter(value);
if (typeConverter != null)
{
if (typeConverter.CanConvertFrom(_styleBinding.Comparand.GetType()))
{
convertedComparand = typeConverter.ConvertFrom(_styleBinding.Comparand);
}
}
}
// Simple check for the equality case
if (_styleBinding.Operator == ComparisonOperators.eq)
{
// Actually, equality is a little more interesting, so put it in
// a helper routine
return ReturnHelper(
CheckEquals(value.GetType(), value, convertedComparand));
}
// For anything other than Equals, we need IComparable
if (!(value is IComparable) || !(convertedComparand is IComparable))
{
Trace(value, "One of the values was not an IComparable");
return ReturnHelper(false);
}
// Compare the values
int comparison = (value as IComparable).CompareTo(convertedComparand);
// And return the comparisson result
switch (_styleBinding.Operator)
{
case ComparisonOperators.g:
return ReturnHelper(comparison > 0);
case ComparisonOperators.ge:
return ReturnHelper(comparison >= 0);
case ComparisonOperators.l:
return ReturnHelper(comparison < 0);
case ComparisonOperators.le:
return ReturnHelper(comparison <= 0);
}
return _notNull;
}
19
Source : CodeDomUtility.cs
with MIT License
from codewitch-honey-crisis
with MIT License
from codewitch-honey-crisis
public static CodeExpression Serialize(object val)
{
if (null == val)
return new CodePrimitiveExpression(null);
if (val is char) // special case for unicode nonsense
{
// console likes to cook unicode characters
// so we render them as ints cast to the character
if (((char)val) > 0x7E)
return new CodeCastExpression(typeof(char), new CodePrimitiveExpression((int)(char)val));
return new CodePrimitiveExpression((char)val);
}
else
if (val is bool ||
val is string ||
val is short ||
val is ushort ||
val is int ||
val is uint ||
val is ulong ||
val is long ||
val is byte ||
val is sbyte ||
val is float ||
val is double ||
val is decimal)
{
// TODO: mess with strings to make them console safe.
return new CodePrimitiveExpression(val);
}
if (val is Array && 1 == ((Array)val).Rank && 0 == ((Array)val).GetLowerBound(0))
{
return _SerializeArray((Array)val);
}
var conv = TypeDescriptor.GetConverter(val);
if (null != conv)
{
if (conv.CanConvertTo(typeof(InstanceDescriptor)))
{
var desc = conv.ConvertTo(val, typeof(InstanceDescriptor)) as InstanceDescriptor;
if (!desc.IsComplete)
throw new NotSupportedException(
string.Format(
"The type \"{0}\" could not be serialized.",
val.GetType().FullName));
var ctor = desc.MemberInfo as ConstructorInfo;
if (null != ctor)
{
var result = new CodeObjectCreateExpression(ctor.DeclaringType);
foreach (var arg in desc.Arguments)
result.Parameters.Add(Serialize(arg));
return result;
}
throw new NotSupportedException(
string.Format(
"The instance descriptor for type \"{0}\" is not supported.",
val.GetType().FullName));
}
else
{
// we special case for KeyValuePair types.
var t = val.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition()==typeof(KeyValuePair<,>))
{
// TODO: Find a workaround for the bug with VBCodeProvider
// may need to modify the reference source
var kvpType = new CodeTypeReference(typeof(KeyValuePair<,>));
foreach (var arg in val.GetType().GetGenericArguments())
kvpType.TypeArguments.Add(arg);
var result = new CodeObjectCreateExpression(kvpType);
for(int ic= kvpType.TypeArguments.Count,i = 0;i<ic;++i)
{
var prop = val.GetType().GetProperty(0==i?"Key":"Value");
result.Parameters.Add(Serialize(prop.GetValue(val)));
}
return result;
}
throw new NotSupportedException(
string.Format("The type \"{0}\" could not be serialized.",
val.GetType().FullName));
}
}
else
throw new NotSupportedException(
string.Format(
"The type \"{0}\" could not be serialized.",
val.GetType().FullName));
}
19
Source : HRESULT.cs
with MIT License
from dahall
with MIT License
from dahall
private static int? ValueFromObj(object obj)
{
switch (obj)
{
case null:
return null;
case int i:
return i;
case uint u:
return unchecked((int)u);
default:
var c = TypeDescriptor.GetConverter(obj);
return c.CanConvertTo(typeof(int)) ? (int?)c.ConvertTo(obj, typeof(int)) : null;
}
}
19
Source : Win32Error.cs
with MIT License
from dahall
with MIT License
from dahall
private static uint? ValueFromObj(object obj)
{
if (obj == null) return null;
var c = TypeDescriptor.GetConverter(obj);
return c.CanConvertTo(typeof(uint)) ? (uint?)c.ConvertTo(obj, typeof(uint)) : null;
}
19
Source : NTStatus.cs
with MIT License
from dahall
with MIT License
from dahall
private static int? ValueFromObj(object obj)
{
switch (obj)
{
case null:
return null;
case int i:
return i;
case uint u:
return unchecked((int)u);
default:
var c = TypeDescriptor.GetConverter(obj);
return c.CanConvertTo(typeof(int)) ? (int?)c.ConvertTo(obj, typeof(int)) : null;
}
}
19
Source : InputDialog.cs
with MIT License
from dahall
with MIT License
from dahall
private static string ConvertToStr(object value)
{
return value switch
{
null => string.Empty,
IConvertible _ => value.ToString(), _ => (string)TypeDescriptor.GetConverter(value).ConvertTo(value, typeof(string)),
};
19
Source : ListViewItemExCollection.cs
with MIT License
from dahall
with MIT License
from dahall
protected override string GetDisplayText(object value)
{
string str;
if (value == null)
return string.Empty;
var defaultProperty = TypeDescriptor.GetDefaultProperty(base.CollectionType);
if ((defaultProperty != null) && (defaultProperty.PropertyType == typeof(string)))
{
str = (string)defaultProperty.GetValue(value);
if (!string.IsNullOrEmpty(str))
{
return str;
}
}
str = TypeDescriptor.GetConverter(value).ConvertToString(value);
if (!string.IsNullOrEmpty(str))
return str;
return value.GetType().Name;
}
19
Source : ListViewItemEx.cs
with MIT License
from dahall
with MIT License
from dahall
protected override string GetDisplayText(object value)
{
string str;
if (value == null)
{
return string.Empty;
}
PropertyDescriptor defaultProperty = TypeDescriptor.GetDefaultProperty(base.CollectionType);
if ((defaultProperty != null) && (defaultProperty.PropertyType == typeof(string)))
{
str = (string)defaultProperty.GetValue(value);
if ((str != null) && (str.Length > 0))
{
return str;
}
}
str = TypeDescriptor.GetConverter(value).ConvertToString(value);
if ((str != null) && (str.Length != 0))
{
return str;
}
return value.GetType().Name;
}
19
Source : ListViewItemExCollection.cs
with MIT License
from dahall
with MIT License
from dahall
protected override string GetDisplayText(object value)
{
string str;
if (value == null)
{
return string.Empty;
}
var defaultProperty = TypeDescriptor.GetDefaultProperty(base.CollectionType);
if ((defaultProperty != null) && (defaultProperty.PropertyType == typeof(string)))
{
str = (string)defaultProperty.GetValue(value);
if (!string.IsNullOrEmpty(str))
{
return str;
}
}
str = TypeDescriptor.GetConverter(value).ConvertToString(value);
if (!string.IsNullOrEmpty(str))
{
return str;
}
return value.GetType().Name;
}
19
Source : ResXResourceWriter.cs
with MIT License
from deepakkumar1984
with MIT License
from deepakkumar1984
private void AddResource(string name, object value, string comment)
{
if (value is string) {
AddResource(name, (string)value, comment);
return;
}
if (name == null)
throw new ArgumentNullException("name");
if (written)
throw new InvalidOperationException("The resource is already generated.");
if (writer == null)
InitWriter();
if (value is byte[]) {
WriteBytes(name, value.GetType(), (byte[])value, comment);
return;
}
if (value is ResourceSerializedObject rso) {
var bytes = rso.GetBytes();
WriteBytes(name, null, bytes, 0, bytes.Length, comment);
return;
}
if (value == null) {
// nulls written as ResXNullRef
WriteString(name, "", ResXNullRefTypeName, comment);
return;
}
if (value != null && !value.GetType().IsSerializable)
throw new InvalidOperationException(String.Format("The element '{0}' of type '{1}' is not serializable.", name, value.GetType().Name));
TypeConverter converter = TypeDescriptor.GetConverter(value);
if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) {
string str = (string)converter.ConvertToInvariantString(value);
WriteString(name, str, value.GetType().replacedemblyQualifiedName, comment);
return;
}
if (converter != null && converter.CanConvertTo(typeof(byte[])) && converter.CanConvertFrom(typeof(byte[]))) {
byte[] b = (byte[])converter.ConvertTo(value, typeof(byte[]));
WriteBytes(name, value.GetType(), b, comment);
return;
}
MemoryStream ms = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
try {
fmt.Serialize(ms, value);
} catch (Exception e) {
throw new InvalidOperationException("Cannot add a " + value.GetType() +
"because it cannot be serialized: " +
e.Message);
}
WriteBytes(name, null, ms.GetBuffer(), 0, (int)ms.Length, comment);
ms.Close();
}
19
Source : ResXResourceWriter.cs
with MIT License
from deepakkumar1984
with MIT License
from deepakkumar1984
public void AddMetadata(string name, object value)
{
if (value is string) {
AddMetadata(name, (string)value);
return;
}
if (value is byte[]) {
AddMetadata(name, (byte[])value);
return;
}
if (name == null)
throw new ArgumentNullException("name");
if (value == null)
throw new ArgumentNullException("value");
if (!value.GetType().IsSerializable)
throw new InvalidOperationException(String.Format("The element '{0}' of type '{1}' is not serializable.", name, value.GetType().Name));
if (written)
throw new InvalidOperationException("The resource is already generated.");
if (writer == null)
InitWriter();
Type type = value.GetType();
TypeConverter converter = TypeDescriptor.GetConverter(value);
if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string))) {
string str = (string)converter.ConvertToInvariantString(value);
writer.WriteStartElement("metadata");
writer.WriteAttributeString("name", name);
if (type != null)
writer.WriteAttributeString("type", type.replacedemblyQualifiedName);
writer.WriteStartElement("value");
writer.WriteString(str);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteWhitespace("\n ");
return;
}
if (converter != null && converter.CanConvertTo(typeof(byte[])) && converter.CanConvertFrom(typeof(byte[]))) {
byte[] b = (byte[])converter.ConvertTo(value, typeof(byte[]));
writer.WriteStartElement("metadata");
writer.WriteAttributeString("name", name);
if (type != null) {
writer.WriteAttributeString("type", type.replacedemblyQualifiedName);
writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType);
writer.WriteStartElement("value");
WriteNiceBase64(b, 0, b.Length);
} else {
writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType);
writer.WriteStartElement("value");
writer.WriteBase64(b, 0, b.Length);
}
writer.WriteEndElement();
writer.WriteEndElement();
return;
}
MemoryStream ms = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
try {
fmt.Serialize(ms, value);
} catch (Exception e) {
throw new InvalidOperationException("Cannot add a " + value.GetType() +
"because it cannot be serialized: " +
e.Message);
}
writer.WriteStartElement("metadata");
writer.WriteAttributeString("name", name);
if (type != null) {
writer.WriteAttributeString("type", type.replacedemblyQualifiedName);
writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType);
writer.WriteStartElement("value");
WriteNiceBase64(ms.GetBuffer(), 0, ms.GetBuffer().Length);
} else {
writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType);
writer.WriteStartElement("value");
writer.WriteBase64(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
writer.WriteEndElement();
writer.WriteEndElement();
ms.Close();
}
19
Source : ObjectExtensions.cs
with MIT License
from dotnet-toolbelt
with MIT License
from dotnet-toolbelt
public static bool CanConvertTo<T>(this object value)
{
if (value != null)
{
var targetType = typeof(T);
var converter = TypeDescriptor.GetConverter(value);
if (converter.CanConvertTo(targetType))
return true;
converter = TypeDescriptor.GetConverter(targetType);
if (converter.CanConvertFrom(value.GetType()))
return true;
}
return false;
}
19
Source : ObjectExtensions.cs
with MIT License
from dotnet-toolbelt
with MIT License
from dotnet-toolbelt
public static T ConvertTo<T>(this object value, T defaultValue)
{
if (value != null)
{
var targetType = typeof(T);
if (value.GetType() == targetType) return (T)value;
var converter = TypeDescriptor.GetConverter(value);
if (converter.CanConvertTo(targetType))
return (T)converter.ConvertTo(value, targetType);
converter = TypeDescriptor.GetConverter(targetType);
if (converter.CanConvertFrom(value.GetType()))
return (T)converter.ConvertFrom(value);
}
return defaultValue;
}
19
Source : SecuritySettings.cs
with GNU Lesser General Public License v2.1
from dvtk-org
with GNU Lesser General Public License v2.1
from dvtk-org
private System.Boolean _ValidCipherFlags(CipherFlags value)
{
string cipherList = TypeDescriptor.GetConverter(value).ConvertToString(value);
return this.m_adaptee.IsValidCipherList(cipherList);
}
19
Source : StockStringConverters.cs
with GNU Lesser General Public License v3.0
from friendsincode
with GNU Lesser General Public License v3.0
from friendsincode
public string ConvertToString(object value)
{
try
{
var converter = TypeDescriptor.GetConverter(value);
return converter.ConvertToString(null, Configuration.CultureInfo, value);
}
catch (Exception ex)
{
throw SettingValueCastException.Create(value.ToString(), value.GetType(), ex);
}
}
19
Source : TypeConverter.cs
with MIT License
from IllusionMods
with MIT License
from IllusionMods
public static object ChangeType(object value, Type destinationType, CultureInfo culture)
{
// Handle null and DBNull
if (value == null || value is DBNull)
{
return destinationType.IsValueType() ? Activator.CreateInstance(destinationType) : null;
}
var sourceType = value.GetType();
// If the source type is compatible with the destination type, no conversion is needed
if (destinationType.IsreplacedignableFrom(sourceType))
{
return value;
}
// Nullable types get a special treatment
if (destinationType.IsGenericType())
{
var genericTypeDefinition = destinationType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
var innerType = destinationType.GetGenericArguments()[0];
var convertedValue = ChangeType(value, innerType, culture);
return Activator.CreateInstance(destinationType, convertedValue);
}
}
// Enums also require special handling
if (destinationType.IsEnum())
{
var valueText = value as string;
return valueText != null ? Enum.Parse(destinationType, valueText, true) : value;
}
// Special case for booleans to support parsing "1" and "0". This is
// necessary for compatibility with XML Schema.
if (destinationType == typeof(bool))
{
if ("0".Equals(value))
return false;
if ("1".Equals(value))
return true;
}
#if !PORTABLE
// Try with the source type's converter
var sourceConverter = TypeDescriptor.GetConverter(value);
if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
{
return sourceConverter.ConvertTo(null, culture, value, destinationType);
}
// Try with the destination type's converter
var destinationConverter = TypeDescriptor.GetConverter(destinationType);
if (destinationConverter != null && destinationConverter.CanConvertFrom(sourceType))
{
return destinationConverter.ConvertFrom(null, culture, value);
}
#endif
// Try to find a casting operator in the source or destination type
foreach (var type in new[] { sourceType, destinationType })
{
foreach (var method in type.GetPublicStaticMethods())
{
var isCastingOperator =
method.IsSpecialName &&
(method.Name == "op_Implicit" || method.Name == "op_Explicit") &&
destinationType.IsreplacedignableFrom(method.ReturnParameter.ParameterType);
if (isCastingOperator)
{
var parameters = method.GetParameters();
var isCompatible =
parameters.Length == 1 &&
parameters[0].ParameterType.IsreplacedignableFrom(sourceType);
if (isCompatible)
{
try
{
return method.Invoke(null, new[] { value });
}
catch (TargetInvocationException ex)
{
throw ex.Unwrap();
}
}
}
}
}
// If source type is string, try to find a Parse or TryParse method
if (sourceType == typeof(string))
{
try
{
// Try with - public static T Parse(string, IFormatProvider)
var parseMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider));
if (parseMethod != null)
{
return parseMethod.Invoke(null, new object[] { value, culture });
}
// Try with - public static T Parse(string)
parseMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string));
if (parseMethod != null)
{
return parseMethod.Invoke(null, new object[] { value });
}
}
catch (TargetInvocationException ex)
{
throw ex.Unwrap();
}
}
// Handle TimeSpan
if (destinationType == typeof(TimeSpan))
{
return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture));
}
// Default to the Convert clreplaced
return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture);
}
19
Source : TypeConverterJsonAdapter.cs
with MIT License
from indice-co
with MIT License
from indice-co
public override void Write(Utf8JsonWriter writer, T objectToWrite, JsonSerializerOptions options) {
var converter = TypeDescriptor.GetConverter(objectToWrite);
var text = converter.ConvertToString(objectToWrite);
writer.WriteStringValue(text);
}
19
Source : EmbeddedSerializer.cs
with MIT License
from joergkrause
with MIT License
from joergkrause
private static string GetPersistValue(PropertyDescriptor propDesc, Type propType, object propValue, BindingType bindingType, bool topLevelInDesigner)
{
string propConverted = string.Empty;
if (bindingType == BindingType.Data)
{
return ("<%# " + propValue + " %>");
}
if (bindingType == BindingType.Expression)
{
return ("<%$ " + propValue + " %>");
}
if (propType.IsEnum)
{
return Enum.Format(propType, propValue, "G");
}
if (propType == typeof(string))
{
if (propValue != null)
{
propConverted = propValue.ToString();
if (!topLevelInDesigner)
{
// TODO: add control from prop
//text1 = HttpUtility.HtmlEncode(text1);
//text1 = GuruComponents.Netrix.HtmlFormatting.HtmlFormatter.GetEnreplacedies(text1, GuruComponents.Netrix.HtmlFormatting.EnreplacedyFormat.Named);
}
}
return propConverted;
}
TypeConverter propConverter;
if (propDesc != null)
{
propConverter = propDesc.Converter;
}
else
{
propConverter = TypeDescriptor.GetConverter(propValue);
}
if (propConverter != null)
{
propConverted = propConverter.ConvertToInvariantString(null, propValue);
}
else
{
propConverted = propValue.ToString();
}
if (!topLevelInDesigner)
{
// TODO: add control from prop
//text1 = GuruComponents.Netrix.HtmlFormatting.HtmlFormatter.GetEnreplacedies(text1, GuruComponents.Netrix.HtmlFormatting.EnreplacedyFormat.Named);
//text1 = HttpUtility.HtmlEncode(text1);
}
return propConverted;
}
19
Source : EmbeddedSerializer.cs
with MIT License
from joergkrause
with MIT License
from joergkrause
private static string GetPersistValue(PropertyDescriptor propDesc, Type propType, object propValue, EmbeddedSerializer.BindingType bindingType, bool topLevelInDesigner)
{
string text1 = string.Empty;
if (bindingType == EmbeddedSerializer.BindingType.Data)
{
return ("<%# " + propValue.ToString() + " %>");
}
if (bindingType == EmbeddedSerializer.BindingType.Expression)
{
return ("<%$ " + propValue.ToString() + " %>");
}
if (propType.IsEnum)
{
return Enum.Format(propType, propValue, "G");
}
if (propType == typeof(string))
{
if (propValue != null)
{
text1 = propValue.ToString();
if (!topLevelInDesigner)
{
text1 = HttpUtility.HtmlEncode(text1);
}
}
return text1;
}
TypeConverter converter1 = null;
if (propDesc != null)
{
converter1 = propDesc.Converter;
}
else
{
converter1 = TypeDescriptor.GetConverter(propValue);
}
if (converter1 != null)
{
text1 = converter1.ConvertToInvariantString(null, propValue);
}
else
{
text1 = propValue.ToString();
}
if (!topLevelInDesigner)
{
text1 = HttpUtility.HtmlEncode(text1);
}
return text1;
}
19
Source : AutoGrayableImage.cs
with MIT License
from LaughingLeader-DOS2-Mods
with MIT License
from LaughingLeader-DOS2-Mods
private void SetSources()
{
// If grayscale image cannot be created set grayscale source to original Source first
_sourceGray = _sourceColor = Source;
// Create Opacity Mask for grayscale image as FormatConvertedBitmap does not keep transparency info
_opacityMaskGray = new ImageBrush(_sourceColor);
_opacityMaskGray.Opacity = 0.6;
Uri uri = null;
try
{
// Get the string Uri for the original image source first
string stringUri = TypeDescriptor.GetConverter(Source).ConvertTo(Source, typeof(string)) as string;
// Try to resolve it as an absolute Uri
if (!Uri.TryCreate(stringUri, UriKind.Absolute, out uri))
{
// Uri is relative => requested image is in the same replacedembly as this object
stringUri = "pack://application:,,,/" + stringUri.TrimStart(new char[2] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
uri = new Uri(stringUri);
}
// create and cache grayscale ImageSource
_sourceGray = new FormatConvertedBitmap(new BitmapImage(uri), PixelFormats.Gray8, null, 0);
}
catch (Exception e)
{
//Debug.Fail("The Image used cannot be grayed out.", "Use BitmapImage or URI as a Source in order to allow gray scaling. Make sure the absolute Uri is used as relative Uri may sometimes resolve incorrectly.\n\nException: " + e.Message);
DivinityApp.Log($"Error greying out image '{uri}'({Source}).\n\nException: {e.Message}");
}
}
19
Source : MergedPropertyDescriptor.cs
with MIT License
from mameolan
with MIT License
from mameolan
private object CopyValue(object value)
{
if (value != null)
{
Type type = value.GetType();
if (type.IsValueType)
{
return value;
}
object obj2 = null;
ICloneable cloneable = value as ICloneable;
if (cloneable != null)
{
obj2 = cloneable.Clone();
}
if (obj2 == null)
{
// TODO: Reuse ObjectServices here?
TypeConverter converter = TypeDescriptor.GetConverter(value);
if (converter.CanConvertTo(typeof(InstanceDescriptor)))
{
InstanceDescriptor descriptor = (InstanceDescriptor)converter.ConvertTo(null, CultureInfo.InvariantCulture, value, typeof(InstanceDescriptor));
if ((descriptor != null) && descriptor.IsComplete)
{
obj2 = descriptor.Invoke();
}
}
if (((obj2 == null) && converter.CanConvertTo(typeof(string))) && converter.CanConvertFrom(typeof(string)))
{
object obj3 = converter.ConvertToInvariantString(value);
obj2 = converter.ConvertFromInvariantString((string)obj3);
}
}
if ((obj2 == null) && type.IsSerializable)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream serializationStream = new MemoryStream();
formatter.Serialize(serializationStream, value);
serializationStream.Position = 0L;
obj2 = formatter.Deserialize(serializationStream);
}
if (obj2 != null)
{
return obj2;
}
}
return value;
}
19
Source : AnimationRate.cs
with GNU General Public License v3.0
from ME3Tweaks
with GNU General Public License v3.0
from ME3Tweaks
public override string ToString()
{
if( this.HasDuration )
return TypeDescriptor.GetConverter( _duration ).ConvertToString( _duration );
return TypeDescriptor.GetConverter( _speed ).ConvertToString( _speed );
}
19
Source : AnimationRateConverter.cs
with GNU General Public License v3.0
from ME3Tweaks
with GNU General Public License v3.0
from ME3Tweaks
public override object ConvertFrom(
ITypeDescriptorContext td,
CultureInfo cultureInfo,
object value )
{
Type valueType = value.GetType();
if( value is string )
{
string stringValue = value as string;
if( ( value as string ).Contains( ":" ) )
{
TimeSpan duration = TimeSpan.Zero;
duration = ( TimeSpan )TypeDescriptor.GetConverter( duration ).ConvertFrom( td, cultureInfo, value );
return new AnimationRate( duration );
}
else
{
double speed = 0;
speed = ( double )TypeDescriptor.GetConverter( speed ).ConvertFrom( td, cultureInfo, value );
return new AnimationRate( speed );
}
}
else if( valueType == typeof( double ) )
{
return ( AnimationRate )( double )value;
}
else if( valueType == typeof( int ) )
{
return ( AnimationRate )( int )value;
}
else // TimeSpan
{
return ( AnimationRate )( TimeSpan )value;
}
}
19
Source : ObjectContainerHelperBase.cs
with GNU General Public License v3.0
from ME3Tweaks
with GNU General Public License v3.0
from ME3Tweaks
protected static List<PropertyDescriptor> GetPropertyDescriptors( object instance, bool hideInheritedProperties )
{
PropertyDescriptorCollection descriptors;
TypeConverter tc = TypeDescriptor.GetConverter( instance );
if( tc == null || !tc.GetPropertiesSupported() )
{
if( instance is ICustomTypeDescriptor )
{
descriptors = ((ICustomTypeDescriptor)instance).GetProperties();
}
//ICustomTypeProvider is only available in .net 4.5 and over. Use reflection so the .net 4.0 and .net 3.5 still works.
else if( instance.GetType().GetInterface( "ICustomTypeProvider", true ) != null )
{
var methodInfo = instance.GetType().GetMethod( "GetCustomType" );
var result = methodInfo.Invoke( instance, null ) as Type;
descriptors = TypeDescriptor.GetProperties( result );
}
else
{
descriptors = TypeDescriptor.GetProperties( instance.GetType() );
}
}
else
{
descriptors = tc.GetProperties( instance );
}
if( ( descriptors != null ) )
{
var descriptorsProperties = descriptors.Cast<PropertyDescriptor>();
if( hideInheritedProperties )
{
var properties = from p in descriptorsProperties
where p.ComponentType == instance.GetType()
select p;
return properties.ToList();
}
else
{
return descriptorsProperties.ToList();
}
}
return null;
}
19
Source : DynamicMetadata.cs
with MIT License
from microsoftarchive
with MIT License
from microsoftarchive
[TestMethod]
public void SimpleAttachment()
{
MetadataStore.Container = new CompositionContainer();
DynamicMetadataTestClreplaced val = DynamicMetadataTestClreplaced.Get("42");
var notYetAttached = TypeDescriptor.GetConverter(val);
replacedert.IsFalse(notYetAttached.CanConvertFrom(typeof(string)), "The default type converter for DynamicMetadataTestClreplaced shouldn't support round tripping");
MetadataStore.AddAttribute(
typeof(DynamicMetadataTestClreplaced),
( type, attributes) =>
Enumerable.Concat(
attributes,
new Attribute[] { new TypeConverterAttribute(typeof(DynamicMetadataTestClreplacedConverter)) }
)
);
var attached = TypeDescriptor.GetConverter(val);
replacedert.IsTrue(attached.CanConvertFrom(typeof(string)), "The new type converter for DynamicMetadataTestClreplaced should support round tripping");
}
19
Source : FilterPipe.cs
with GNU General Public License v2.0
from nesherhh
with GNU General Public License v2.0
from nesherhh
internal void SaveTo(FiltersSection section)
{
FilterCollection filterCollection = section.Filters;
filterCollection.Clear();
foreach (IFilter filter in list)
{
Type filterType = filter.GetType();
FilterElement filterElement = new FilterElement();
filterElement.Name = filterType.Name;
filterElement.Type = filterType;
filterCollection.Add(filterElement);
foreach (PropertyInfo propertyInfo in filterType.GetProperties())
{
if (propertyInfo.Name != "LastResult")
{
FilterParameterElement parameter = new FilterParameterElement();
parameter.Name = propertyInfo.Name;
object propertyValue = propertyInfo.GetValue(filter, null);
parameter.Type = propertyValue.GetType();
TypeConverter converter = TypeDescriptor.GetConverter(propertyValue);
parameter.Value = converter.ConvertToString(propertyValue);
filterElement.Parameters.Add(parameter);
}
}
}
}
19
Source : ObjectView.cs
with GNU General Public License v3.0
from nstlaurent
with GNU General Public License v3.0
from nstlaurent
TypeConverter ICustomTypeDescriptor.GetConverter()
{
if (_isCustomTypeDescriptor)
{
return _customTypeDescriptor.GetConverter();
}
else
{
return TypeDescriptor.GetConverter(Object);
}
}
19
Source : DomainTextClipboardExporter.cs
with MIT License
from NtreevSoft
with MIT License
from NtreevSoft
protected override void StartDataItemField(DataGridContext dataGridContext, Column column, object fieldValue)
{
if (this.isFistColumn == true)
{
}
else
{
this.sb.Append("\t");
}
if (fieldValue != null)
{
var converter = System.ComponentModel.TypeDescriptor.GetConverter(fieldValue);
if (fieldValue is string)
{
var text = fieldValue.ToString();
text = text.Replace("\"", "\"\"").Replace(Environment.NewLine, "\n");
if (text.IndexOf('\n') >= 0)
{
text = text.WrapQuot();
}
this.sb.Append(text);
}
else
{
this.sb.Append(converter.ConvertToString(fieldValue));
}
}
this.isFistColumn = false;
}
19
Source : TypeHelper.cs
with MIT License
from Panallox
with MIT License
from Panallox
public static object Convert(string value, Type type)
{
var code = Type.GetTypeCode(type);
if (value == null)
return type.IsValueType && code != TypeCode.String ? Activator.CreateInstance(type) : null;
if (Nullable.IsreplacedignableFrom(type))
type = type.GenericTypeArguments.First();
if (code == TypeCode.DBNull)
return DBNull.Value;
if (code == TypeCode.Empty)
return null;
if (code == TypeCode.String)
return value;
var ex = new InvalidCastException($"Cannot convert '{value}' to '{type.FullName}'");
try
{
if (code == TypeCode.Boolean && char.IsNumber(value[0]) && int.TryParse(value, out var int32))
return int32 > 0;
var converter = TypeDescriptor.GetConverter(value);
if (converter != null && converter.CanConvertTo(type))
return converter.ConvertTo(value, type);
if (code != TypeCode.Object)
{
converter = TypeDescriptor.GetConverter(type);
return converter.ConvertFromString(null, CultureInfo.InvariantCulture, value);
}
}
catch
{
}
throw ex;
}
19
Source : ImageGreyer.cs
with MIT License
from Peregrine66
with MIT License
from Peregrine66
private void SetSources()
{
if (null == _image.Source)
return;
// in case greyscale image cannot be created set greyscale source to original Source first
_sourceGreyscale = _sourceColour = _image.Source;
try
{
BitmapSource colourBitmap;
if (_sourceColour is BitmapSource)
colourBitmap = _sourceColour as BitmapSource;
else if (_sourceColour is DrawingImage)
{
// support for DrawingImage as a source - thanks to Morten Schou who provided this code
colourBitmap = new RenderTargetBitmap((int)_sourceColour.Width,
(int)_sourceColour.Height,
96, 96,
PixelFormats.Default);
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingDC = drawingVisual.RenderOpen();
drawingDC.DrawImage(_sourceColour,
new Rect(new Size(_sourceColour.Height,
_sourceColour.Width)));
drawingDC.Close();
(colourBitmap as RenderTargetBitmap).Render(drawingVisual);
}
else
{
// get the string Uri for the original image source first
String stringUri = TypeDescriptor.GetConverter(_sourceColour).ConvertTo(_sourceColour, typeof(string)) as string;
// Create colour BitmapImage using an absolute Uri (generated from stringUri)
colourBitmap = new BitmapImage(GetAbsoluteUri(stringUri));
}
// create and cache greyscale ImageSource
_sourceGreyscale = new FormatConvertedBitmap(colourBitmap, PixelFormats.Gray8, null, 0);
}
catch (Exception e)
{
System.Diagnostics.Debug.Fail("The Image used cannot be greyed out.",
"Make sure absolute Uri is used, relative Uri may sometimes resolve incorrectly.\n\nException: " + e.Message);
}
}
19
Source : ResXResourceWriter.cs
with MIT License
from reactiveui
with MIT License
from reactiveui
private void AddResource(string name, object value, string comment)
{
if (value is string)
{
AddResource(name, (string)value, comment);
return;
}
if (name == null)
throw new ArgumentNullException(nameof(name));
if (written)
throw new InvalidOperationException("The resource is already generated.");
if (writer == null)
InitWriter();
if (value is byte[])
{
WriteBytes(name, value.GetType(), (byte[])value, comment);
return;
}
if (value is ResourceSerializedObject rso)
{
var bytes = rso.GetBytes();
WriteBytes(name, null, bytes, 0, bytes.Length, comment);
return;
}
if (value == null)
{
// nulls written as ResXNullRef
WriteString(name, "", ResXNullRefTypeName, comment);
return;
}
if (value != null && !value.GetType().IsSerializable)
throw new InvalidOperationException(String.Format("The element '{0}' of type '{1}' is not serializable.", name, value.GetType().Name));
var converter = TypeDescriptor.GetConverter(value);
if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
{
var str = (string)converter.ConvertToInvariantString(value);
WriteString(name, str, value.GetType().replacedemblyQualifiedName, comment);
return;
}
if (converter != null && converter.CanConvertTo(typeof(byte[])) && converter.CanConvertFrom(typeof(byte[])))
{
var b = (byte[])converter.ConvertTo(value, typeof(byte[]));
WriteBytes(name, value.GetType(), b, comment);
return;
}
var ms = new MemoryStream();
var fmt = new BinaryFormatter();
try
{
fmt.Serialize(ms, value);
}
catch (Exception e)
{
throw new InvalidOperationException("Cannot add a " + value.GetType() +
"because it cannot be serialized: " +
e.Message);
}
WriteBytes(name, null, ms.GetBuffer(), 0, (int)ms.Length, comment);
ms.Close();
}
19
Source : ResXResourceWriter.cs
with MIT License
from reactiveui
with MIT License
from reactiveui
public void AddMetadata(string name, object value)
{
if (value is string)
{
AddMetadata(name, (string)value);
return;
}
if (value is byte[])
{
AddMetadata(name, (byte[])value);
return;
}
if (name == null)
throw new ArgumentNullException(nameof(name));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (!value.GetType().IsSerializable)
throw new InvalidOperationException(String.Format("The element '{0}' of type '{1}' is not serializable.", name, value.GetType().Name));
if (written)
throw new InvalidOperationException("The resource is already generated.");
if (writer == null)
InitWriter();
var type = value.GetType();
var converter = TypeDescriptor.GetConverter(value);
if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
{
var str = (string)converter.ConvertToInvariantString(value);
writer.WriteStartElement("metadata");
writer.WriteAttributeString("name", name);
if (type != null)
writer.WriteAttributeString("type", type.replacedemblyQualifiedName);
writer.WriteStartElement("value");
writer.WriteString(str);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteWhitespace("\n ");
return;
}
if (converter != null && converter.CanConvertTo(typeof(byte[])) && converter.CanConvertFrom(typeof(byte[])))
{
var b = (byte[])converter.ConvertTo(value, typeof(byte[]));
writer.WriteStartElement("metadata");
writer.WriteAttributeString("name", name);
if (type != null)
{
writer.WriteAttributeString("type", type.replacedemblyQualifiedName);
writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType);
writer.WriteStartElement("value");
WriteNiceBase64(b, 0, b.Length);
}
else
{
writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType);
writer.WriteStartElement("value");
writer.WriteBase64(b, 0, b.Length);
}
writer.WriteEndElement();
writer.WriteEndElement();
return;
}
var ms = new MemoryStream();
var fmt = new BinaryFormatter();
try
{
fmt.Serialize(ms, value);
}
catch (Exception e)
{
throw new InvalidOperationException("Cannot add a " + value.GetType() +
"because it cannot be serialized: " +
e.Message);
}
writer.WriteStartElement("metadata");
writer.WriteAttributeString("name", name);
if (type != null)
{
writer.WriteAttributeString("type", type.replacedemblyQualifiedName);
writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType);
writer.WriteStartElement("value");
WriteNiceBase64(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
else
{
writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType);
writer.WriteStartElement("value");
writer.WriteBase64(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}
writer.WriteEndElement();
writer.WriteEndElement();
ms.Close();
}
19
Source : RTC_CustomEngine.cs
with MIT License
from redscientistlabs
with MIT License
from redscientistlabs
public static PartialSpec LoadTemplateFile(string Filename = null)
{
if (Filename == null)
{
OpenFileDialog ofd = new OpenFileDialog
{
DefaultExt = "cet",
replacedle = "Open Engine Template File",
Filter = "CET files|*.cet",
RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
Filename = ofd.FileName;
}
else
{
return null;
}
}
PartialSpec pSpec = new PartialSpec("RTCSpec");
try
{
using (FileStream fs = File.Open(Filename, FileMode.OpenOrCreate))
{
Dictionary<string, object> d = JsonHelper.Deserialize<Dictionary<string, object>>(fs);
//We don't want to store type data in the serialized data but specs store object
//To work around this, we store the type in a dictionary and preplaced the data through a typeconverter
foreach (var k in d.Keys)
{
var t = d[k];
//If the type doesn't exist, just use what it's parsed as
if (!name2TypeDico.ContainsKey(k))
{
pSpec[k] = t;
continue;
}
var type = name2TypeDico[k];
if (t.GetType() != type)
{
//There's no typeconverter for bigint so we have to handle it manually. Convert it to a string then bigint it
if (type == typeof(BigInteger))
{
if (BigInteger.TryParse(t.ToString(), out BigInteger a))
{
t = a;
}
else
{
throw new Exception("Couldn't convert " + t.ToString() +
" to BigInteger! Something is wrong with your template.");
}
}
//ULong64 gets deserialized to bigint for some reason?????
else if (t is BigInteger _t && _t <= ulong.MaxValue)
{
t = (ulong)(_t & ulong.MaxValue);
}
//handle the enums
else if (type.BaseType == typeof(Enum))
{
//We can't use tryparse here so we have to catch the exception
try
{
t = Enum.Parse(type, t.ToString());
}
catch (ArgumentException e)
{
throw new Exception("Couldn't convert " + t.ToString() +
" to " + type.Name + "! Something is wrong with your template.", e);
}
}
else
{
t = TypeDescriptor.GetConverter(t).ConvertTo(t, type);
}
}
pSpec[k] = t;
}
}
}
catch (Exception e)
{
MessageBox.Show("The Template file could not be loaded" + e);
return null;
}
//Overwrites spec path with loaded path
pSpec[RTCSPEC.CUSTOM_PATH] = Filename;
return pSpec;
}
19
Source : DaggerBasePin.cs
with MIT License
from richinsley
with MIT License
from richinsley
protected void SetData(object data)
{
if (data == null)
{
_data = null;
}
try
{
_data = data;
}
catch(InvalidCastException ex)
{
//we need to convert the data
TypeConverter tc = TypeDescriptor.GetConverter(data);
if (tc is BooleanConverter)
{
// BooleanConverters only go to/from text so change data to an Int holding 0 or 1
// then get a IntTypeConverter
data = (int)(((bool)data) ? 1 : 0);
tc = TypeDescriptor.GetConverter(data);
}
if (tc != null)
{
if(tc.CanConvertTo(_dataType))
{
_data = tc.ConvertTo(data, _dataType);
}
else
{
//can't convert
throw new InvalidCastException();
}
}
else
{
//no IConvertible available
throw new InvalidCastException();
}
}
if (PinDataSet != null)
{
PinDataSet(this, _data);
}
}
19
Source : CharFA.CodeGeneration.cs
with MIT License
from SpecFlowOSS
with MIT License
from SpecFlowOSS
static CodeExpression _Serialize(object val)
{
if (null == val)
return new CodePrimitiveExpression(null);
if (val is char) // special case for unicode nonsense
{
// console likes to cook unicode characters
// so we render them as ints cast to the character
if (((char)val) > 0x7E)
return new CodeCastExpression(typeof(char), new CodePrimitiveExpression((int)(char)val));
return new CodePrimitiveExpression((char)val);
}
else
if (val is bool ||
val is string ||
val is short ||
val is ushort ||
val is int ||
val is uint ||
val is ulong ||
val is long ||
val is byte ||
val is sbyte ||
val is float ||
val is double ||
val is decimal)
{
// TODO: mess with strings to make them console safe.
return new CodePrimitiveExpression(val);
}
if (val is Array && 1 == ((Array)val).Rank && 0 == ((Array)val).GetLowerBound(0))
{
return _SerializeArray((Array)val);
}
var conv = TypeDescriptor.GetConverter(val);
if (null != conv)
{
if (conv.CanConvertTo(typeof(InstanceDescriptor)))
{
var desc = conv.ConvertTo(val, typeof(InstanceDescriptor)) as InstanceDescriptor;
if (!desc.IsComplete)
throw new NotSupportedException(
string.Format(
"The type \"{0}\" could not be serialized.",
val.GetType().FullName));
var ctor = desc.MemberInfo as ConstructorInfo;
if (null != ctor)
{
var result = new CodeObjectCreateExpression(ctor.DeclaringType);
foreach (var arg in desc.Arguments)
result.Parameters.Add(_Serialize(arg));
return result;
}
throw new NotSupportedException(
string.Format(
"The instance descriptor for type \"{0}\" is not supported.",
val.GetType().FullName));
}
else
{
// we special case for KeyValuePair types.
var t = val.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
// TODO: Find a workaround for the bug with VBCodeProvider
// may need to modify the reference source
var kvpType = new CodeTypeReference(typeof(KeyValuePair<,>));
foreach (var arg in val.GetType().GetGenericArguments())
kvpType.TypeArguments.Add(arg);
var result = new CodeObjectCreateExpression(kvpType);
for (int ic = kvpType.TypeArguments.Count, i = 0; i < ic; ++i)
{
var prop = val.GetType().GetProperty(0 == i ? "Key" : "Value");
result.Parameters.Add(_Serialize(prop.GetValue(val)));
}
return result;
}
throw new NotSupportedException(
string.Format("The type \"{0}\" could not be serialized.",
val.GetType().FullName));
}
}
else
throw new NotSupportedException(
string.Format(
"The type \"{0}\" could not be serialized.",
val.GetType().FullName));
}
19
Source : SettingsStore.cs
with MIT License
from TestCentric
with MIT License
from TestCentric
public void SaveSettings()
{
if (!_writeable || _settings.Keys.Count <= 0)
return;
try
{
string dirPath = Path.GetDirectoryName(_settingsFile);
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
var stream = new MemoryStream();
using (var writer = new XmlTextWriter(stream, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
writer.WriteProcessingInstruction("xml", "version=\"1.0\"");
writer.WriteStartElement("NUnitSettings");
writer.WriteStartElement("Settings");
List<string> keys = new List<string>(_settings.Keys);
keys.Sort();
foreach (string name in keys)
{
object val = GetSetting(name);
if (val != null)
{
writer.WriteStartElement("Setting");
writer.WriteAttributeString("name", name);
writer.WriteAttributeString("value",
TypeDescriptor.GetConverter(val).ConvertToInvariantString(val));
writer.WriteEndElement();
}
}
writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
var reader = new StreamReader(stream, Encoding.UTF8, true);
stream.Seek(0, SeekOrigin.Begin);
var contents = reader.ReadToEnd();
File.WriteAllText(_settingsFile, contents, Encoding.UTF8);
}
}
catch (Exception)
{
// So we won't try this again
_writeable = false;
throw;
}
}
19
Source : GreyableImage.cs
with GNU General Public License v3.0
from xmlexplorer
with GNU General Public License v3.0
from xmlexplorer
private void SetSources()
{
// in case greyscale image cannot be created set greyscale source to original Source first
_sourceG = _sourceC = Source;
// create Opacity Mask for greyscale image as FormatConvertedBitmap does not keep transparency info
_opacityMaskG = new ImageBrush(_sourceC);
_opacityMaskG.Opacity = 0.6;
try
{
// get the string Uri for the original image source first
String stringUri = TypeDescriptor.GetConverter(Source).ConvertTo(Source, typeof(string)) as string;
Uri uri = null;
// try to resolve it as an absolute Uri (if it is relative and used it as is
// it is likely to point in a wrong direction)
if (!Uri.TryCreate(stringUri, UriKind.Absolute, out uri))
{
// it seems that the Uri is relative, at this stage we can only replacedume that
// the image requested is in the same replacedembly as this oblect,
// so we modify the string Uri to make it absolute ...
stringUri = "pack://application:,,,/" + stringUri.TrimStart(new char[2] { System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar });
// ... and try to resolve again
uri = new Uri(stringUri);
}
// create and cache greyscale ImageSource
_sourceG = new FormatConvertedBitmap(new BitmapImage(uri), PixelFormats.Gray8, null, 0);
}
catch (Exception e)
{
System.Diagnostics.Debug.Fail("The Image used cannot be greyed out.",
"Use BitmapImage or URI as a Source in order to allow greyscaling. Make sure the absolute Uri is used as relative Uri may sometimes resolve incorrectly.\n\nException: " + e.Message);
}
}
19
Source : UIniFileEx.cs
with GNU General Public License v3.0
from yhuse
with GNU General Public License v3.0
from yhuse
private void SetValue(string section, string key, object value)
{
if (value == null)
{
this[section][key] = string.Empty;
}
else
{
TypeConverter conv = TypeDescriptor.GetConverter(value);
if (!conv.CanConvertTo(typeof(string)))
{
this[section][key] = value.ToString();
}
else
{
this[section][key] = (string)conv.ConvertTo(value, typeof(string));
}
}
UpdateFile();
}
19
Source : NumberUtils.cs
with Apache License 2.0
from zhangzihan
with Apache License 2.0
from zhangzihan
public static bool CanConvertToDecimal(object number)
{
TypeConverter converter = TypeDescriptor.GetConverter(number);
return converter.CanConvertTo(typeof(Single))
|| converter.CanConvertTo(typeof(Double))
|| converter.CanConvertTo(typeof(Decimal))
;
}
19
Source : NumberUtils.cs
with Apache License 2.0
from zhangzihan
with Apache License 2.0
from zhangzihan
public static bool CanConvertToInteger(object number)
{
TypeConverter converter = TypeDescriptor.GetConverter(number);
return converter.CanConvertTo(typeof(Int32))
|| converter.CanConvertTo(typeof(Int16))
|| converter.CanConvertTo(typeof(Int64))
|| converter.CanConvertTo(typeof(UInt16))
|| converter.CanConvertTo(typeof(UInt64))
|| converter.CanConvertTo(typeof(Byte))
|| converter.CanConvertTo(typeof(SByte))
;
}
19
Source : ObjectExtensions.cs
with Apache License 2.0
from zqlovejyc
with Apache License 2.0
from zqlovejyc
public static T To<T>(this object @this)
{
if (@this != null)
{
var targetType = typeof(T);
if (@this.GetType() == targetType)
return (T)@this;
var converter = TypeDescriptor.GetConverter(@this);
if (converter != null)
{
if (converter.CanConvertTo(targetType))
return (T)converter.ConvertTo(@this, targetType);
}
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null)
{
if (converter.CanConvertFrom(@this.GetType()))
return (T)converter.ConvertFrom(@this);
}
if (@this == DBNull.Value)
return (T)(object)null;
}
return @this == null ? default : (T)@this;
}
19
Source : Utilities.cs
with MIT License
from zzzprojects
with MIT License
from zzzprojects
internal static object To(this Object @this, Type type)
{
if (@this != null)
{
Type targetType = type;
if (@this.GetType() == targetType)
{
return @this;
}
TypeConverter converter = TypeDescriptor.GetConverter(@this);
if (converter != null)
{
if (converter.CanConvertTo(targetType))
{
return converter.ConvertTo(@this, targetType);
}
}
converter = TypeDescriptor.GetConverter(targetType);
if (converter != null)
{
if (converter.CanConvertFrom(@this.GetType()))
{
return converter.ConvertFrom(@this);
}
}
if (@this == DBNull.Value)
{
return null;
}
}
return @this;
}