/// Encodes the specified string. /// @param text The string to encode. /// @returns The encoded string. public string Encode(string text) { var buffer = Encoding.Default.GetBytes(text); var hash = MD2.Create().ComputeHash(buffer); return(HexCodec.GetString(hash)); }
public void TestCodec() { var buf = HexCodec.HexDecode("A"); Assert.Equal(0x0a, buf[0]); EncodeDecode("A"); EncodeDecode("0123456789ABCDEF"); buf = HexCodec.HexDecode("0123456789ABCDEF"); Assert.Equal(1, buf[0]); Assert.Equal(0x23, buf[1]); Assert.Equal(0x45, buf[2]); Assert.Equal(0x67, buf[3]); Assert.Equal(0x89, buf[4] & 0xff); Assert.Equal(0xab, buf[5] & 0xff); Assert.Equal(0xcd, buf[6] & 0xff); Assert.Equal(0xef, buf[7] & 0xff); buf = HexCodec.HexDecode("ABC"); Assert.Equal(0x0a, buf[0] & 0xff); Assert.Equal(0xbc, buf[1] & 0xff); EncodeDecode("ABC"); }
public override IsoValue Parse(int field, sbyte[] buf, int pos, ICustomField custom) { if (pos < 0) { throw new ParseException($"Invalid BINARY field {field} position {pos}"); } if (pos + Length * 2 > buf.Length) { throw new ParseException($"Insufficient data for BINARY field {field} of length {Length}, pos {pos}"); } var s = buf.ToString(pos, Length * 2, Encoding.Default); //var binval = HexCodec.HexDecode(Encoding.ASCII.GetString(buf, // pos, // Length * 2)); var binval = HexCodec.HexDecode(s); if (custom == null) { return(new IsoValue(IsoType, binval, binval.Length)); } s = buf.ToString(pos, Length * 2, Encoding); //var dec = custom.DecodeField(Encoding.GetString(buf, // pos, // Length * 2)); var dec = custom.DecodeField(s); return(dec == null ? new IsoValue(IsoType, binval, binval.Length) : new IsoValue(IsoType, dec, Length, custom)); }
public void TestParseLengthWithRadix10() { // Given var input = "0100" + // MTI "7000000000000000" + // bitmap "10" + "ABCDEFGHIJ" + // F2 length (10 = 10) + value "26" + "01234567890123456789012345" + // F3 length (26 = 26) + value "ZZZZZZZZ"; // F4 // When IsoMessage m = mfact.ParseMessage(input.GetSignedBytes(), 0); // Then Assert.NotNull(m); Assert.Equal("ABCDEFGHIJ", m.GetObjectValue(2)); Assert.Equal("01234567890123456789012345", HexCodec.HexEncode((sbyte[])m.GetObjectValue(3), 0, 13)); Assert.Equal("ZZZZZZZZ", m.GetObjectValue(4)); }
/// <summary> /// Crée une URI à en-tête "pack" qui pointe sur une ressource de l'assemblage spécifié. /// </summary> /// <param name="uri">URI de la ressource référencée.</param> /// <param name="assembly">Assemblage contenant la ressource référencée.</param> /// <param name="useStrongName">Valeur indiquant si l'URI retournée utilise le nom fort (i.e. avec le numéro de version et le jeton de clé publique) de l'assemblage spécifié.</param> /// <returns>URI à en-tête "pack" qui pointe sur la ressource référencée de l'assemblage spécifié.</returns> /// <exception cref="ArgumentNullException">L'URI ou l'assemblage spécifié est une référence null.</exception> public static Uri MakePack(this Uri uri, Assembly assembly, bool useStrongName) { // Validation des arguments if (uri == null) { throw new ArgumentNullException("uri"); } if (assembly == null) { throw new ArgumentNullException("assembly"); } // En-tête "pack" var builder = new StringBuilder("pack://application:,,,/"); // Nom de l'assemblage if (!useStrongName) { builder.Append(assembly.FullName.Split(',')[0]); } else { var assemblyName = assembly.GetName(); builder.Append(assemblyName.Name); builder.Append(";v"); builder.Append(assemblyName.Version); builder.Append(';'); builder.Append(HexCodec.GetString(assemblyName.GetPublicKeyToken())); } // Chemin de la ressource var absolutePath = (uri.IsAbsoluteUri) ? uri.AbsolutePath : uri.OriginalString.Split('?')[0]; if (!absolutePath.StartsWith("/", StringComparison.Ordinal)) { absolutePath = '/' + absolutePath; } builder.Append(";component"); builder.Append(absolutePath); return(new Uri(builder.ToString())); }
public override IsoValue ParseBinary(int field, sbyte[] buf, int pos, ICustomField custom) { if (pos < 0) { throw new ParseException($"Invalid BINARY field {field} position {pos}"); } if (pos + Length > buf.Length) { throw new ParseException($"Insufficient data for BINARY field {field} of length {Length}, pos {pos}"); } var v = new sbyte[Length]; var sbytes = buf; Array.Copy(sbytes, pos, v, 0, Length); if (custom == null) { return(new IsoValue(IsoType, v, Length)); } var dec = custom.DecodeField(HexCodec.HexEncode(v, 0, v.Length)); return(dec == null ? new IsoValue(IsoType, v, Length) : new IsoValue(IsoType, dec, Length, custom)); }
public void Downgrades128BitTraceIdToLower64Bits() { string hex128Bits = "463ac35c9f6413ad48485a3953bb6124"; string lower64Bits = "48485a3953bb6124"; DelegatingTextMap textMap = new DelegatingTextMap(); textMap.Set(B3TextMapCodec.TraceIdName, hex128Bits); textMap.Set(B3TextMapCodec.SpanIdName, lower64Bits); textMap.Set(B3TextMapCodec.ParentSpanIdName, "0"); textMap.Set(B3TextMapCodec.SampledName, "1"); textMap.Set(B3TextMapCodec.FlagsName, "1"); SpanContext context = b3Codec.Extract(textMap); //Assert.NotNull(HexCodec.LowerHexToUnsignedLong(lower64Bits)); Assert.Equal(HexCodec.LowerHexToUnsignedLong(lower64Bits), context.TraceId.Low); Assert.Equal(HexCodec.LowerHexToUnsignedLong(lower64Bits), context.SpanId); Assert.Equal(new SpanId(0), context.ParentId); Assert.True(context.Flags.HasFlag(SpanContextFlags.Sampled)); Assert.True(context.Flags.HasFlag(SpanContextFlags.Debug)); }
public void EncodeDecode(string hex) { var buf = HexCodec.HexDecode(hex); Assert.Equal(hex.Length / 2 + hex.Length % 2, buf.Length); var reenc = HexCodec.HexEncode(buf, 0, buf.Length); if (reenc.StartsWith("0", StringComparison.Ordinal) && !hex.StartsWith("0", StringComparison.Ordinal)) { Assert.Equal(reenc.Substring(1), hex); } else { Assert.Equal(hex, reenc); } }
public void TestMessage() { var trama = HexCodec.HexDecode( "f1f8f1f42030010002000000f0f0f0f0f0f0f0f1f5f9f5f5f1f3f0f6f1f2f1f1f2f9f0f8f8f3f1f8f0f0"); var mfact = new MessageFactory <IsoMessage> { UseBinaryBitmap = true }; var pinfo = new Dictionary <int, FieldParseInfo> { { 3, new AlphaParseInfo(6) }, { 11, new AlphaParseInfo(6) }, { 12, new AlphaParseInfo(12) }, { 24, new AlphaParseInfo(3) }, { 39, new AlphaParseInfo(3) } }; mfact.SetParseMap(0x1814, pinfo); mfact.Encoding = CodePagesEncodingProvider.Instance.GetEncoding(1047); mfact.ForceStringEncoding = true; var iso = mfact.ParseMessage(trama, 0); Assert.NotNull(iso); Assert.Equal("000000", iso.GetObjectValue(3)); Assert.Equal("015955", iso.GetObjectValue(11)); Assert.Equal("130612112908", iso.GetObjectValue(12)); Assert.Equal("831", iso.GetObjectValue(24)); Assert.Equal("800", iso.GetObjectValue(39)); }
public void TestMessages() { //Create a message with both factories var ascii = _mfactAscii.NewMessage(0x600); var bin = _mfactBin.NewMessage(0x600); Assert.False(ascii.Binary || ascii.BinBitmap); Assert.True(bin.Binary); //HEXencode the binary message, headers should be similar to the ASCII version sbyte[] v = bin.WriteData(); var hexBin = HexCodec.HexEncode(v, 0, v.Length); var hexAscii = ascii.WriteData().SbyteString(Encoding.Default).ToUpper(CultureInfo.CurrentCulture); Assert.Equal("0600", hexBin.Substring(0, 4)); //Should be the same up to the field 42 (first 80 chars) Assert.Equal(hexAscii.Substring(0, 88), hexBin.Substring(0, 88)); Assert.Equal(ascii.GetObjectValue(43), v.SbyteString(44, 40, Encoding.Default).Trim()); //Parse both messages sbyte[] asciiBuf = ascii.WriteData(); IsoMessage ascii2 = _mfactAscii.ParseMessage(asciiBuf, 0); TestParsed(ascii2); Assert.Equal(ascii.GetObjectValue(7).ToString(), ascii2.GetObjectValue(7).ToString()); IsoMessage bin2 = _mfactBin.ParseMessage(bin.WriteData(), 0); //Compare values, should be the same TestParsed(bin2); Assert.Equal(bin.GetObjectValue(7).ToString(), bin2.GetObjectValue(7).ToString()); //Test the debug string ascii.SetValue(60, "XXX", IsoType.LLVAR, 0); bin.SetValue(60, "XXX", IsoType.LLVAR, 0); Assert.Equal(ascii.DebugString(), bin.DebugString()); // "Debug strings differ" Assert.True(ascii.DebugString().Contains("03XXX"), "LLVAR fields wrong"); }
public override IsoValue Parse(int field, sbyte[] buf, int pos, ICustomField custom) { if (pos < 0) { throw new ParseException($"Invalid LLLBIN field {field} pos {pos}"); } if (pos + 3 > buf.Length) { throw new ParseException($"Insufficient LLLBIN header field {field}"); } var l = DecodeLength(buf, pos, 3); if (l < 0) { throw new ParseException($"Invalid LLLBIN length {l} field {field} pos {pos}"); } if (l + pos + 3 > buf.Length) { throw new ParseException($"Insufficient data for LLLBIN field {field}, pos {pos}"); } var binval = l == 0 ? new sbyte[0] : HexCodec.HexDecode(buf.SignedBytesToString(pos + 3, l, Encoding.Default)); if (custom == null) { return(new IsoValue(IsoType, binval, binval.Length)); } var customBinaryField = custom as ICustomBinaryField; if (customBinaryField != null) { try { var dec = customBinaryField.DecodeBinaryField(buf, pos + 3, l); return(dec == null ? new IsoValue(IsoType, binval, binval.Length) : new IsoValue(IsoType, dec, 0, custom)); } catch (Exception) { throw new ParseException($"Insufficient data for LLLBIN field {field}, pos {pos}"); } } try { var dec = custom.DecodeField(l == 0 ? "" : buf.SignedBytesToString(pos + 3, l, Encoding.Default)); return(dec == null ? new IsoValue(IsoType, binval, binval.Length) : new IsoValue(IsoType, dec, l, custom)); } catch (Exception) { throw new Exception($"Insufficient data for LLLBIN field {field}, pos {pos}"); } }
public void TestPartial() { Assert.Equal("FF01", HexCodec.HexEncode(new byte[] { 0, 0xff, 1, 2, 3, 4 }.ToInt8(), 1, 2)); }
//// ===================================================================================== /// <summary> /// Calcule la valeur de hachage MD5 pour le tableau d'octets spécifié. /// </summary> /// <param name="buffer">Entrée pour laquelle le code de hachage doit être calculé.</param> /// <returns>Code de hachage calculé, exprimé sous forme de chaîne hexadécimale.</returns> public static string ComputeMD5(byte[] buffer) { return(HexCodec.GetString(MD5.Create().ComputeHash(buffer))); }
private static void ParseHeaders <T>(XmlNodeList nodes, MessageFactory <T> mfact) where T : IsoMessage { List <XmlElement> refs = null; for (var i = 0; i < nodes.Count; i++) { var elem = (XmlElement)nodes.Item(i); if (elem == null) { continue; } var type = ParseType(elem.GetAttribute("type")); if (type == -1) { throw new IOException($"Invalid type {elem.GetAttribute("type")} for ISO8583 header: "); } if (elem.ChildNodes.Count == 0) { if (elem.GetAttribute("ref") != null && !string.IsNullOrEmpty(elem.GetAttribute("ref"))) { refs ??= new List <XmlElement>(nodes.Count - i); refs.Add(elem); } else { throw new IOException("Invalid ISO8583 header element"); } } else { var header = elem.ChildNodes.Item(0)?.Value; var binHeader = "true".Equals(elem.GetAttribute("binary")); if (Logger.IsEnabled(LogEventLevel.Debug)) { var binary = binHeader ? "binary" : string.Empty; Logger.Debug( $"Adding {binary} ISO8583 header for type {elem.GetAttribute("type")} : {header}"); } if (binHeader) { mfact.SetBinaryIsoHeader( type, HexCodec.HexDecode(header).ToUnsignedBytes()); } else { mfact.SetIsoHeader( type, header); } } } if (refs == null) { return; } { foreach (var elem in refs) { if (elem == null) { continue; } var type = ParseType(elem.GetAttribute("type")); if (type == -1) { throw new IOException("Invalid type for ISO8583 header: " + elem.GetAttribute("type")); } if (elem.GetAttribute("ref") == null || elem.GetAttribute("ref").IsEmpty()) { continue; } var t2 = ParseType(elem.GetAttribute("ref")); if (t2 == -1) { throw new IOException( "Invalid type reference " + elem.GetAttribute("ref") + " for ISO8583 header " + type); } var h = mfact.GetIsoHeader(t2); if (h == null) { throw new ArgumentException("Header def " + type + " refers to nonexistent header " + t2); } if (Logger.IsEnabled(LogEventLevel.Debug)) { Logger.Debug( "Adding ISO8583 header for type {Type}: {H} (copied from {Ref})", elem.GetAttribute("type"), h, elem.GetAttribute("ref")); } mfact.SetIsoHeader( type, h); } } }
public void TestPartial() { Assert.Equal("FF01", HexCodec.HexEncode(new byte[] { 0, (byte)0xff, 1, 2, 3, 4 }.ToSignedBytes(), 1, 2)); }
private void TestFieldType(IsoType type, FieldParseInfo fieldParser, int offset1, int offset2) { var bigintCodec = new BigIntBcdCodec(); var longCodec = new LongBcdCodec(); var mfact = new MessageFactory <IsoMessage>(); var tmpl = new IsoMessage { Binary = true, Type = 0x200 }; tmpl.SetValue(2, 1234567890L, longCodec, type, 0); tmpl.SetValue(3, b29, bigintCodec, type, 0); mfact.AddMessageTemplate(tmpl); mfact.SetCustomField(2, longCodec); mfact.SetCustomField(3, bigintCodec); var parser = new Dictionary <int, FieldParseInfo> { { 2, fieldParser }, { 3, fieldParser } }; mfact.SetParseMap(0x200, parser); mfact.UseBinaryMessages = true; //Test encoding tmpl = mfact.NewMessage(0x200); var buf = tmpl.WriteData(); var message = HexCodec.HexEncode(buf, 0, buf.Length); Console.WriteLine("MESSAGE: " + message); for (var i = 0; i < 5; i++) { var b = longData2[i]; Assert.Equal(b, buf[i + offset1]); } for (var i = 0; i < 15; i++) { Assert.Equal(bigintData1[i], buf[i + offset2]); } //Test parsing tmpl = mfact.ParseMessage(buf, 0); Assert.Equal(1234567890L, tmpl.GetObjectValue(2)); Assert.Equal(b29, tmpl.GetObjectValue(3)); }
//// ===================================================================================== /// <summary> /// Calcule la valeur de hachage SHA-512 pour le tableau d'octets spécifié. /// </summary> /// <param name="buffer">Entrée pour laquelle le code de hachage doit être calculé.</param> /// <returns>Code de hachage calculé, exprimé sous forme de chaîne hexadécimale.</returns> public static string ComputeSha512(byte[] buffer) { return(HexCodec.GetString(SHA512.Create().ComputeHash(buffer))); }
public override IsoValue ParseBinary(int field, sbyte[] buf, int pos, ICustomField custom) { if (pos < 0) { throw new ParseException($"Invalid bin LLBIN field {field} position {pos}"); } if (pos + 1 > buf.Length) { throw new ParseException($"Insufficient bin LLBIN header field {field}"); } var sbytes = buf; var l = ((sbytes[pos] & 0xf0) >> 4) * 10 + (sbytes[pos] & 0x0f); if (l < 0) { throw new ParseException($"Invalid bin LLBIN length {l} pos {pos}"); } if (l + pos + 1 > buf.Length) { throw new ParseException( $"Insufficient data for bin LLBIN field {field}, pos {pos}: need {l}, only {buf.Length} available"); } var v = new sbyte[l]; Array.Copy(sbytes, pos + 1, v, 0, l); if (custom == null) { return(new IsoValue(IsoType, v)); } if (custom is ICustomBinaryField) { try { var dec = ((ICustomBinaryField)custom).DecodeBinaryField(sbytes, pos + 1, l); return(dec == null ? new IsoValue(IsoType, v, v.Length) : new IsoValue(IsoType, dec, l, custom)); } catch (Exception) { throw new ParseException($"Insufficient data for LLBIN field {field}, pos {pos} length {l}"); } } { var dec = custom.DecodeField(HexCodec.HexEncode(v, 0, v.Length)); return(dec == null ? new IsoValue(IsoType, v) : new IsoValue(IsoType, dec, custom)); } }
public void Write(Stream outs, bool binary, bool forceStringEncoding) { switch (Type) { case IsoType.LLLVAR: case IsoType.LLVAR: case IsoType.LLLLVAR: WriteLengthHeader(Length, outs, Type, binary, forceStringEncoding); break; case IsoType.LLBIN: case IsoType.LLLBIN: case IsoType.LLLLBIN: WriteLengthHeader(binary ? Length : Length * 2, outs, Type, binary, forceStringEncoding); break; default: if (binary) { //numeric types in binary are coded like this var buf = Type switch { IsoType.NUMERIC => new sbyte[Length / 2 + Length % 2], IsoType.AMOUNT => new sbyte[6], IsoType.DATE10 => new sbyte[Length / 2], IsoType.DATE4 => new sbyte[Length / 2], IsoType.DATE_EXP => new sbyte[Length / 2], IsoType.TIME => new sbyte[Length / 2], IsoType.DATE12 => new sbyte[Length / 2], IsoType.DATE14 => new sbyte[Length / 2], IsoType.DATE6 => new sbyte[Length / 2], _ => null }; //Encode in BCD if it's one of these types if (buf != null) { Bcd.Encode(ToString(), buf); outs.Write(buf.ToUint8(), 0, buf.Length); return; } } break; } if (binary && (Type == IsoType.BINARY || Type == IsoType.LLBIN || Type == IsoType.LLLBIN || Type == IsoType.LLLLBIN)) { var missing = 0; if (Value is sbyte[] bytes) { outs.Write(bytes.ToUint8(), 0, bytes.Length); missing = Length - bytes.Length; } else { switch (Encoder) { case ICustomBinaryField customBinaryField: { var binval = customBinaryField.EncodeBinaryField(Value); outs.Write(binval.ToUint8(), 0, binval.Length); missing = Length - binval.Length; break; } default: { var binval = HexCodec.HexDecode(Value.ToString()); outs.Write(binval.ToUint8(), 0, binval.Length); missing = Length - binval.Length; break; } } } if (Type != IsoType.BINARY || missing <= 0) { return; } for (var i = 0; i < missing; i++) { outs.WriteByte(0); } } else { var bytes = ToString().GetSignedBytes(Encoding); outs.Write(bytes.ToUint8(), 0, bytes.Length); } }
public override IsoValue ParseBinary(int field, sbyte[] buf, int pos, ICustomField custom) { if (pos < 0) { throw new ParseException($"Invalid bin LLLLBIN field {field} pos {pos}"); } if (pos + 2 > buf.Length) { throw new ParseException($"Insufficient LLLLBIN header field {field}"); } int l = ((buf[pos] & 0xf0) * 1000) + ((buf[pos] & 0x0f) * 100) + (((buf[pos + 1] & 0xf0) >> 4) * 10) + (buf[pos + 1] & 0x0f); if (l < 0) { throw new ParseException($"Invalid LLLLBIN length {l} field {field} pos {pos}"); } if (l + pos + 2 > buf.Length) { throw new ParseException( $"Insufficient data for bin LLLLBIN field {field}, pos {pos} requires {l}, only {buf.Length - pos + 1} available"); } var v = new sbyte[l]; Array.Copy(buf, pos + 2, v, 0, l); if (custom == null) { return(new IsoValue(IsoType, v)); } var customBinaryField = custom as ICustomBinaryField; if (customBinaryField != null) { try { var dec = customBinaryField.DecodeBinaryField(buf, pos + 2, l); return(dec == null ? new IsoValue(IsoType, v, v.Length) : new IsoValue(IsoType, dec, l, custom)); } catch (Exception) { throw new ParseException($"Insufficient data for LLLLBIN field {field}, pos {pos}"); } } { var dec = custom.DecodeField(HexCodec.HexEncode(v, 0, v.Length)); return(dec == null ? new IsoValue(IsoType, v) : new IsoValue(IsoType, dec, custom)); } }
public override string ToString() { if (Value == null) { return("ISOValue<null>"); } switch (Type) { case IsoType.NUMERIC: case IsoType.AMOUNT: if (Type == IsoType.AMOUNT) { if (Value is decimal value) { return(Type.Format(value, 12)); } else { return(Type.Format(Convert.ToDecimal(Value), 12)); } } else { return Value switch { BigInteger _ => Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length), long l => Type.Format(l, Length), _ => Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length) } }; case IsoType.ALPHA: return(Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length)); case IsoType.LLVAR: case IsoType.LLLVAR: case IsoType.LLLLVAR: return(Encoder == null?Value.ToString() : Encoder.EncodeField(Value)); } if (Value is DateTime dateTime) { return(Type.Format(dateTime)); } switch (Type) { case IsoType.BINARY: if (Value is sbyte[] v1) { return(Type.Format(Encoder == null ? HexCodec.HexEncode(v1, 0, v1.Length) : Encoder.EncodeField(v1), Length * 2)); } else { return(Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length * 2)); } case IsoType.LLBIN: case IsoType.LLLBIN: case IsoType.LLLLBIN: if (Value is sbyte[] v) { return(Encoder == null ? HexCodec.HexEncode(v, 0, v.Length) : Encoder.EncodeField(v)); } else { var s = Encoder == null?Value.ToString() : Encoder.EncodeField(Value); return(s.Length % 2 == 1 ? $"0{s}" : s); } } return(Encoder == null?Value.ToString() : Encoder.EncodeField(Value)); }
public string DebugString() { var sb = new StringBuilder(); if (IsoHeader != null) { sb.Append(IsoHeader); } else if (BinIsoHeader != null) { sb.Append("[0x").Append(HexCodec.HexEncode(BinIsoHeader, 0, BinIsoHeader.Length)).Append("]"); } sb.Append(Type.ToString("x4")); //Bitmap var bs = CreateBitmapBitSet(); var pos = 0; var lim = bs.Length / 4; for (var i = 0; i < lim; i++) { var nibble = 0; if (bs.Get(pos++)) { nibble |= 8; } if (bs.Get(pos++)) { nibble |= 4; } if (bs.Get(pos++)) { nibble |= 2; } if (bs.Get(pos++)) { nibble |= 1; } var string0 = Hex.SignedBytesToString(nibble, 1, Encoding); sb.Append(string0); } //Fields for (var i = 2; i < 129; i++) { var v = _fields[i]; if (v == null) { continue; } var desc = v.ToString(); if (v.Type == IsoType.LLBIN || v.Type == IsoType.LLVAR) { sb.Append(desc.Length.ToString("D2")); } else if (v.Type == IsoType.LLLBIN || v.Type == IsoType.LLLVAR) { sb.Append(desc.Length.ToString("D3")); } else if (v.Type == IsoType.LLLLBIN || v.Type == IsoType.LLLLVAR) { sb.Append(desc.Length.ToString("D4")); } sb.Append(desc); } return(sb.ToString()); }
public override string ToString() { if (Value == null) { return("ISOValue<null>"); } switch (Type) { case IsoType.NUMERIC: case IsoType.AMOUNT: if (Type == IsoType.AMOUNT) { if (Value is decimal) { return(Type.Format((decimal)Value, 12)); } else { return(Type.Format(Convert.ToDecimal(Value), 12)); } } else if (Value is BigInteger) { return(Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length)); } else if (Value is long) { return(Type.Format((long)Value, Length)); } else { return(Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length)); } case IsoType.ALPHA: return(Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length)); case IsoType.LLVAR: case IsoType.LLLVAR: case IsoType.LLLLVAR: return(Encoder == null?Value.ToString() : Encoder.EncodeField(Value)); } if (Value is DateTime) { return(Type.Format((DateTime)Value)); } switch (Type) { case IsoType.BINARY: if (Value is sbyte[]) { var v = (sbyte[])Value; return(Type.Format(Encoder == null ? HexCodec.HexEncode(v, 0, v.Length) : Encoder.EncodeField(Value), Length * 2)); } else { return(Type.Format(Encoder == null ? Value.ToString() : Encoder.EncodeField(Value), Length * 2)); } case IsoType.LLBIN: case IsoType.LLLBIN: case IsoType.LLLLBIN: if (Value is sbyte[]) { var v = (sbyte[])Value; return(Encoder == null ? HexCodec.HexEncode(v, 0, v.Length) : Encoder.EncodeField(Value)); } else { var s = Encoder == null?Value.ToString() : Encoder.EncodeField(Value); return(s.Length % 2 == 1 ? $"0{s}" : s); } } return(Encoder == null?Value.ToString() : Encoder.EncodeField(Value)); }
public override IsoValue Parse(int field, sbyte[] buf, int pos, ICustomField custom) { if (pos < 0) { throw new ParseException($"Invalid LLBIN field {field} position {pos}"); } if (pos + 2 > buf.Length) { throw new ParseException($"Invalid LLBIN field {field} position {pos}"); } var len = DecodeLength(buf, pos, 2); if (len < 0) { throw new ParseException($"Invalid LLBIN field {field} length {len} pos {pos}"); } if (len + pos + 2 > buf.Length) { throw new ParseException( $"Insufficient data for LLBIN field {field}, pos {pos} (LEN states '{buf.SignedBytesToString(pos, 2, Encoding.Default)}')"); } var binval = len == 0 ? new sbyte[0] : HexCodec.HexDecode(buf.SignedBytesToString(pos + 2, len, Encoding.Default)); if (custom == null) { return(new IsoValue(IsoType, binval, binval.Length)); } var binaryField = custom as ICustomBinaryField; if (binaryField != null) { try { var dec = binaryField.DecodeBinaryField(buf, pos + 2, len); if (dec == null) { return(new IsoValue(IsoType, binval, binval.Length)); } return(new IsoValue(IsoType, dec, 0, custom)); } catch (Exception) { throw new ParseException( $"Insufficient data for LLBIN field {field}, pos {pos} (LEN states '{buf.SignedBytesToString(pos, 2, Encoding.Default)}')"); } } try { var dec = custom.DecodeField(buf.SignedBytesToString(pos + 2, len, Encoding.Default)); return(dec == null ? new IsoValue(IsoType, binval, binval.Length) : new IsoValue(IsoType, dec, binval.Length, custom)); } catch (Exception) { throw new ParseException( $"Insufficient data for LLBIN field {field}, pos {pos} (LEN states '{buf.SignedBytesToString(pos, 2, Encoding.Default)}')"); } }
public void Write(Stream outs, bool binary, bool forceStringEncoding) { switch (Type) { case IsoType.LLLVAR: case IsoType.LLVAR: case IsoType.LLLLVAR: WriteLengthHeader(Length, outs, Type, binary, forceStringEncoding); break; case IsoType.LLBIN: case IsoType.LLLBIN: case IsoType.LLLLBIN: WriteLengthHeader(binary ? Length : Length * 2, outs, Type, binary, forceStringEncoding); break; default: if (binary) { //numeric types in binary are coded like this sbyte[] buf = null; switch (Type) { case IsoType.NUMERIC: buf = new sbyte[Length / 2 + Length % 2]; break; case IsoType.AMOUNT: buf = new sbyte[6]; break; case IsoType.DATE10: case IsoType.DATE4: case IsoType.DATE_EXP: case IsoType.TIME: case IsoType.DATE12: case IsoType.DATE14: buf = new sbyte[Length / 2]; break; } //Encode in BCD if it's one of these types if (buf != null) { Bcd.Encode(ToString(), buf); outs.Write(buf.ToUnsignedBytes(), 0, buf.Length); return; } } break; } if (binary && (Type == IsoType.BINARY || Type == IsoType.LLBIN || Type == IsoType.LLLBIN || Type == IsoType.LLLLBIN)) { var missing = 0; if (Value is sbyte[]) { var bytes = (sbyte[])Value; outs.Write(bytes.ToUnsignedBytes(), 0, bytes.Length); missing = Length - bytes.Length; } else if (Encoder is ICustomBinaryField) { var binval = ((ICustomBinaryField)Encoder).EncodeBinaryField(Value); outs.Write(binval.ToUnsignedBytes(), 0, binval.Length); missing = Length - binval.Length; } else { var binval = HexCodec.HexDecode(Value.ToString()); outs.Write(binval.ToUnsignedBytes(), 0, binval.Length); missing = Length - binval.Length; } if (Type != IsoType.BINARY || missing <= 0) { return; } for (var i = 0; i < missing; i++) { outs.WriteByte(0); } } else { var bytes = ToString().GetSignedbytes(Encoding); outs.Write(bytes.ToUnsignedBytes(), 0, bytes.Length); } }