using System; using System.Text; using XYLEM.Communication; namespace XYLEM.Communication.ValueEncoders { public static class StringEncoder { public static Encoding GetDefaultEncoding( ) { try { return Encoding.GetEncoding( "Windows-1252"/*Strings._CONFIG_STD_String_DefaultCharacterEncoding*/ ); } catch (Exception ex) { throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rGetDefaultEncoding"+ "\n\rError when making default encoding with = "+ "\n\rWindows-1252"/*Strings._CONFIG_STD_String_DefaultCharacterEncoding*/, ex ); } //Legacy code return Encoding.GetEncoding( 1252 ); } /// /// Standard Windows iso-8859-1-encoding page. /// static Encoding s_Encoder = GetDefaultEncoding( ); // Default Fallback /// /// /// /// /// /// ex. "iso-8859-1" /// public static byte[] Encode(string value, int lenght, string CharacterSet) { if (value.Length > lenght) { throw new ArgumentException( "value.Length is too long", "value" ); } var result = new byte[ lenght ]; try { if (!String.IsNullOrEmpty( CharacterSet )) { Encoding.GetEncoding( CharacterSet ).GetBytes( value ).CopyTo( result, 0 ); return result; } } catch (Exception ex) { throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rEncode"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ + Environment.NewLine + ex.Message ); } // Use defalt s_Encoder.GetBytes( value ).CopyTo( result, 0 ); return result; } /// /// Use default characterSet /// /// /// /// public static byte[] Encode(string value, int lenght) { return Encode( value, lenght, null ); } /// /// /// /// /// /// ex. "iso-8859-1" /// public static string Decode(byte[] value, int lenght, string CharacterSet) { if (value.Length != lenght) { throw new ArgumentException( "value.Length wrong lenght", "value" ); } string result = null; try { if (!String.IsNullOrEmpty( CharacterSet )) { result = Encoding.GetEncoding( CharacterSet ).GetString( value ); } } catch (Exception ex) { throw new Exception( typeof( StringEncoder ).ToString( )+ "\n\rDecode()"+ "\n\rWith = " + "iso-8859-1"/*Strings._CONFIG_STD_Email_DefaultCharacterEncoding*/ + Environment.NewLine + ex.Message ); } // Use defalt if (result == null) { result = s_Encoder.GetString( value ); } var index = result.IndexOf( '\0' ); if (index >= 0) return result.Substring( 0, result.IndexOf( '\0' ) ); else return result; } /// /// Use default characterSet /// /// /// /// public static string Decode(byte[] value, int lenght) { return Decode( value, lenght, null ); } } }