using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
namespace Orthogonal.Common
{
///
/// This class is a custom TypeConverter for converting byte arrays to and from string
/// representations. It is intended for use in the control.
///
public class ByteArrayConverter : TypeConverter
{
//==================================================================================
public ByteArrayConverter()
{
}
//==================================================================================
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType.GetType().IsArray)
return true;
return base.CanConvertTo (context, destinationType);
}
//==================================================================================
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom (context, sourceType);
}
//==================================================================================
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if ((destinationType == typeof(string)) && (value is Array))
{
Array arr = (Array)value;
if (arr.GetType().GetElementType() == typeof(byte))
{
byte[] arrbytes = (byte[])value;
return string.Format("{0}",Utils.BytesToString(arrbytes,0));
}
}
return base.ConvertTo (context, culture, value, destinationType);
}
//==================================================================================
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
string s = (string)value;
if (s.Length == 0)
throw new Exception("At least one pair of hexadecimal digits is required");
if (!Utils.IsHexString(s))
throw new Exception("The string is not valid pairs of hexadecimal digits");
return Utils.StringToBytes(s);
}
return base.ConvertFrom (context, culture, value);
}
}
}
/* Utility methods used in the converter code above, copied from another file.
public static bool IsHexString(string s)
{
const string HEXCHARS = "0123456789abcdefABCDEF";
if (s == null)
return false;
if ((s.Length % 2) != 0)
return false;
for (int i=0; i byteArray.Length))
throw new ArgumentOutOfRangeException("offset",offset,"offset is negative or beyond the byte array length");
for (int i=0; i 0) && (gap>0) && (i%gap==0))
sb.Append(" ");
sb.Append(x2);
}
return sb.ToString();
}
*/