using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using XYLEM.Base; namespace XYLEM.Communication.ValueEncoders { /// /// IP Address encoder when it has to be converted to a u32 value /// internal static class U32_IP_Encoder { /// /// Check if string is okay and possible to encode /// /// /// internal static bool IsOkay(string stringForCheck) { try { if (string.IsNullOrEmpty( stringForCheck )) { return false; // if string empty, then this is off and there is nothing to check } try { var test = Encode( stringForCheck ); } catch { return false; // Error is not possible to convert } return true; // Okay to convert } catch (Exception ex) { throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "IsOkay" ) ); } } /// /// Encode xxx.xxx.xxx.xxx to bytes /// /// /// static internal byte[] Encode(string ip_XXX_XXX_XXX_XXX) { try { var splited = ip_XXX_XXX_XXX_XXX.Split( '.' ); if (splited.Count( ) != 4) { throw new Exception( "IP must be formated xxx.xxx.xxx.xxx but is " + ip_XXX_XXX_XXX_XXX.ToString( ) ); } var values = splited.Select( value => byte.Parse( value ) ); return values.ToArray( ); } catch (Exception ex) { throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "Encode" ) ); } } /// /// decode bytes /// /// /// xxx.xxx.xxx.xxx static internal string Decode(byte[] data) { try { if ((data == null) || (data.Count( ) != 4)) { throw new Exception( "Must be 4 bytes" ); } return String.Format( "{0}.{1}.{2}.{3}", data[ 0 ], data[ 1 ], data[ 2 ], data[ 3 ] ); } catch (Exception ex) { throw new Exception( ex.ToFuncErrorText( typeof( U32_IP_Encoder ).ToString( ), "Decode" ) ); } } } }