EncodingConverter.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //-----------------------------------------------------------------------------
  4. namespace System.ServiceModel.Configuration
  5. {
  6. using System;
  7. using System.ComponentModel;
  8. using System.ComponentModel.Design.Serialization;
  9. using System.Globalization;
  10. using System.ServiceModel.Channels;
  11. using System.Text;
  12. class EncodingConverter : TypeConverter
  13. {
  14. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  15. {
  16. if (typeof(string) == sourceType)
  17. {
  18. return true;
  19. }
  20. return base.CanConvertFrom(context, sourceType);
  21. }
  22. public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
  23. {
  24. if (typeof(InstanceDescriptor) == destinationType)
  25. {
  26. return true;
  27. }
  28. return base.CanConvertTo(context, destinationType);
  29. }
  30. public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
  31. {
  32. if (value is string)
  33. {
  34. string encoding = (string)value;
  35. Encoding retval;
  36. if (String.Compare(encoding, TextEncoderDefaults.EncodingString, StringComparison.OrdinalIgnoreCase) == 0)
  37. {
  38. // special case for utf-8 to match with what we do in the default text encoding
  39. retval = TextEncoderDefaults.Encoding;
  40. }
  41. else
  42. {
  43. retval = Encoding.GetEncoding(encoding);
  44. }
  45. if (retval == null)
  46. {
  47. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.ConfigInvalidEncodingValue, encoding));
  48. }
  49. return retval;
  50. }
  51. return base.ConvertFrom(context, culture, value);
  52. }
  53. public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
  54. {
  55. if (typeof(string) == destinationType && value is Encoding)
  56. {
  57. Encoding encoding = (Encoding)value;
  58. return encoding.HeaderName;
  59. }
  60. return base.ConvertTo(context, culture, value, destinationType);
  61. }
  62. }
  63. }