From 222527df46670811d61c3ed260e88c95aedf0e73 Mon Sep 17 00:00:00 2001 From: Grant Birchmeier Date: Tue, 14 Apr 2026 10:24:55 -0500 Subject: [PATCH 1/4] remove HiPerfTimer class which isn't used anywhere --- UnitTests/HiPerfTimer.cs | 67 ---------------------------------------- 1 file changed, 67 deletions(-) delete mode 100644 UnitTests/HiPerfTimer.cs diff --git a/UnitTests/HiPerfTimer.cs b/UnitTests/HiPerfTimer.cs deleted file mode 100644 index 8d4aae57a..000000000 --- a/UnitTests/HiPerfTimer.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using System.ComponentModel; -using System.Threading; - -namespace UnitTests -{ - /// - /// High Performance Win32 Timer, taken from CodeProject. - /// - internal class HiPerfTimer - { - [DllImport("Kernel32.dll")] - private static extern bool QueryPerformanceCounter( - out long lpPerformanceCount); - - [DllImport("Kernel32.dll")] - private static extern bool QueryPerformanceFrequency( - out long lpFrequency); - - private long startTime, stopTime; - private long freq; - - // Constructor - - public HiPerfTimer() - { - startTime = 0; - stopTime = 0; - - if (QueryPerformanceFrequency(out freq) == false) - { - // high-performance counter not supported - - throw new Win32Exception(); - } - } - - // Start the timer - - public void Start() - { - // lets do the waiting threads there work - - Thread.Sleep(0); - - QueryPerformanceCounter(out startTime); - } - - // Stop the timer - - public void Stop() - { - QueryPerformanceCounter(out stopTime); - } - - // Returns the duration of the timer (in seconds) - - public double Duration - { - get - { - return (double)(stopTime - startTime) / (double)freq; - } - } - } -} \ No newline at end of file From 73e24b051c076b3b2d071bb58633feebc2229328 Mon Sep 17 00:00:00 2001 From: Grant Birchmeier Date: Tue, 14 Apr 2026 10:46:47 -0500 Subject: [PATCH 2/4] use file-scoped namespaces - UTs --- UnitTests/DefaultMessageFactoryTests.cs | 48 +- UnitTests/FieldMapTests.cs | 898 ++++---- UnitTests/FieldTests.cs | 385 ++-- UnitTests/FileStoreTests.cs | 402 ++-- UnitTests/GenMessageTest.cs | 239 +- UnitTests/GroupTests.cs | 93 +- UnitTests/MemoryStoreTest.cs | 43 +- UnitTests/MessageCrackerTests.cs | 155 +- UnitTests/MessageTests.cs | 2009 ++++++++--------- UnitTests/MessageToXmlTests.cs | 239 +- UnitTests/SessionIDTest.cs | 145 +- UnitTests/SessionScheduleTests.cs | 1267 ++++++----- UnitTests/SessionSettingsTest.cs | 579 +++-- UnitTests/SessionStateTest.cs | 357 ++- UnitTests/SettingsTest.cs | 95 +- UnitTests/SocketSettingsTest.cs | 181 +- .../DataDictionaryLoadExtensions.cs | 19 +- UnitTests/ThreadedSocketAcceptorTests.cs | 56 +- UnitTests/ThreadedSocketReactorTests.cs | 87 +- UnitTests/Util/ExceptionExtensionsTests.cs | 35 +- UnitTests/Util/UtcDateTimeSerializerTests.cs | 74 +- 21 files changed, 3687 insertions(+), 3719 deletions(-) diff --git a/UnitTests/DefaultMessageFactoryTests.cs b/UnitTests/DefaultMessageFactoryTests.cs index a69b2a15d..c12c35465 100644 --- a/UnitTests/DefaultMessageFactoryTests.cs +++ b/UnitTests/DefaultMessageFactoryTests.cs @@ -1,40 +1,36 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using NUnit.Framework; using QuickFix; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class DefaultMessageFactoryTests { - [TestFixture] - public class DefaultMessageFactoryTests + [Test] + public void GroupCreateTest_Fix50() { - [Test] - public void GroupCreateTest_Fix50() - { - DefaultMessageFactory dmf = new DefaultMessageFactory(QuickFix.FixValues.ApplVerID.FIX50); + DefaultMessageFactory dmf = new DefaultMessageFactory(QuickFix.FixValues.ApplVerID.FIX50); - Group? g44 = dmf.Create("FIX.4.4", "B", 33); - Assert.That(g44, Is.InstanceOf()); + Group? g44 = dmf.Create("FIX.4.4", "B", 33); + Assert.That(g44, Is.InstanceOf()); - Group? g50 = dmf.Create("FIXT.1.1", "B", 33); - Assert.That(g50, Is.InstanceOf()); + Group? g50 = dmf.Create("FIXT.1.1", "B", 33); + Assert.That(g50, Is.InstanceOf()); - Group? g50sp2 = dmf.Create("FIXT.1.1", "CD", QuickFix.Fields.Tags.NoAsgnReqs); - Assert.That(g50sp2, Is.Null); - } + Group? g50sp2 = dmf.Create("FIXT.1.1", "CD", QuickFix.Fields.Tags.NoAsgnReqs); + Assert.That(g50sp2, Is.Null); + } - [Test] - public void GroupCreateTest_DefaultFix50Sp2() - { - DefaultMessageFactory dmf = new DefaultMessageFactory(); + [Test] + public void GroupCreateTest_DefaultFix50Sp2() + { + DefaultMessageFactory dmf = new DefaultMessageFactory(); - Group? g44 = dmf.Create("FIX.4.4", "B", 33); - Assert.That(g44, Is.InstanceOf()); + Group? g44 = dmf.Create("FIX.4.4", "B", 33); + Assert.That(g44, Is.InstanceOf()); - Group? g50sp2 = dmf.Create("FIXT.1.1", "CD", QuickFix.Fields.Tags.NoAsgnReqs); - Assert.That(g50sp2, Is.InstanceOf()); - } + Group? g50sp2 = dmf.Create("FIXT.1.1", "CD", QuickFix.Fields.Tags.NoAsgnReqs); + Assert.That(g50sp2, Is.InstanceOf()); } } diff --git a/UnitTests/FieldMapTests.cs b/UnitTests/FieldMapTests.cs index e73550154..bf7eb9f51 100644 --- a/UnitTests/FieldMapTests.cs +++ b/UnitTests/FieldMapTests.cs @@ -3,458 +3,456 @@ using QuickFix; using QuickFix.Fields; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class FieldMapTests { + [Test] + public void CharFieldTest() + { + FieldMap fm = new(); + CharField field = new CharField(100, 'd'); + fm.SetField(field); + CharField refield = new CharField(100); + fm.GetField(refield); + Assert.That('d', Is.EqualTo(refield.Value)); + + field.Value = 'e'; + fm.SetField(field); + CharField r = fm.GetField(refield); + Assert.That('e', Is.EqualTo(refield.Value)); + + Assert.That(r, Is.SameAs(refield)); + } + + [Test] + public void GetCharTest() + { + FieldMap fm = new(); + fm.SetField(new CharField(20, 'a')); + Assert.That(fm.GetChar(20), Is.EqualTo('a')); + + fm.SetField(new StringField(21, "b")); + Assert.That(fm.GetChar(21), Is.EqualTo('b')); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetString(99900); }); + } + + [Test] + public void GetDecimalTest() + { + FieldMap fm = new(); + var val = new decimal(20.4); + fm.SetField(new DecimalField(200, val)); + Assert.That(fm.GetDecimal(200), Is.EqualTo(val)); + + fm.SetField(new StringField(201, "33.22")); + Assert.That(fm.GetDecimal(201), Is.EqualTo(new decimal(33.22))); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetString(99900); }); + } + + + [Test] + public void StringFieldTest() + { + FieldMap fm = new(); + fm.SetField(new Account("hello")); + Account acct = new Account(); + fm.GetField(acct); + Assert.That("hello", Is.EqualTo(acct.Value)); + + fm.SetField(new Account("helloworld")); + StringField r = fm.GetField(acct); + Assert.That("helloworld", Is.EqualTo(acct.Value)); + + Assert.That(acct, Is.SameAs(r)); + } + + [Test] + public void GetStringTest() + { + FieldMap fm = new(); + fm.SetField(new Account("hello")); + Assert.That(fm.GetString(Tags.Account), Is.EqualTo("hello")); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetString(99900); }); + } + + [Test] + public void DateTimeFieldTest() + { + FieldMap fm = new(); + fm.SetField(new DateTimeField(Tags.TransactTime, new DateTime(2009, 12, 10))); + TransactTime tt = new TransactTime(); + fm.GetField(tt); + Assert.That(new DateTime(2009, 12, 10), Is.EqualTo(tt.Value)); + + fm.SetField(new TransactTime(new DateTime(2010, 12, 10))); + DateTimeField r = fm.GetField(tt); + Assert.That(new DateTime(2010, 12, 10), Is.EqualTo(tt.Value)); + + Assert.That(tt, Is.SameAs(r)); + } + + [Test] + public void DateTimeFieldNanoTest() + { + FieldMap fm = new(); + fm.SetField(new StringField(Tags.TransactTime, "20200309-20:53:10.643649215")); + TransactTime tt = new TransactTime(); + fm.GetField(tt); + // Ticks resolution is 100 nanoseconds, so we lose the last 2 decimal points + Assert.That(tt.Value.Ticks, Is.EqualTo(637193839906436492)); + } + + [Test] + public void DateOnlyFieldTest() + { + FieldMap fm = new(); + fm.SetField(new DateOnlyField(Tags.MDEntryDate, new DateTime(2009, 12, 10, 1, 2, 3))); + MDEntryDate ed = new MDEntryDate(); + fm.GetField(ed); + Assert.That(ed.Value, Is.EqualTo(new DateTime(2009, 12, 10))); + + fm.SetField(new MDEntryDate(new DateTime(2010, 12, 10))); + DateOnlyField r = fm.GetField(ed); + Assert.That(ed.Value, Is.EqualTo(new DateTime(2010, 12, 10))); + + Assert.That(ed, Is.SameAs(r)); + Assert.That(ed.ToString(), Is.EqualTo("20101210")); + } + + [Test] + public void TimeOnlyFieldTest() + { + FieldMap fm = new(); + fm.SetField(new TimeOnlyField(Tags.MDEntryTime, new DateTime(1, 1, 1, 1, 2, 3), false)); + MDEntryTime et = new MDEntryTime(); + fm.GetField(et); + Assert.That(et.Value, Is.EqualTo(new DateTime(1980, 01, 01, 1, 2, 3))); + + fm.SetField(new MDEntryTime(new DateTime(1, 1, 1, 1, 2, 5))); + TimeOnlyField r = fm.GetField(et); + Assert.That(et.Value, Is.EqualTo(new DateTime(1980, 01, 01, 1, 2, 5))); + + Assert.That(et, Is.SameAs(r)); + Assert.That(et.ToString(), Is.EqualTo("01:02:05.000")); + } + + [Test] + public void GetDateTimeTest() + { + FieldMap fm = new(); + fm.SetField(new DateTimeField(Tags.TransactTime, new DateTime(2009, 12, 10))); + Assert.That(fm.GetDateTime(Tags.TransactTime), Is.EqualTo(new DateTime(2009, 12, 10))); + + fm.SetField(new StringField(Tags.TransactTime, "20091211-12:12:44")); + Assert.That(fm.GetDateTime(Tags.TransactTime), Is.EqualTo(new DateTime(2009, 12, 11, 12, 12, 44))); + + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetDateTime(99900); }); + } + + [Test] + public void GetDateOnlyTest() + { + FieldMap fm = new(); + fm.SetField(new DateOnlyField(Tags.MDEntryDate, new DateTime(2009, 12, 10, 1, 2, 3))); + Assert.That(fm.GetDateTime(Tags.MDEntryDate), Is.EqualTo(new DateTime(2009, 12, 10))); + + fm.SetField(new StringField(Tags.MDEntryDate, "20091211")); + Assert.That(fm.GetDateOnly(Tags.MDEntryDate), Is.EqualTo(new DateTime(2009, 12, 11))); + + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetDateOnly(99900); }); + } + + [Test] + public void GetTimeOnlyTest() + { + FieldMap fm = new(); + fm.SetField(new TimeOnlyField(Tags.MDEntryTime, new DateTime(2009, 12, 10, 1, 2, 3))); + Assert.That(fm.GetDateTime(Tags.MDEntryTime), Is.EqualTo(new DateTime(1980, 01, 01, 1, 2, 3))); + + fm.SetField(new StringField(Tags.MDEntryTime, "07:30:47")); + Assert.That(fm.GetTimeOnly(Tags.MDEntryTime), Is.EqualTo(new DateTime(1980, 01, 01, 7, 30, 47))); + + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetTimeOnly(99900); }); + } + + [Test] + public void BooleanFieldTest() + { + FieldMap fm = new(); + BooleanField field = new BooleanField(200, true); + BooleanField refield = new BooleanField(200); + fm.SetField(field); + fm.GetField(refield); + Assert.That(true, Is.EqualTo(refield.Value)); + + field.Value = false; + fm.SetField(field); + BooleanField r = fm.GetField(refield); + Assert.That(false, Is.EqualTo(refield.Value)); + + Assert.That(refield, Is.SameAs(r)); + } + + [Test] + public void GetBooleanTest() + { + FieldMap fm = new(); + fm.SetField(new BooleanField(200, true)); + Assert.That(fm.GetBoolean(200), Is.EqualTo(true)); + + fm.SetField(new StringField(201, "N")); + Assert.That(fm.GetBoolean(201), Is.EqualTo(false)); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetString(99900); }); + } + + [Test] + public void IntFieldTest() + { + FieldMap fm = new(); + IntField field = new IntField(200, 101); + IntField refield = new IntField(200); + fm.SetField(field); + fm.GetField(refield); + Assert.That(101, Is.EqualTo(refield.Value)); + + field.Value = 102; + fm.SetField(field); + IntField r = fm.GetField(refield); + Assert.That(102, Is.EqualTo(refield.Value)); + + Assert.That(refield, Is.SameAs(r)); + } + + [Test] + public void GetIntTest() + { + FieldMap fm = new(); + IntField field = new IntField(200, 101); + fm.SetField(field); + Assert.That(fm.GetInt(200), Is.EqualTo(101)); + + fm.SetField(new StringField(202, "2222")); + Assert.That(fm.GetInt(202), Is.EqualTo(2222)); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetInt(99900); }); + } + + [Test] + public void DecimalFieldTest() + { + FieldMap fm = new(); + DecimalField field = new DecimalField(200, new decimal(101.0001)); + DecimalField refield = new DecimalField(200); + fm.SetField(field); + fm.GetField(refield); + Assert.That(101.0001, Is.EqualTo(refield.Value)); + + field.Value = 101.0002m; + fm.SetField(field); + DecimalField r = fm.GetField(refield); + Assert.That(101.0002, Is.EqualTo(refield.Value)); + + Assert.That(refield, Is.SameAs(r)); + } + + [Test] + public void DefaultFieldTest() + { + FieldMap fm = new(); + DecimalField field = new DecimalField(200, new decimal(101.0001)); + fm.SetField(field); + string refield = fm.GetString(200); + Assert.That("101.0001", Is.EqualTo(refield)); + } + + [Test] + public void SetFieldOverwriteTest() + { + FieldMap fm = new(); + IntField field = new IntField(21901, 1011); + IntField refield = new IntField(21901); + fm.SetField(field, false); + fm.GetField(refield); + Assert.That(1011, Is.EqualTo(refield.Value)); + + field.Value = 1021; + IntField refield2 = new IntField(21901); + fm.SetField(field, false); + fm.GetField(refield2); + Assert.That(refield.Value, Is.EqualTo(1011)); + + fm.SetField(field, true); + IntField refield3 = new IntField(21901); + fm.GetField(refield3); + Assert.That(1021, Is.EqualTo(refield3.Value)); + } + + [Test] + public void FieldNotFoundTest() + { + FieldMap fm = new(); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetString(99900); }); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetField(new DateTimeField(1002030)); }); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetField(new CharField(23099)); }); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetField(new BooleanField(99900)); }); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetField(new StringField(99900)); }); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetField(new IntField(99900)); }); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetField(new DecimalField(99900)); }); + } + + [Test] + public void SimpleFieldOrderTest() + { + int[] fieldord = { 10, 11, 12, 13, 200 }; + FieldMap fm = new FieldMap(fieldord); + Assert.That(fm.FieldOrder, Is.EqualTo(fieldord)); + } + + [Test] + public void GroupDelimTest() + { + Group g1 = new Group(100, 200); + Assert.That(g1.CounterField, Is.EqualTo(100)); //counter + Assert.That(g1.Delim, Is.EqualTo(200)); + + g1.SetField(new StringField(200, "delim!")); + + FieldMap fm = new FieldMap(); + fm.AddGroup(g1); + Assert.That(fm.GetInt(100), Is.EqualTo(1)); + + Group g2 = new Group(100, 200); + g2.SetField(new StringField(200, "again!")); + fm.AddGroup(g2); + Assert.That(fm.GetInt(100), Is.EqualTo(2)); + } + + [Test] + public void AddGetGroupTest() + { + Group g1 = new Group(100, 200); + Group g2 = new Group(100, 201); + FieldMap fm = new FieldMap(); + fm.AddGroup(g1); + fm.AddGroup(g2); + Assert.That(fm.GetGroup(1, 100), Is.EqualTo(g1)); + Assert.That(fm.GetGroup(2, 100), Is.EqualTo(g2)); + + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetGroup(1, 101); }); // group counter 101 not found + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetGroup(0, 100); }); // num too low + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetGroup(3, 100); }); // num too high + } + + [Test] + public void RemoveGroupTest() + { + Group g1 = new Group(100, 200); + Group g2 = new Group(100, 201); + FieldMap fm = new FieldMap(); + fm.AddGroup(g1); + fm.AddGroup(g2); + + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.RemoveGroup(1, 101); }); // group counter 101 not found + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.RemoveGroup(0, 100); }); // num too low + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.RemoveGroup(3, 101); }); // num too high + + fm.RemoveGroup(1, 100); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetGroup(2, 100); }); // try to remove item 2 (of 1) + + Assert.That(fm.GetGroupTags().Contains(100)); // still true, because there's still 1 group + + fm.RemoveGroup(1, 100); + Assert.That(fm.GetGroupTags().Contains(100), Is.False); + + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.GetGroup(1, 100); }); // try to remove item 1 (of 0) + } + + [Test] + public void ReplaceGroupTest() + { + Group g1 = new Group(100, 200); + Group g2 = new Group(100, 201); + FieldMap fm = new FieldMap(); + fm.AddGroup(g1); + fm.AddGroup(g2); + + Group g3 = new Group(100, 202); + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.ReplaceGroup(1, 101, g3); }); // group counter 101 not found + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.ReplaceGroup(0, 100, g3); }); // num too low + Assert.Throws(typeof(FieldNotFoundException), + delegate { fm.ReplaceGroup(3, 100, g3); }); // num too high + + fm.ReplaceGroup(1, 100, g3); + fm.ReplaceGroup(2, 100, g3); + Assert.That(fm.GetGroup(1, 100), Is.EqualTo(g3)); + Assert.That(fm.GetGroup(2, 100), Is.EqualTo(g3)); + } + + [Test] + public void IsFieldSetTest() + { + FieldMap fieldmap = new FieldMap(); + BooleanField field = new BooleanField(200, true); + Assert.That(fieldmap.IsSetField(field), Is.EqualTo(false)); + Assert.That(fieldmap.IsSetField(field.Tag), Is.EqualTo(false)); + fieldmap.SetField(field); + Assert.That(fieldmap.IsSetField(field), Is.EqualTo(true)); + Assert.That(fieldmap.IsSetField(field.Tag), Is.EqualTo(true)); + } + + [Test] + public void ClearAndIsEmptyTest() + { + FieldMap fieldmap = new FieldMap(); + BooleanField field = new BooleanField(200, true); + Assert.That(fieldmap.IsEmpty(), Is.EqualTo(true)); + fieldmap.SetField(field); + Assert.That(fieldmap.IsEmpty(), Is.EqualTo(false)); + fieldmap.Clear(); + Assert.That(fieldmap.IsEmpty(), Is.EqualTo(true)); + Group g = new Group(100, 101); + fieldmap.AddGroup(g); + Assert.That(fieldmap.IsEmpty(), Is.EqualTo(false)); + fieldmap.Clear(); + Assert.That(fieldmap.IsEmpty(), Is.EqualTo(true)); + } - [TestFixture] - public class FieldMapTests + [Test] + public void AddGroupKeepTypeTest() { - [Test] - public void CharFieldTest() - { - FieldMap fm = new(); - CharField field = new CharField(100, 'd'); - fm.SetField(field); - CharField refield = new CharField(100); - fm.GetField(refield); - Assert.That('d', Is.EqualTo(refield.Value)); - - field.Value = 'e'; - fm.SetField(field); - CharField r = fm.GetField(refield); - Assert.That('e', Is.EqualTo(refield.Value)); - - Assert.That(r, Is.SameAs(refield)); - } - - [Test] - public void GetCharTest() - { - FieldMap fm = new(); - fm.SetField(new CharField(20, 'a')); - Assert.That(fm.GetChar(20), Is.EqualTo('a')); - - fm.SetField(new StringField(21, "b")); - Assert.That(fm.GetChar(21), Is.EqualTo('b')); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetString(99900); }); - } - - [Test] - public void GetDecimalTest() - { - FieldMap fm = new(); - var val = new Decimal(20.4); - fm.SetField(new DecimalField(200, val)); - Assert.That(fm.GetDecimal(200), Is.EqualTo(val)); - - fm.SetField(new StringField(201, "33.22")); - Assert.That(fm.GetDecimal(201), Is.EqualTo(new Decimal(33.22))); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetString(99900); }); - } - - - [Test] - public void StringFieldTest() - { - FieldMap fm = new(); - fm.SetField(new Account("hello")); - Account acct = new Account(); - fm.GetField(acct); - Assert.That("hello", Is.EqualTo(acct.Value)); - - fm.SetField(new Account("helloworld")); - StringField r = fm.GetField(acct); - Assert.That("helloworld", Is.EqualTo(acct.Value)); - - Assert.That(acct, Is.SameAs(r)); - } - - [Test] - public void GetStringTest() - { - FieldMap fm = new(); - fm.SetField(new Account("hello")); - Assert.That(fm.GetString(Tags.Account), Is.EqualTo("hello")); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetString(99900); }); - } - - [Test] - public void DateTimeFieldTest() - { - FieldMap fm = new(); - fm.SetField(new DateTimeField(Tags.TransactTime, new DateTime(2009, 12, 10))); - TransactTime tt = new TransactTime(); - fm.GetField(tt); - Assert.That(new DateTime(2009, 12, 10), Is.EqualTo(tt.Value)); - - fm.SetField(new TransactTime(new DateTime(2010, 12, 10))); - DateTimeField r = fm.GetField(tt); - Assert.That(new DateTime(2010, 12, 10), Is.EqualTo(tt.Value)); - - Assert.That(tt, Is.SameAs(r)); - } - - [Test] - public void DateTimeFieldNanoTest() - { - FieldMap fm = new(); - fm.SetField(new StringField(Tags.TransactTime, "20200309-20:53:10.643649215")); - TransactTime tt = new TransactTime(); - fm.GetField(tt); - // Ticks resolution is 100 nanoseconds, so we lose the last 2 decimal points - Assert.That(tt.Value.Ticks, Is.EqualTo(637193839906436492)); - } - - [Test] - public void DateOnlyFieldTest() - { - FieldMap fm = new(); - fm.SetField(new DateOnlyField(Tags.MDEntryDate, new DateTime(2009, 12, 10, 1, 2, 3))); - MDEntryDate ed = new MDEntryDate(); - fm.GetField(ed); - Assert.That(ed.Value, Is.EqualTo(new DateTime(2009, 12, 10))); - - fm.SetField(new MDEntryDate(new DateTime(2010, 12, 10))); - DateOnlyField r = fm.GetField(ed); - Assert.That(ed.Value, Is.EqualTo(new DateTime(2010, 12, 10))); - - Assert.That(ed, Is.SameAs(r)); - Assert.That(ed.ToString(), Is.EqualTo("20101210")); - } - - [Test] - public void TimeOnlyFieldTest() - { - FieldMap fm = new(); - fm.SetField(new TimeOnlyField(Tags.MDEntryTime, new DateTime(1, 1, 1, 1, 2, 3), false)); - MDEntryTime et = new MDEntryTime(); - fm.GetField(et); - Assert.That(et.Value, Is.EqualTo(new DateTime(1980, 01, 01, 1, 2, 3))); - - fm.SetField(new MDEntryTime(new DateTime(1, 1, 1, 1, 2, 5))); - TimeOnlyField r = fm.GetField(et); - Assert.That(et.Value, Is.EqualTo(new DateTime(1980, 01, 01, 1, 2, 5))); - - Assert.That(et, Is.SameAs(r)); - Assert.That(et.ToString(), Is.EqualTo("01:02:05.000")); - } - - [Test] - public void GetDateTimeTest() - { - FieldMap fm = new(); - fm.SetField(new DateTimeField(Tags.TransactTime, new DateTime(2009, 12, 10))); - Assert.That(fm.GetDateTime(Tags.TransactTime), Is.EqualTo(new DateTime(2009, 12, 10))); - - fm.SetField(new StringField(Tags.TransactTime, "20091211-12:12:44")); - Assert.That(fm.GetDateTime(Tags.TransactTime), Is.EqualTo(new DateTime(2009, 12, 11, 12, 12, 44))); - - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetDateTime(99900); }); - } - - [Test] - public void GetDateOnlyTest() - { - FieldMap fm = new(); - fm.SetField(new DateOnlyField(Tags.MDEntryDate, new DateTime(2009, 12, 10, 1, 2, 3))); - Assert.That(fm.GetDateTime(Tags.MDEntryDate), Is.EqualTo(new DateTime(2009, 12, 10))); - - fm.SetField(new StringField(Tags.MDEntryDate, "20091211")); - Assert.That(fm.GetDateOnly(Tags.MDEntryDate), Is.EqualTo(new DateTime(2009, 12, 11))); - - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetDateOnly(99900); }); - } - - [Test] - public void GetTimeOnlyTest() - { - FieldMap fm = new(); - fm.SetField(new TimeOnlyField(Tags.MDEntryTime, new DateTime(2009, 12, 10, 1, 2, 3))); - Assert.That(fm.GetDateTime(Tags.MDEntryTime), Is.EqualTo(new DateTime(1980, 01, 01, 1, 2, 3))); - - fm.SetField(new StringField(Tags.MDEntryTime, "07:30:47")); - Assert.That(fm.GetTimeOnly(Tags.MDEntryTime), Is.EqualTo(new DateTime(1980, 01, 01, 7, 30, 47))); - - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetTimeOnly(99900); }); - } - - [Test] - public void BooleanFieldTest() - { - FieldMap fm = new(); - BooleanField field = new BooleanField(200, true); - BooleanField refield = new BooleanField(200); - fm.SetField(field); - fm.GetField(refield); - Assert.That(true, Is.EqualTo(refield.Value)); - - field.Value = false; - fm.SetField(field); - BooleanField r = fm.GetField(refield); - Assert.That(false, Is.EqualTo(refield.Value)); - - Assert.That(refield, Is.SameAs(r)); - } - - [Test] - public void GetBooleanTest() - { - FieldMap fm = new(); - fm.SetField(new BooleanField(200, true)); - Assert.That(fm.GetBoolean(200), Is.EqualTo(true)); - - fm.SetField(new StringField(201, "N")); - Assert.That(fm.GetBoolean(201), Is.EqualTo(false)); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetString(99900); }); - } - - [Test] - public void IntFieldTest() - { - FieldMap fm = new(); - IntField field = new IntField(200, 101); - IntField refield = new IntField(200); - fm.SetField(field); - fm.GetField(refield); - Assert.That(101, Is.EqualTo(refield.Value)); - - field.Value = 102; - fm.SetField(field); - IntField r = fm.GetField(refield); - Assert.That(102, Is.EqualTo(refield.Value)); - - Assert.That(refield, Is.SameAs(r)); - } - - [Test] - public void GetIntTest() - { - FieldMap fm = new(); - IntField field = new IntField(200, 101); - fm.SetField(field); - Assert.That(fm.GetInt(200), Is.EqualTo(101)); - - fm.SetField(new StringField(202, "2222")); - Assert.That(fm.GetInt(202), Is.EqualTo(2222)); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetInt(99900); }); - } - - [Test] - public void DecimalFieldTest() - { - FieldMap fm = new(); - DecimalField field = new DecimalField(200, new Decimal(101.0001)); - DecimalField refield = new DecimalField(200); - fm.SetField(field); - fm.GetField(refield); - Assert.That(101.0001, Is.EqualTo(refield.Value)); - - field.Value = 101.0002m; - fm.SetField(field); - DecimalField r = fm.GetField(refield); - Assert.That(101.0002, Is.EqualTo(refield.Value)); - - Assert.That(refield, Is.SameAs(r)); - } - - [Test] - public void DefaultFieldTest() - { - FieldMap fm = new(); - DecimalField field = new DecimalField(200, new Decimal(101.0001)); - fm.SetField(field); - string refield = fm.GetString(200); - Assert.That("101.0001", Is.EqualTo(refield)); - } - - [Test] - public void SetFieldOverwriteTest() - { - FieldMap fm = new(); - IntField field = new IntField(21901, 1011); - IntField refield = new IntField(21901); - fm.SetField(field, false); - fm.GetField(refield); - Assert.That(1011, Is.EqualTo(refield.Value)); - - field.Value = 1021; - IntField refield2 = new IntField(21901); - fm.SetField(field, false); - fm.GetField(refield2); - Assert.That(refield.Value, Is.EqualTo(1011)); - - fm.SetField(field, true); - IntField refield3 = new IntField(21901); - fm.GetField(refield3); - Assert.That(1021, Is.EqualTo(refield3.Value)); - } - - [Test] - public void FieldNotFoundTest() - { - FieldMap fm = new(); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetString(99900); }); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetField(new DateTimeField(1002030)); }); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetField(new CharField(23099)); }); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetField(new BooleanField(99900)); }); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetField(new StringField(99900)); }); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetField(new IntField(99900)); }); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetField(new DecimalField(99900)); }); - } - - [Test] - public void SimpleFieldOrderTest() - { - int[] fieldord = { 10, 11, 12, 13, 200 }; - FieldMap fm = new FieldMap(fieldord); - Assert.That(fm.FieldOrder, Is.EqualTo(fieldord)); - } - - [Test] - public void GroupDelimTest() - { - Group g1 = new Group(100, 200); - Assert.That(g1.CounterField, Is.EqualTo(100)); //counter - Assert.That(g1.Delim, Is.EqualTo(200)); - - g1.SetField(new StringField(200, "delim!")); - - FieldMap fm = new FieldMap(); - fm.AddGroup(g1); - Assert.That(fm.GetInt(100), Is.EqualTo(1)); - - Group g2 = new Group(100, 200); - g2.SetField(new StringField(200, "again!")); - fm.AddGroup(g2); - Assert.That(fm.GetInt(100), Is.EqualTo(2)); - } - - [Test] - public void AddGetGroupTest() - { - Group g1 = new Group(100, 200); - Group g2 = new Group(100, 201); - FieldMap fm = new FieldMap(); - fm.AddGroup(g1); - fm.AddGroup(g2); - Assert.That(fm.GetGroup(1, 100), Is.EqualTo(g1)); - Assert.That(fm.GetGroup(2, 100), Is.EqualTo(g2)); - - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetGroup(1, 101); }); // group counter 101 not found - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetGroup(0, 100); }); // num too low - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetGroup(3, 100); }); // num too high - } - - [Test] - public void RemoveGroupTest() - { - Group g1 = new Group(100, 200); - Group g2 = new Group(100, 201); - FieldMap fm = new FieldMap(); - fm.AddGroup(g1); - fm.AddGroup(g2); - - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.RemoveGroup(1, 101); }); // group counter 101 not found - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.RemoveGroup(0, 100); }); // num too low - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.RemoveGroup(3, 101); }); // num too high - - fm.RemoveGroup(1, 100); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetGroup(2, 100); }); // try to remove item 2 (of 1) - - Assert.That(fm.GetGroupTags().Contains(100)); // still true, because there's still 1 group - - fm.RemoveGroup(1, 100); - Assert.That(fm.GetGroupTags().Contains(100), Is.False); - - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.GetGroup(1, 100); }); // try to remove item 1 (of 0) - } - - [Test] - public void ReplaceGroupTest() - { - Group g1 = new Group(100, 200); - Group g2 = new Group(100, 201); - FieldMap fm = new FieldMap(); - fm.AddGroup(g1); - fm.AddGroup(g2); - - Group g3 = new Group(100, 202); - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.ReplaceGroup(1, 101, g3); }); // group counter 101 not found - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.ReplaceGroup(0, 100, g3); }); // num too low - Assert.Throws(typeof(FieldNotFoundException), - delegate { fm.ReplaceGroup(3, 100, g3); }); // num too high - - fm.ReplaceGroup(1, 100, g3); - fm.ReplaceGroup(2, 100, g3); - Assert.That(fm.GetGroup(1, 100), Is.EqualTo(g3)); - Assert.That(fm.GetGroup(2, 100), Is.EqualTo(g3)); - } - - [Test] - public void IsFieldSetTest() - { - FieldMap fieldmap = new FieldMap(); - BooleanField field = new BooleanField(200, true); - Assert.That(fieldmap.IsSetField(field), Is.EqualTo(false)); - Assert.That(fieldmap.IsSetField(field.Tag), Is.EqualTo(false)); - fieldmap.SetField(field); - Assert.That(fieldmap.IsSetField(field), Is.EqualTo(true)); - Assert.That(fieldmap.IsSetField(field.Tag), Is.EqualTo(true)); - } - - [Test] - public void ClearAndIsEmptyTest() - { - FieldMap fieldmap = new FieldMap(); - BooleanField field = new BooleanField(200, true); - Assert.That(fieldmap.IsEmpty(), Is.EqualTo(true)); - fieldmap.SetField(field); - Assert.That(fieldmap.IsEmpty(), Is.EqualTo(false)); - fieldmap.Clear(); - Assert.That(fieldmap.IsEmpty(), Is.EqualTo(true)); - Group g = new Group(100, 101); - fieldmap.AddGroup(g); - Assert.That(fieldmap.IsEmpty(), Is.EqualTo(false)); - fieldmap.Clear(); - Assert.That(fieldmap.IsEmpty(), Is.EqualTo(true)); - } - - [Test] - public void AddGroupKeepTypeTest() - { - // bug found during issue 56 - Group object was losing type after being added - FieldMap fm = new FieldMap(); - QuickFix.FIX42.News.LinesOfTextGroup linesGroup = new QuickFix.FIX42.News.LinesOfTextGroup(); - linesGroup.Text = new Text("foo"); - fm.AddGroup(linesGroup); - - var rvGroup = fm.GetGroup(1, Tags.LinesOfText); - Assert.That(rvGroup, Is.InstanceOf()); - } + // bug found during issue 56 - Group object was losing type after being added + FieldMap fm = new FieldMap(); + QuickFix.FIX42.News.LinesOfTextGroup linesGroup = new(); + linesGroup.Text = new Text("foo"); + fm.AddGroup(linesGroup); + + var rvGroup = fm.GetGroup(1, Tags.LinesOfText); + Assert.That(rvGroup, Is.InstanceOf()); } } diff --git a/UnitTests/FieldTests.cs b/UnitTests/FieldTests.cs index efe3f300a..2ba5ae155 100644 --- a/UnitTests/FieldTests.cs +++ b/UnitTests/FieldTests.cs @@ -4,200 +4,199 @@ using UnitTests.TestHelpers; using StringField = QuickFix.Fields.StringField; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class FieldTests { - [TestFixture] - public class FieldTests + [Test] + public void Tag() + { + // three paths to this value + Assert.That(QuickFix.Fields.Account.TAG, Is.EqualTo(1)); + Assert.That(new QuickFix.Fields.Account().Tag, Is.EqualTo(1)); + Assert.That(QuickFix.Fields.Tags.Account, Is.EqualTo(1)); + } + + [Test] + public void IntFieldTest() + { + IntField field = new IntField(Tags.AdvTransType, 500); + Assert.That(field.Value, Is.EqualTo(500)); + Assert.That(field.Tag, Is.EqualTo(5)); + Assert.That(field.ToString(), Is.EqualTo("500")); + Assert.That(field.Value, Is.EqualTo(500)); + Assert.That(field.Tag, Is.EqualTo(5)); + field.Tag = 10; + Assert.That(field.Tag, Is.EqualTo(10)); + } + + [Test] + public void StringFieldTest() + { + StringField field = new StringField(200, "wayner"); + Assert.That(field.Value, Is.EqualTo("wayner")); + Assert.That(field.Value, Is.EqualTo("wayner")); + Assert.That(field.Tag, Is.EqualTo(200)); + field.Value = "galway"; + Assert.That(field.Value, Is.EqualTo("galway")); + } + + [Test] + public void CharFieldTest() + { + CharField field = new CharField(200, '3'); + Assert.That(field.Value, Is.EqualTo('3')); + Assert.That(field.Value, Is.EqualTo('3')); + Assert.That(field.Tag, Is.EqualTo(200)); + } + + [Test] + public void DecimalFieldTest() + { + Decimal val = new Decimal(3.232535); + Decimal newval = new Decimal(3.14159); + DecimalField field = new DecimalField(200, val); + Assert.That(field.Value, Is.EqualTo(val)); + Assert.That(field.Value, Is.EqualTo(val)); + Assert.That(field.Tag, Is.EqualTo(200)); + field.Value = newval; + Assert.That(field.Value, Is.EqualTo(newval)); + } + + [Test] + public void BooleanFieldTest() + { + BooleanField field = new BooleanField(10, true); + Assert.That(field.Value, Is.EqualTo(true)); + Assert.That(field.Value, Is.EqualTo(true)); + Assert.That(field.Tag, Is.EqualTo(10)); + field.Value = false; + Assert.That(field.Value, Is.EqualTo(false)); + } + + [Test] + public void DateTimeFieldTest() + { + DateTime val = new DateTime( 2009, 9, 4, 3, 44, 1 ); + DateTime newval = new DateTime(2009, 9, 4, 3, 44, 1); + DateTimeField field = new DateTimeField(200, val); + Assert.That(field.Value, Is.EqualTo(val)); + Assert.That(field.Value, Is.EqualTo(val)); + Assert.That(field.Tag, Is.EqualTo(200)); + field.Value = newval; + Assert.That(field.Value, Is.EqualTo(newval)); + Assert.That(field.ToString(), Is.EqualTo("20090904-03:44:01.000")); + } + + [Test] + public void DateTimeFieldNanoTest() + { + DateTime val = TimeHelper.MakeDateTime(2009, 9, 4, 3, 44, 1, 100, 310, 300); + DateTime newval = TimeHelper.MakeDateTime(2009, 9, 4, 3, 44, 1, 100, 310, 300); + DateTimeField field = new DateTimeField(200, val, QuickFix.Fields.Converters.TimeStampPrecision.Nanosecond); + Assert.That(field.Value, Is.EqualTo(val)); + Assert.That(field.Value, Is.EqualTo(val)); + Assert.That(field.Tag, Is.EqualTo(200)); + field.Value = newval; + Assert.That(field.Value, Is.EqualTo(newval)); + Assert.That(field.ToString(), Is.EqualTo("20090904-03:44:01.100310300")); + } + + [Test] + public void StringFieldTest_TotalAndLength() + { + StringField obj = new StringField(12, "VALUE"); + Assert.That(obj.ToStringField(), Is.EqualTo("12=VALUE")); + Assert.That(obj.GetTotal(), Is.EqualTo(542)); + Assert.That(obj.GetLength(), Is.EqualTo(9)); + obj.Value = "VALUF"; // F = E+1 + Assert.That(obj.ToStringField(), Is.EqualTo("12=VALUF")); + Assert.That(obj.GetTotal(), Is.EqualTo(543)); + Assert.That(obj.GetLength(), Is.EqualTo(9)); + obj.Tag = 13; // 13 = 12+1 + Assert.That(obj.ToStringField(), Is.EqualTo("13=VALUF")); + Assert.That(obj.GetTotal(), Is.EqualTo(544)); + Assert.That(obj.GetLength(), Is.EqualTo(9)); + + // latin-1-specific character + obj = new StringField(359, "olé!"); // the é is single-byte in iso-8859-1, but is 2 bytes in ascii or utf-8 + Assert.That(obj.GetTotal(), Is.EqualTo(708)); // sum of all bytes in "359=olé!"+nul + Assert.That(obj.GetLength(), Is.EqualTo(9)); // 8 single-byte chars + 1 nul char + } + + [Test] + public void DefaultValTest() + { + BooleanField bf = new BooleanField(110); + Assert.That(false, Is.EqualTo(bf.Value)); + Assert.That(110, Is.EqualTo(bf.Tag)); + CharField cf = new CharField(300); + Assert.That('\0', Is.EqualTo(cf.Value)); + Assert.That(300, Is.EqualTo(cf.Tag)); + DateTimeField dtf = new DateTimeField(3); + Assert.That(3, Is.EqualTo(dtf.Tag)); + StringField sf = new StringField(32); + Assert.That(32, Is.EqualTo(sf.Tag)); + Assert.That("", Is.EqualTo(sf.Value)); + IntField ifld = new IntField(239); + Assert.That(239, Is.EqualTo(ifld.Tag)); + Assert.That(0, Is.EqualTo(ifld.Value)); + DecimalField df = new DecimalField(1); + Assert.That(1, Is.EqualTo(df.Tag)); + Assert.That(new Decimal(0.0), Is.EqualTo(df.Value)); + } + + [Test] + public void AccountFieldTest() + { + Account acct = new Account("iiiD4"); + Assert.That("iiiD4", Is.EqualTo(acct.Value)); + Assert.That(Tags.Account, Is.EqualTo(acct.Tag)); + } + + [Test] + public void EnumFieldTest() + { + CommType ct = new CommType(CommType.PER_UNIT); + Assert.That('1', Is.EqualTo(ct.Value)); + ExecInst ei = new ExecInst(ExecInst.STRICT_LIMIT); + Assert.That("b", Is.EqualTo(ei.Value)); + AllocStatus ass = new AllocStatus(AllocStatus.REVERSED); + Assert.That(7, Is.EqualTo(ass.Value)); + } + + [Test] + public void DateOnlyFieldTest() + { + MDEntryDate d = new MDEntryDate(new DateTime(2011, 11, 30, 8, 9, 10, 555)); + Assert.That(d.ToString(), Is.EqualTo("20111130")); + } + + [Test] + public void TimeOnlyFieldTest() + { + MDEntryTime t = new MDEntryTime(new DateTime(2011, 11, 30, 8, 9, 10, 555), true); + Assert.That(t.ToString(), Is.EqualTo("08:09:10.555")); + + t = new MDEntryTime(new DateTime(2011, 11, 30, 8, 9, 10, 555), false); + Assert.That(t.ToString(), Is.EqualTo("08:09:10")); + } + + [Test] + public void EqualsTest() { - [Test] - public void Tag() - { - // three paths to this value - Assert.That(QuickFix.Fields.Account.TAG, Is.EqualTo(1)); - Assert.That(new QuickFix.Fields.Account().Tag, Is.EqualTo(1)); - Assert.That(QuickFix.Fields.Tags.Account, Is.EqualTo(1)); - } - - [Test] - public void IntFieldTest() - { - IntField field = new IntField(Tags.AdvTransType, 500); - Assert.That(field.Value, Is.EqualTo(500)); - Assert.That(field.Tag, Is.EqualTo(5)); - Assert.That(field.ToString(), Is.EqualTo("500")); - Assert.That(field.Value, Is.EqualTo(500)); - Assert.That(field.Tag, Is.EqualTo(5)); - field.Tag = 10; - Assert.That(field.Tag, Is.EqualTo(10)); - } - - [Test] - public void StringFieldTest() - { - StringField field = new StringField(200, "wayner"); - Assert.That(field.Value, Is.EqualTo("wayner")); - Assert.That(field.Value, Is.EqualTo("wayner")); - Assert.That(field.Tag, Is.EqualTo(200)); - field.Value = "galway"; - Assert.That(field.Value, Is.EqualTo("galway")); - } - - [Test] - public void CharFieldTest() - { - CharField field = new CharField(200, '3'); - Assert.That(field.Value, Is.EqualTo('3')); - Assert.That(field.Value, Is.EqualTo('3')); - Assert.That(field.Tag, Is.EqualTo(200)); - } - - [Test] - public void DecimalFieldTest() - { - Decimal val = new Decimal(3.232535); - Decimal newval = new Decimal(3.14159); - DecimalField field = new DecimalField(200, val); - Assert.That(field.Value, Is.EqualTo(val)); - Assert.That(field.Value, Is.EqualTo(val)); - Assert.That(field.Tag, Is.EqualTo(200)); - field.Value = newval; - Assert.That(field.Value, Is.EqualTo(newval)); - } - - [Test] - public void BooleanFieldTest() - { - BooleanField field = new BooleanField(10, true); - Assert.That(field.Value, Is.EqualTo(true)); - Assert.That(field.Value, Is.EqualTo(true)); - Assert.That(field.Tag, Is.EqualTo(10)); - field.Value = false; - Assert.That(field.Value, Is.EqualTo(false)); - } - - [Test] - public void DateTimeFieldTest() - { - DateTime val = new DateTime( 2009, 9, 4, 3, 44, 1 ); - DateTime newval = new DateTime(2009, 9, 4, 3, 44, 1); - DateTimeField field = new DateTimeField(200, val); - Assert.That(field.Value, Is.EqualTo(val)); - Assert.That(field.Value, Is.EqualTo(val)); - Assert.That(field.Tag, Is.EqualTo(200)); - field.Value = newval; - Assert.That(field.Value, Is.EqualTo(newval)); - Assert.That(field.ToString(), Is.EqualTo("20090904-03:44:01.000")); - } - - [Test] - public void DateTimeFieldNanoTest() - { - DateTime val = TimeHelper.MakeDateTime(2009, 9, 4, 3, 44, 1, 100, 310, 300); - DateTime newval = TimeHelper.MakeDateTime(2009, 9, 4, 3, 44, 1, 100, 310, 300); - DateTimeField field = new DateTimeField(200, val, QuickFix.Fields.Converters.TimeStampPrecision.Nanosecond); - Assert.That(field.Value, Is.EqualTo(val)); - Assert.That(field.Value, Is.EqualTo(val)); - Assert.That(field.Tag, Is.EqualTo(200)); - field.Value = newval; - Assert.That(field.Value, Is.EqualTo(newval)); - Assert.That(field.ToString(), Is.EqualTo("20090904-03:44:01.100310300")); - } - - [Test] - public void StringFieldTest_TotalAndLength() - { - StringField obj = new StringField(12, "VALUE"); - Assert.That(obj.ToStringField(), Is.EqualTo("12=VALUE")); - Assert.That(obj.GetTotal(), Is.EqualTo(542)); - Assert.That(obj.GetLength(), Is.EqualTo(9)); - obj.Value = "VALUF"; // F = E+1 - Assert.That(obj.ToStringField(), Is.EqualTo("12=VALUF")); - Assert.That(obj.GetTotal(), Is.EqualTo(543)); - Assert.That(obj.GetLength(), Is.EqualTo(9)); - obj.Tag = 13; // 13 = 12+1 - Assert.That(obj.ToStringField(), Is.EqualTo("13=VALUF")); - Assert.That(obj.GetTotal(), Is.EqualTo(544)); - Assert.That(obj.GetLength(), Is.EqualTo(9)); - - // latin-1-specific character - obj = new StringField(359, "olé!"); // the é is single-byte in iso-8859-1, but is 2 bytes in ascii or utf-8 - Assert.That(obj.GetTotal(), Is.EqualTo(708)); // sum of all bytes in "359=olé!"+nul - Assert.That(obj.GetLength(), Is.EqualTo(9)); // 8 single-byte chars + 1 nul char - } - - [Test] - public void DefaultValTest() - { - BooleanField bf = new BooleanField(110); - Assert.That(false, Is.EqualTo(bf.Value)); - Assert.That(110, Is.EqualTo(bf.Tag)); - CharField cf = new CharField(300); - Assert.That('\0', Is.EqualTo(cf.Value)); - Assert.That(300, Is.EqualTo(cf.Tag)); - DateTimeField dtf = new DateTimeField(3); - Assert.That(3, Is.EqualTo(dtf.Tag)); - StringField sf = new StringField(32); - Assert.That(32, Is.EqualTo(sf.Tag)); - Assert.That("", Is.EqualTo(sf.Value)); - IntField ifld = new IntField(239); - Assert.That(239, Is.EqualTo(ifld.Tag)); - Assert.That(0, Is.EqualTo(ifld.Value)); - DecimalField df = new DecimalField(1); - Assert.That(1, Is.EqualTo(df.Tag)); - Assert.That(new Decimal(0.0), Is.EqualTo(df.Value)); - } - - [Test] - public void AccountFieldTest() - { - Account acct = new Account("iiiD4"); - Assert.That("iiiD4", Is.EqualTo(acct.Value)); - Assert.That(Tags.Account, Is.EqualTo(acct.Tag)); - } - - [Test] - public void EnumFieldTest() - { - CommType ct = new CommType(CommType.PER_UNIT); - Assert.That('1', Is.EqualTo(ct.Value)); - ExecInst ei = new ExecInst(ExecInst.STRICT_LIMIT); - Assert.That("b", Is.EqualTo(ei.Value)); - AllocStatus ass = new AllocStatus(AllocStatus.REVERSED); - Assert.That(7, Is.EqualTo(ass.Value)); - } - - [Test] - public void DateOnlyFieldTest() - { - MDEntryDate d = new MDEntryDate(new DateTime(2011, 11, 30, 8, 9, 10, 555)); - Assert.That(d.ToString(), Is.EqualTo("20111130")); - } - - [Test] - public void TimeOnlyFieldTest() - { - MDEntryTime t = new MDEntryTime(new DateTime(2011, 11, 30, 8, 9, 10, 555), true); - Assert.That(t.ToString(), Is.EqualTo("08:09:10.555")); - - t = new MDEntryTime(new DateTime(2011, 11, 30, 8, 9, 10, 555), false); - Assert.That(t.ToString(), Is.EqualTo("08:09:10")); - } - - [Test] - public void EqualsTest() - { - StringField a1 = new StringField(123, "a"); - StringField aSame = a1; - StringField a2 = new StringField(123, "a"); - StringField diffValue = new StringField(123, "b"); - StringField diffTag = new StringField(999, "a"); - IField diffType = new CharField(123, 'a'); - - Assert.That(a1.Equals(aSame), Is.True); - Assert.That(a1.Equals(a2), Is.True); - Assert.That(a1.Equals(diffValue), Is.False); - Assert.That(a1.Equals(diffTag), Is.False); - Assert.That(a1.Equals(diffType), Is.False); - } + StringField a1 = new StringField(123, "a"); + StringField aSame = a1; + StringField a2 = new StringField(123, "a"); + StringField diffValue = new StringField(123, "b"); + StringField diffTag = new StringField(999, "a"); + IField diffType = new CharField(123, 'a'); + + Assert.That(a1.Equals(aSame), Is.True); + Assert.That(a1.Equals(a2), Is.True); + Assert.That(a1.Equals(diffValue), Is.False); + Assert.That(a1.Equals(diffTag), Is.False); + Assert.That(a1.Equals(diffType), Is.False); } } diff --git a/UnitTests/FileStoreTests.cs b/UnitTests/FileStoreTests.cs index 3f28d802e..6264c4d74 100755 --- a/UnitTests/FileStoreTests.cs +++ b/UnitTests/FileStoreTests.cs @@ -3,211 +3,209 @@ using System.IO; using NUnit.Framework; using System.Threading; -using QuickFix; using QuickFix.Store; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class FileStoreTests { - [TestFixture] - public class FileStoreTests + private FileStore? _store; + private FileStoreFactory? _factory; + + private QuickFix.SessionSettings _settings = new(); + private QuickFix.SessionID _sessionId = new("unset", "unset", "unset"); + + private string _storeDirectory = "unset"; + + [SetUp] + public void Setup() + { + _storeDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "store"); + + if (System.IO.Directory.Exists(_storeDirectory)) + System.IO.Directory.Delete(_storeDirectory, true); + + _sessionId = new QuickFix.SessionID("FIX.4.2", "SENDERCOMP", "TARGETCOMP"); + + QuickFix.SettingsDictionary config = new QuickFix.SettingsDictionary(); + config.SetString(QuickFix.SessionSettings.CONNECTION_TYPE, "initiator"); + config.SetString(QuickFix.SessionSettings.FILE_STORE_PATH, _storeDirectory); + + _settings = new QuickFix.SessionSettings(); + _settings.Set(_sessionId, config); + _factory = new FileStoreFactory(_settings); + + _store = (FileStore)_factory.Create(_sessionId); + } + + void RebuildStore() + { + _store?.Dispose(); + _store = (FileStore)_factory!.Create(_sessionId); + } + + + [TearDown] + public void Teardown() { - private FileStore? _store; - private FileStoreFactory? _factory; - - private QuickFix.SessionSettings _settings = new(); - private QuickFix.SessionID _sessionId = new("unset", "unset", "unset"); - - private string _storeDirectory = "unset"; - - [SetUp] - public void Setup() - { - _storeDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "store"); - - if (System.IO.Directory.Exists(_storeDirectory)) - System.IO.Directory.Delete(_storeDirectory, true); - - _sessionId = new QuickFix.SessionID("FIX.4.2", "SENDERCOMP", "TARGETCOMP"); - - QuickFix.SettingsDictionary config = new QuickFix.SettingsDictionary(); - config.SetString(QuickFix.SessionSettings.CONNECTION_TYPE, "initiator"); - config.SetString(QuickFix.SessionSettings.FILE_STORE_PATH, _storeDirectory); - - _settings = new QuickFix.SessionSettings(); - _settings.Set(_sessionId, config); - _factory = new FileStoreFactory(_settings); - - _store = (FileStore)_factory.Create(_sessionId); - } - - void RebuildStore() - { - _store?.Dispose(); - _store = (FileStore)_factory!.Create(_sessionId); - } - - - [TearDown] - public void Teardown() - { - _store!.Dispose(); - Directory.Delete(_storeDirectory, true); - } - - [Test] - public void TestPrefixForSessionWithSubsAndLoc() - { - QuickFix.SessionID sessionIDWithSubsAndLocation = new QuickFix.SessionID("FIX.4.2", "SENDERCOMP", "SENDERSUB", "SENDERLOC", "TARGETCOMP", "TARGETSUB", "TARGETLOC"); - Assert.That(FileStore.Prefix(sessionIDWithSubsAndLocation), Is.EqualTo("FIX.4.2-SENDERCOMP_SENDERSUB_SENDERLOC-TARGETCOMP_TARGETSUB_TARGETLOC")); - - QuickFix.SessionID sessionIDWithSubsNoLocation = new QuickFix.SessionID("FIX.4.2", "SENDERCOMP", "SENDERSUB", "TARGETCOMP", "TARGETSUB"); - Assert.That(FileStore.Prefix(sessionIDWithSubsNoLocation), Is.EqualTo("FIX.4.2-SENDERCOMP_SENDERSUB-TARGETCOMP_TARGETSUB")); - } - - [Test] - public void GenerateFileNamesTest() - { - Assert.That(System.IO.File.Exists(Path.Combine(_storeDirectory, "FIX.4.2-SENDERCOMP-TARGETCOMP.seqnums"))); - Assert.That(System.IO.File.Exists(Path.Combine(_storeDirectory, "FIX.4.2-SENDERCOMP-TARGETCOMP.body"))); - Assert.That(System.IO.File.Exists(Path.Combine(_storeDirectory, "FIX.4.2-SENDERCOMP-TARGETCOMP.header"))); - Assert.That(System.IO.File.Exists(Path.Combine(_storeDirectory, "FIX.4.2-SENDERCOMP-TARGETCOMP.session"))); - } - - [Test] - public void NextSenderMsgSeqNumTest() - { - Assert.That(_store!.NextSenderMsgSeqNum, Is.EqualTo(1)); - _store.NextSenderMsgSeqNum = 5; - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(5)); - RebuildStore(); - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(5)); - } - - [Test] - public void IncNextSenderMsgSeqNumTest() - { - _store!.IncrNextSenderMsgSeqNum(); - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(2)); - RebuildStore(); - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(2)); - } - - [Test] - public void NextTargetMsgSeqNumTest() - { - Assert.That(_store!.NextTargetMsgSeqNum, Is.EqualTo(1)); - _store.NextTargetMsgSeqNum = 6; - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(6)); - RebuildStore(); - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(6)); - } - - [Test] - public void IncNextTargetMsgSeqNumTest() - { - _store!.IncrNextTargetMsgSeqNum(); - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(2)); - RebuildStore(); - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(2)); - } - - /// Using UInt64 seqnums per FIX Trading Community Continuous Markets Working Group recommendations. - [Test] - public void TestSeqNumLimitsForContinuousMarkets() - { - // Given the next seqnums are UInt64.MaxValue - 1 - _store!.NextSenderMsgSeqNum = System.UInt64.MaxValue - 1; - _store.NextTargetMsgSeqNum = _store.NextSenderMsgSeqNum; - - // When the next seqnums are incremented - _store.IncrNextSenderMsgSeqNum(); - _store.IncrNextTargetMsgSeqNum(); - - // Then the next seqnums should be UInt64.MaxValue - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(System.UInt64.MaxValue)); - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(System.UInt64.MaxValue)); - - // When the store is reloaded from files - RebuildStore(); - - // Then the next seqnums should still be UInt64.MaxValue - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(System.UInt64.MaxValue)); - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(System.UInt64.MaxValue)); - - // When the next seqnums are incremented again - _store.IncrNextSenderMsgSeqNum(); - _store.IncrNextTargetMsgSeqNum(); - - // Then the next seqnums should overflow to zero - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(0)); - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(0)); - - // When the store is reloaded from files - RebuildStore(); - - // Then the next seqnums should still be zero - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(0)); - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(0)); - } - - [Test] - public void ResetTest() - { - // seq nums reset - _store!.NextTargetMsgSeqNum = 5; - _store.NextSenderMsgSeqNum = 4; - _store.Reset(); - Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(1)); - Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(1)); - - // Check that messages do not persist after reset - _store.Set(1, "dude"); - _store.Set(2, "pude"); - _store.Set(3, "ok"); - _store.Set(4, "ohai"); - - _store.Reset(); - - var msgs = new List(); - _store.Get(2, 3, msgs); - Assert.That(msgs,Is.Empty); - } - - [Test] - public void CreationTimeTest() - { - DateTime d1 = _store!.CreationTime!.Value; - RebuildStore(); - DateTime d2 = _store.CreationTime.Value; - Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d1, d2); - - Thread.Sleep(1000); - _store.Reset(); - DateTime d3 = _store.CreationTime.Value; - Assert.That(DateTimeOffset.Compare(d1, d3), Is.EqualTo(-1)); // e.g. d1 is earlier than d3 - } - - - [Test] - public void GetTest() - { - _store!.Set(1, "dude"); - _store.Set(2, "pude"); - _store.Set(3, "ok"); - _store.Set(4, "ohai"); - - var msgs = new List(); - _store.Get(2, 3, msgs); - var expected = new List() { "pude", "ok" }; - - Assert.That(msgs, Is.EqualTo(expected)); - - RebuildStore(); - - msgs = new List(); - _store.Get(2, 3, msgs); - - Assert.That(msgs, Is.EqualTo(expected)); - } + _store!.Dispose(); + Directory.Delete(_storeDirectory, true); + } + + [Test] + public void TestPrefixForSessionWithSubsAndLoc() + { + QuickFix.SessionID sessionIDWithSubsAndLocation = new QuickFix.SessionID("FIX.4.2", "SENDERCOMP", "SENDERSUB", "SENDERLOC", "TARGETCOMP", "TARGETSUB", "TARGETLOC"); + Assert.That(FileStore.Prefix(sessionIDWithSubsAndLocation), Is.EqualTo("FIX.4.2-SENDERCOMP_SENDERSUB_SENDERLOC-TARGETCOMP_TARGETSUB_TARGETLOC")); + + QuickFix.SessionID sessionIDWithSubsNoLocation = new QuickFix.SessionID("FIX.4.2", "SENDERCOMP", "SENDERSUB", "TARGETCOMP", "TARGETSUB"); + Assert.That(FileStore.Prefix(sessionIDWithSubsNoLocation), Is.EqualTo("FIX.4.2-SENDERCOMP_SENDERSUB-TARGETCOMP_TARGETSUB")); + } + + [Test] + public void GenerateFileNamesTest() + { + Assert.That(System.IO.File.Exists(Path.Combine(_storeDirectory, "FIX.4.2-SENDERCOMP-TARGETCOMP.seqnums"))); + Assert.That(System.IO.File.Exists(Path.Combine(_storeDirectory, "FIX.4.2-SENDERCOMP-TARGETCOMP.body"))); + Assert.That(System.IO.File.Exists(Path.Combine(_storeDirectory, "FIX.4.2-SENDERCOMP-TARGETCOMP.header"))); + Assert.That(System.IO.File.Exists(Path.Combine(_storeDirectory, "FIX.4.2-SENDERCOMP-TARGETCOMP.session"))); + } + + [Test] + public void NextSenderMsgSeqNumTest() + { + Assert.That(_store!.NextSenderMsgSeqNum, Is.EqualTo(1)); + _store.NextSenderMsgSeqNum = 5; + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(5)); + RebuildStore(); + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(5)); + } + + [Test] + public void IncNextSenderMsgSeqNumTest() + { + _store!.IncrNextSenderMsgSeqNum(); + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(2)); + RebuildStore(); + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(2)); + } + + [Test] + public void NextTargetMsgSeqNumTest() + { + Assert.That(_store!.NextTargetMsgSeqNum, Is.EqualTo(1)); + _store.NextTargetMsgSeqNum = 6; + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(6)); + RebuildStore(); + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(6)); + } + + [Test] + public void IncNextTargetMsgSeqNumTest() + { + _store!.IncrNextTargetMsgSeqNum(); + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(2)); + RebuildStore(); + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(2)); + } + + /// Using UInt64 seqnums per FIX Trading Community Continuous Markets Working Group recommendations. + [Test] + public void TestSeqNumLimitsForContinuousMarkets() + { + // Given the next seqnums are UInt64.MaxValue - 1 + _store!.NextSenderMsgSeqNum = System.UInt64.MaxValue - 1; + _store.NextTargetMsgSeqNum = _store.NextSenderMsgSeqNum; + + // When the next seqnums are incremented + _store.IncrNextSenderMsgSeqNum(); + _store.IncrNextTargetMsgSeqNum(); + + // Then the next seqnums should be UInt64.MaxValue + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(System.UInt64.MaxValue)); + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(System.UInt64.MaxValue)); + + // When the store is reloaded from files + RebuildStore(); + + // Then the next seqnums should still be UInt64.MaxValue + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(System.UInt64.MaxValue)); + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(System.UInt64.MaxValue)); + + // When the next seqnums are incremented again + _store.IncrNextSenderMsgSeqNum(); + _store.IncrNextTargetMsgSeqNum(); + + // Then the next seqnums should overflow to zero + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(0)); + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(0)); + + // When the store is reloaded from files + RebuildStore(); + + // Then the next seqnums should still be zero + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(0)); + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(0)); + } + + [Test] + public void ResetTest() + { + // seq nums reset + _store!.NextTargetMsgSeqNum = 5; + _store.NextSenderMsgSeqNum = 4; + _store.Reset(); + Assert.That(_store.NextTargetMsgSeqNum, Is.EqualTo(1)); + Assert.That(_store.NextSenderMsgSeqNum, Is.EqualTo(1)); + + // Check that messages do not persist after reset + _store.Set(1, "dude"); + _store.Set(2, "pude"); + _store.Set(3, "ok"); + _store.Set(4, "ohai"); + + _store.Reset(); + + var msgs = new List(); + _store.Get(2, 3, msgs); + Assert.That(msgs,Is.Empty); + } + + [Test] + public void CreationTimeTest() + { + DateTime d1 = _store!.CreationTime!.Value; + RebuildStore(); + DateTime d2 = _store.CreationTime.Value; + Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d1, d2); + + Thread.Sleep(1000); + _store.Reset(); + DateTime d3 = _store.CreationTime.Value; + Assert.That(DateTimeOffset.Compare(d1, d3), Is.EqualTo(-1)); // e.g. d1 is earlier than d3 + } + + + [Test] + public void GetTest() + { + _store!.Set(1, "dude"); + _store.Set(2, "pude"); + _store.Set(3, "ok"); + _store.Set(4, "ohai"); + + var msgs = new List(); + _store.Get(2, 3, msgs); + var expected = new List() { "pude", "ok" }; + + Assert.That(msgs, Is.EqualTo(expected)); + + RebuildStore(); + + msgs = new List(); + _store.Get(2, 3, msgs); + + Assert.That(msgs, Is.EqualTo(expected)); } } diff --git a/UnitTests/GenMessageTest.cs b/UnitTests/GenMessageTest.cs index 6dc221355..d6fc0f2ee 100644 --- a/UnitTests/GenMessageTest.cs +++ b/UnitTests/GenMessageTest.cs @@ -2,138 +2,137 @@ using NUnit.Framework; using QuickFix.Fields; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class GenMessageTests { - [TestFixture] - public class GenMessageTests + [Test] + public void TcrFieldPropertiesTest() { - [Test] - public void TcrFieldPropertiesTest() - { - decimal val = 3.232535m; - QuickFix.FIX44.TradeCaptureReport tcr = new(); - tcr.AvgPx = new AvgPx(val); - Assert.That(tcr.AvgPx.Value, Is.EqualTo(val)); - } + decimal val = 3.232535m; + QuickFix.FIX44.TradeCaptureReport tcr = new(); + tcr.AvgPx = new AvgPx(val); + Assert.That(tcr.AvgPx.Value, Is.EqualTo(val)); + } - [Test] - public void TcrFieldGetterTest() - { - AvgPx avgPx = new AvgPx(10.5m); - QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport(); - tcr.SetField(avgPx); - Assert.That(tcr.AvgPx.Value, Is.EqualTo(avgPx.Value)); - AvgPx avgPx2 = new AvgPx(); - tcr.GetField(avgPx2); - Assert.That(avgPx2.Value, Is.EqualTo(avgPx.Value)); - } + [Test] + public void TcrFieldGetterTest() + { + AvgPx avgPx = new AvgPx(10.5m); + QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport(); + tcr.SetField(avgPx); + Assert.That(tcr.AvgPx.Value, Is.EqualTo(avgPx.Value)); + AvgPx avgPx2 = new AvgPx(); + tcr.GetField(avgPx2); + Assert.That(avgPx2.Value, Is.EqualTo(avgPx.Value)); + } - [Test] - public void TcrFieldSetterTypeSafeOldWayTest() - { - AvgPx avgPx = new AvgPx(10.5m); - QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport(); - tcr.Set(avgPx); - Assert.That(tcr.AvgPx.Value, Is.EqualTo(avgPx.Value)); - } + [Test] + public void TcrFieldSetterTypeSafeOldWayTest() + { + AvgPx avgPx = new AvgPx(10.5m); + QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport(); + tcr.Set(avgPx); + Assert.That(tcr.AvgPx.Value, Is.EqualTo(avgPx.Value)); + } - [Test] - public void TcrFieldGetterTypeSafeOldWayTest() - { - AvgPx avgPx = new AvgPx(10.5m); - QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport(); - tcr.Set(new AvgPx(10.5m)); - tcr.Get(avgPx); - Assert.That(tcr.AvgPx.Value, Is.EqualTo(avgPx.Value)); - } + [Test] + public void TcrFieldGetterTypeSafeOldWayTest() + { + AvgPx avgPx = new AvgPx(10.5m); + QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport(); + tcr.Set(new AvgPx(10.5m)); + tcr.Get(avgPx); + Assert.That(tcr.AvgPx.Value, Is.EqualTo(avgPx.Value)); + } - [Test] - public void TcrMsgTypeGetsSetTest() - { - QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport(); - Assert.That(tcr.Header.IsSetField(Tags.MsgType), Is.True); - MsgType msgType = new MsgType(); - tcr.Header.GetField(msgType); - Assert.That(msgType.Value, Is.EqualTo("AE")); - } + [Test] + public void TcrMsgTypeGetsSetTest() + { + QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport(); + Assert.That(tcr.Header.IsSetField(Tags.MsgType), Is.True); + MsgType msgType = new MsgType(); + tcr.Header.GetField(msgType); + Assert.That(msgType.Value, Is.EqualTo("AE")); + } - [Test] - public void TcrReqFieldsCtorTest() - { - QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport( - new TradeReportID("dude1"), - new PreviouslyReported(true), - new Symbol("AAPL"), - new LastQty(100.1m), - new LastPx(100.2m), - new TradeDate("2010-12-12"), - new TransactTime(new DateTime(2010, 12, 15, 10, 55, 32, 455))); - Assert.That(tcr.Symbol.Value, Is.EqualTo("AAPL")); - Assert.That(tcr.TradeReportID.Value, Is.EqualTo("dude1")); - MsgType msgType = new MsgType(); - tcr.Header.GetField(msgType); - Assert.That(msgType.Value, Is.EqualTo("AE")); - } + [Test] + public void TcrReqFieldsCtorTest() + { + QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport( + new TradeReportID("dude1"), + new PreviouslyReported(true), + new Symbol("AAPL"), + new LastQty(100.1m), + new LastPx(100.2m), + new TradeDate("2010-12-12"), + new TransactTime(new DateTime(2010, 12, 15, 10, 55, 32, 455))); + Assert.That(tcr.Symbol.Value, Is.EqualTo("AAPL")); + Assert.That(tcr.TradeReportID.Value, Is.EqualTo("dude1")); + MsgType msgType = new MsgType(); + tcr.Header.GetField(msgType); + Assert.That(msgType.Value, Is.EqualTo("AE")); + } - [Test] - public void TcrIsSetTest() - { - QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport( - new TradeReportID("dude1"), - new PreviouslyReported(true), - new Symbol("AAPL"), - new LastQty(100.1m), - new LastPx(100.2m), - new TradeDate("2010-12-12"), - new TransactTime(new DateTime(2010, 12, 15, 10, 55, 32, 455))); - LastPx lastPx = new LastPx(); - Assert.That(tcr.IsSet(lastPx), Is.True); - AvgPx avgPx = new AvgPx(10.5m); - Assert.That(tcr.IsSet(avgPx), Is.False); - Assert.That(tcr.IsSetAvgPx(), Is.False); - tcr.Set(avgPx); - Assert.That(tcr.IsSet(avgPx), Is.True); - Assert.That(tcr.IsSetAvgPx(), Is.True); + [Test] + public void TcrIsSetTest() + { + QuickFix.FIX44.TradeCaptureReport tcr = new QuickFix.FIX44.TradeCaptureReport( + new TradeReportID("dude1"), + new PreviouslyReported(true), + new Symbol("AAPL"), + new LastQty(100.1m), + new LastPx(100.2m), + new TradeDate("2010-12-12"), + new TransactTime(new DateTime(2010, 12, 15, 10, 55, 32, 455))); + LastPx lastPx = new LastPx(); + Assert.That(tcr.IsSet(lastPx), Is.True); + AvgPx avgPx = new AvgPx(10.5m); + Assert.That(tcr.IsSet(avgPx), Is.False); + Assert.That(tcr.IsSetAvgPx(), Is.False); + tcr.Set(avgPx); + Assert.That(tcr.IsSet(avgPx), Is.True); + Assert.That(tcr.IsSetAvgPx(), Is.True); - } + } - [Test] - public void TcrGroupCtorTest() - { - int[] expFieldOrder = - [ - 54, 37, 198, 11, 526, 66, 453, 1, 660, 581, 81, 575, 576, - 635, 578, 579, 821, 15, 376, 377, 528, 529, 582, 40, 18, 483, - 336, 625, 943, 12, 13, 479, 497, 381, 157, 230, 158, 159, - 738, 920, 921, 922, 238, 237, 118, 119, 120, 155, 156, 77, - 58, 354, 355, 752, 518, 232, 136, 825, 826, 591, 70, 78, 0 - ]; - QuickFix.FIX44.TradeCaptureReport.NoSidesGroup noSides = new QuickFix.FIX44.TradeCaptureReport.NoSidesGroup(); - Assert.That(noSides.FieldOrder, Is.EqualTo(expFieldOrder)); - Assert.That(QuickFix.FIX44.TradeCaptureReport.NoSidesGroup.DefaultFieldOrder, Is.EqualTo(expFieldOrder)); - } + [Test] + public void TcrGroupCtorTest() + { + int[] expFieldOrder = + [ + 54, 37, 198, 11, 526, 66, 453, 1, 660, 581, 81, 575, 576, + 635, 578, 579, 821, 15, 376, 377, 528, 529, 582, 40, 18, 483, + 336, 625, 943, 12, 13, 479, 497, 381, 157, 230, 158, 159, + 738, 920, 921, 922, 238, 237, 118, 119, 120, 155, 156, 77, + 58, 354, 355, 752, 518, 232, 136, 825, 826, 591, 70, 78, 0 + ]; + QuickFix.FIX44.TradeCaptureReport.NoSidesGroup noSides = new QuickFix.FIX44.TradeCaptureReport.NoSidesGroup(); + Assert.That(noSides.FieldOrder, Is.EqualTo(expFieldOrder)); + Assert.That(QuickFix.FIX44.TradeCaptureReport.NoSidesGroup.DefaultFieldOrder, Is.EqualTo(expFieldOrder)); + } - [Test] - public void TcrGroupInGroupCtorTest() - { - int[] expFieldOrder = [757, 758, 759, 806, 0]; - QuickFix.FIX44.TradeCaptureReport.NoSidesGroup.NoAllocsGroup.NoNested2PartyIDsGroup grp = new QuickFix.FIX44.TradeCaptureReport.NoSidesGroup.NoAllocsGroup.NoNested2PartyIDsGroup(); - Assert.That(grp.FieldOrder, Is.EqualTo(expFieldOrder)); - Assert.That(QuickFix.FIX44.TradeCaptureReport.NoSidesGroup.NoAllocsGroup.NoNested2PartyIDsGroup.DefaultFieldOrder, Is.EqualTo(expFieldOrder)); - } + [Test] + public void TcrGroupInGroupCtorTest() + { + int[] expFieldOrder = [757, 758, 759, 806, 0]; + QuickFix.FIX44.TradeCaptureReport.NoSidesGroup.NoAllocsGroup.NoNested2PartyIDsGroup grp = new QuickFix.FIX44.TradeCaptureReport.NoSidesGroup.NoAllocsGroup.NoNested2PartyIDsGroup(); + Assert.That(grp.FieldOrder, Is.EqualTo(expFieldOrder)); + Assert.That(QuickFix.FIX44.TradeCaptureReport.NoSidesGroup.NoAllocsGroup.NoNested2PartyIDsGroup.DefaultFieldOrder, Is.EqualTo(expFieldOrder)); + } - [Test] - public void TcrGroupFieldGetterSetterTest() - { - QuickFix.FIX44.TradeCaptureReport.NoSidesGroup noSides = new QuickFix.FIX44.TradeCaptureReport.NoSidesGroup(); - OrderID ordId = new OrderID("fooey"); - Assert.That(noSides.IsSet(ordId), Is.False); - Assert.That(noSides.IsSetOrderID(), Is.False); - noSides.Set(ordId); - Assert.That(noSides.IsSet(ordId), Is.True); - Assert.That(noSides.IsSetOrderID(), Is.True); - Assert.That(noSides.OrderID.Value, Is.EqualTo("fooey")); - } + [Test] + public void TcrGroupFieldGetterSetterTest() + { + QuickFix.FIX44.TradeCaptureReport.NoSidesGroup noSides = new QuickFix.FIX44.TradeCaptureReport.NoSidesGroup(); + OrderID ordId = new OrderID("fooey"); + Assert.That(noSides.IsSet(ordId), Is.False); + Assert.That(noSides.IsSetOrderID(), Is.False); + noSides.Set(ordId); + Assert.That(noSides.IsSet(ordId), Is.True); + Assert.That(noSides.IsSetOrderID(), Is.True); + Assert.That(noSides.OrderID.Value, Is.EqualTo("fooey")); } } diff --git a/UnitTests/GroupTests.cs b/UnitTests/GroupTests.cs index 3c430204c..0803c7028 100644 --- a/UnitTests/GroupTests.cs +++ b/UnitTests/GroupTests.cs @@ -2,54 +2,53 @@ using QuickFix; using QuickFix.Fields; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class GroupTests { - [TestFixture] - public class GroupTests + [Test] + public void SubGroup() + { + // issue #11 bug, as reported by karabiberoglu's further-down post + + QuickFix.FIX44.CollateralInquiry.NoPartyIDsGroup noParty = new(); + noParty.PartyID = new PartyID("ABC"); + noParty.PartyIDSource = new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE); + noParty.PartyRole = new PartyRole(PartyRole.CLEARING_FIRM); + + // group in group + QuickFix.FIX44.CollateralInquiry.NoPartyIDsGroup.NoPartySubIDsGroup noPartySub = new(); + noPartySub.PartySubID = new PartySubID("subABC"); + noPartySub.PartySubIDType = new PartySubIDType(PartySubIDType.FIRM); + noParty.AddGroup(noPartySub); + noPartySub.PartySubID = new PartySubID("subDEF"); + noPartySub.PartySubIDType = new PartySubIDType(PartySubIDType.LOCATION); + noParty.AddGroup(noPartySub); + + string msgString = noParty.ToString(); + string expected = "448=ABC|447=D|452=4|" + + "802=2|" //NoPartySubIDs + + "523=subABC|803=1|" + + "523=subDEF|803=31|"; + + //Console.WriteLine(msgString); + Assert.That(msgString.Replace(Message.SOH, '|'), Does.Contain(expected)); + } + + [Test] + public void GroupClone() { - [Test] - public void SubGroup() - { - // issue #11 bug, as reported by karabiberoglu's further-down post - - QuickFix.FIX44.CollateralInquiry.NoPartyIDsGroup noParty = new(); - noParty.PartyID = new PartyID("ABC"); - noParty.PartyIDSource = new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE); - noParty.PartyRole = new PartyRole(PartyRole.CLEARING_FIRM); - - // group in group - QuickFix.FIX44.CollateralInquiry.NoPartyIDsGroup.NoPartySubIDsGroup noPartySub = new(); - noPartySub.PartySubID = new PartySubID("subABC"); - noPartySub.PartySubIDType = new PartySubIDType(PartySubIDType.FIRM); - noParty.AddGroup(noPartySub); - noPartySub.PartySubID = new PartySubID("subDEF"); - noPartySub.PartySubIDType = new PartySubIDType(PartySubIDType.LOCATION); - noParty.AddGroup(noPartySub); - - string msgString = noParty.ToString(); - string expected = "448=ABC|447=D|452=4|" - + "802=2|" //NoPartySubIDs - + "523=subABC|803=1|" - + "523=subDEF|803=31|"; - - //Console.WriteLine(msgString); - Assert.That(msgString.Replace(Message.SOH, '|'), Does.Contain(expected)); - } - - [Test] - public void GroupClone() - { - QuickFix.FIX42.News.LinesOfTextGroup linesGroup = new(); - linesGroup.Text = new Text("foo"); - linesGroup.EncodedText = new EncodedText("bar"); - - QuickFix.FIX42.News.LinesOfTextGroup clone = (linesGroup.Clone() as QuickFix.FIX42.News.LinesOfTextGroup)!; - - Assert.That(clone.Text.Value, Is.EqualTo(linesGroup.Text.Value)); - Assert.That(clone.EncodedText.Value, Is.EqualTo(linesGroup.EncodedText.Value)); - Assert.That(clone.Delim, Is.EqualTo(linesGroup.Delim)); - Assert.That(clone.CounterField, Is.EqualTo(linesGroup.CounterField)); - Assert.That(clone.FieldOrder, Is.EqualTo(linesGroup.FieldOrder)); - } + QuickFix.FIX42.News.LinesOfTextGroup linesGroup = new(); + linesGroup.Text = new Text("foo"); + linesGroup.EncodedText = new EncodedText("bar"); + + QuickFix.FIX42.News.LinesOfTextGroup clone = (linesGroup.Clone() as QuickFix.FIX42.News.LinesOfTextGroup)!; + + Assert.That(clone.Text.Value, Is.EqualTo(linesGroup.Text.Value)); + Assert.That(clone.EncodedText.Value, Is.EqualTo(linesGroup.EncodedText.Value)); + Assert.That(clone.Delim, Is.EqualTo(linesGroup.Delim)); + Assert.That(clone.CounterField, Is.EqualTo(linesGroup.CounterField)); + Assert.That(clone.FieldOrder, Is.EqualTo(linesGroup.FieldOrder)); } } diff --git a/UnitTests/MemoryStoreTest.cs b/UnitTests/MemoryStoreTest.cs index 9d153e2bd..43d521dc9 100644 --- a/UnitTests/MemoryStoreTest.cs +++ b/UnitTests/MemoryStoreTest.cs @@ -1,32 +1,27 @@ using System.Collections.Generic; using NUnit.Framework; -using QuickFix; -using QuickFix.Fields; using QuickFix.Store; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class MemoryStoreTests { - [TestFixture] - public class MemoryStoreTests + [Test] + public void GetTest() { - [Test] - public void GetTest() - { - MemoryStore store = new MemoryStore(); - store.Set(1, "dude"); - store.Set(2, "pude"); - store.Set(3, "ok"); - store.Set(4, "ohai"); - var msgs = new List(); - store.Get(2, 3, msgs); - var expected = new List() { "pude", "ok" }; - Assert.That(msgs, Is.EqualTo(expected)); - - msgs = new List(); - store.Get(5, 6, msgs); - Assert.That(msgs, Is.Empty); - + MemoryStore store = new MemoryStore(); + store.Set(1, "dude"); + store.Set(2, "pude"); + store.Set(3, "ok"); + store.Set(4, "ohai"); + List msgs = []; + store.Get(2, 3, msgs); + List expected = ["pude", "ok"]; + Assert.That(msgs, Is.EqualTo(expected)); - } + msgs = []; + store.Get(5, 6, msgs); + Assert.That(msgs, Is.Empty); } -} \ No newline at end of file +} diff --git a/UnitTests/MessageCrackerTests.cs b/UnitTests/MessageCrackerTests.cs index 355dfd28c..922201d3a 100644 --- a/UnitTests/MessageCrackerTests.cs +++ b/UnitTests/MessageCrackerTests.cs @@ -3,110 +3,109 @@ using QuickFix; using System.Reflection; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class MessageCrackerTests { - [TestFixture] - public class MessageCrackerTests + private readonly SessionID _dummySessionId = new ("a","b","c"); + + [SetUp] + public void Setup() { - private readonly SessionID _dummySessionId = new ("a","b","c"); + } - [SetUp] - public void Setup() - { - } + [TearDown] + public void Teardown() + { + } - [TearDown] - public void Teardown() - { - } + class TheseMightBeHandlerMethods + { + // These are handlers. + public void OnMessage(QuickFix.FIX42.News m, SessionID s) { } + public void OnMessage(QuickFix.FIXT11.Logon m, SessionID s) { } - class TheseMightBeHandlerMethods - { - // These are handlers. - public void OnMessage(QuickFix.FIX42.News m, SessionID s) { } - public void OnMessage(QuickFix.FIXT11.Logon m, SessionID s) { } + // These are NOT handlers because... - // These are NOT handlers because... + // it's private + private void OnMessage(QuickFix.FIX42.ListCancelRequest m, SessionID s) { } - // it's private - private void OnMessage(QuickFix.FIX42.ListCancelRequest m, SessionID s) { } + // name doesn't match convention + public void NameIsWrong(QuickFix.FIX42.ListExecute m, SessionID s) { } - // name doesn't match convention - public void NameIsWrong(QuickFix.FIX42.ListExecute m, SessionID s) { } + // params count != 2 + public void OnMessage(QuickFix.FIX42.ListStatus m) { } + public void OnMessage(QuickFix.FIX42.ListStatusRequest m, SessionID s, object o) { } - // params count != 2 - public void OnMessage(QuickFix.FIX42.ListStatus m) { } - public void OnMessage(QuickFix.FIX42.ListStatusRequest m, SessionID s, object o) { } + // param types aren't correct + public void OnMessage(object o, SessionID s) { } + public void OnMessage(QuickFix.FIX42.ListStrikePrice m, object o) { } - // param types aren't correct - public void OnMessage(object o, SessionID s) { } - public void OnMessage(QuickFix.FIX42.ListStrikePrice m, object o) { } + // return value isn't void + public int OnMessage(QuickFix.FIX42.MassQuote m, SessionID s) { return 0; } + } - // return value isn't void - public int OnMessage(QuickFix.FIX42.MassQuote m, SessionID s) { return 0; } - } + [Test] + public void IsHandlerMethod() + { + MethodInfo[] methods = typeof(TheseMightBeHandlerMethods).GetMethods(); + List handlers = []; - [Test] - public void IsHandlerMethod() + foreach (MethodInfo m in methods) { - MethodInfo[] methods = typeof(TheseMightBeHandlerMethods).GetMethods(); - List handlers = new List(); - - foreach (MethodInfo m in methods) + if (MessageCracker.IsHandlerMethod(m)) { - if (MessageCracker.IsHandlerMethod(m)) - { - handlers.Add(m); - } + handlers.Add(m); } - - Assert.That(handlers.Count, Is.EqualTo(2)); - Assert.That(typeof(QuickFix.FIX42.News), Is.EqualTo(handlers[0].GetParameters()[0].ParameterType)); - Assert.That(typeof(QuickFix.FIXT11.Logon), Is.EqualTo(handlers[1].GetParameters()[0].ParameterType)); } + Assert.That(handlers.Count, Is.EqualTo(2)); + Assert.That(typeof(QuickFix.FIX42.News), Is.EqualTo(handlers[0].GetParameters()[0].ParameterType)); + Assert.That(typeof(QuickFix.FIXT11.Logon), Is.EqualTo(handlers[1].GetParameters()[0].ParameterType)); + } - public class TestCracker : MessageCracker - { - public bool CrackedNews42 { get; set; } - public bool CrackedNews44 { get; set; } - public bool CrackedLogonFIXT11 { get; set; } - public void OnMessage(QuickFix.FIX42.News msg, SessionID s) { CrackedNews42 = true; } - public void OnMessage(QuickFix.FIX44.News msg, SessionID s) { CrackedNews44 = true; } - public void OnMessage(QuickFix.FIXT11.Logon msg, SessionID s) { CrackedLogonFIXT11 = true; } - } + public class TestCracker : MessageCracker + { + public bool CrackedNews42 { get; set; } + public bool CrackedNews44 { get; set; } + public bool CrackedLogonFIXT11 { get; set; } - [Test] - public void GoldenPath() - { - MessageCracker mc = new TestCracker(); - TestCracker tc = (mc as TestCracker)!; + public void OnMessage(QuickFix.FIX42.News msg, SessionID s) { CrackedNews42 = true; } + public void OnMessage(QuickFix.FIX44.News msg, SessionID s) { CrackedNews44 = true; } + public void OnMessage(QuickFix.FIXT11.Logon msg, SessionID s) { CrackedLogonFIXT11 = true; } + } - mc.Crack(new QuickFix.FIX42.News(), _dummySessionId); - Assert.That(tc.CrackedNews42, Is.True); - Assert.That(tc.CrackedNews44, Is.False); + [Test] + public void GoldenPath() + { + MessageCracker mc = new TestCracker(); + TestCracker tc = (mc as TestCracker)!; - // reset and do the opposite - tc.CrackedNews42 = false; + mc.Crack(new QuickFix.FIX42.News(), _dummySessionId); + Assert.That(tc.CrackedNews42, Is.True); + Assert.That(tc.CrackedNews44, Is.False); - mc.Crack(new QuickFix.FIX44.News(), _dummySessionId); - Assert.That(tc.CrackedNews42, Is.False); - Assert.That(tc.CrackedNews44, Is.True); + // reset and do the opposite + tc.CrackedNews42 = false; - Assert.That(tc.CrackedLogonFIXT11, Is.False); - mc.Crack(new QuickFix.FIXT11.Logon(), _dummySessionId); - Assert.That(tc.CrackedLogonFIXT11, Is.True); - } + mc.Crack(new QuickFix.FIX44.News(), _dummySessionId); + Assert.That(tc.CrackedNews42, Is.False); + Assert.That(tc.CrackedNews44, Is.True); - [Test] - public void UnsupportedMessage() - { - MessageCracker mc = new TestCracker(); - Assert.Throws(delegate { mc.Crack(new QuickFix.FIX42.Email(), _dummySessionId); }); - Assert.Throws(delegate { mc.Crack(new QuickFix.FIX43.News(), _dummySessionId); }); - } + Assert.That(tc.CrackedLogonFIXT11, Is.False); + mc.Crack(new QuickFix.FIXT11.Logon(), _dummySessionId); + Assert.That(tc.CrackedLogonFIXT11, Is.True); + } + + [Test] + public void UnsupportedMessage() + { + MessageCracker mc = new TestCracker(); + Assert.Throws(delegate { mc.Crack(new QuickFix.FIX42.Email(), _dummySessionId); }); + Assert.Throws(delegate { mc.Crack(new QuickFix.FIX43.News(), _dummySessionId); }); } } diff --git a/UnitTests/MessageTests.cs b/UnitTests/MessageTests.cs index 0b3cfc20d..30152706f 100644 --- a/UnitTests/MessageTests.cs +++ b/UnitTests/MessageTests.cs @@ -6,1125 +6,1124 @@ using UnitTests.TestHelpers; using Message = QuickFix.Message; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class MessageTests { - [TestFixture] - public class MessageTests - { - private readonly IMessageFactory _defaultMsgFactory = new DefaultMessageFactory(); + private readonly IMessageFactory _defaultMsgFactory = new DefaultMessageFactory(); - [Test] - public void IdentifyTypeTest() - { - string msg1 = "|35=A|".Replace('|', Message.SOH); - Assert.That(Message.IdentifyType(msg1).Value, Is.EqualTo(new MsgType("A").Value)); - string msg2 = "a;sldkfjadls;k|35=A|a;sldkfja;sdlfk".Replace('|', Message.SOH); - Assert.That(Message.IdentifyType(msg2).Value, Is.EqualTo(new MsgType("A").Value)); - string msg3 = "8=FIX4.2|9=12||35=B|10=031|".Replace('|', Message.SOH); - Assert.That(Message.IdentifyType(msg3).Value, Is.EqualTo(new MsgType("B").Value)); - - // no 35 - string err1 = "8=FIX.4.4|49=Sender|".Replace('|', Message.SOH); - Assert.Throws(delegate { Message.IdentifyType(err1); }); - // no SOH at end of 35 - string err2 = "8=FIX.4.4|35=A".Replace('|', Message.SOH); - Assert.Throws(delegate { Message.IdentifyType(err2); }); - } + [Test] + public void IdentifyTypeTest() + { + string msg1 = "|35=A|".Replace('|', Message.SOH); + Assert.That(Message.IdentifyType(msg1).Value, Is.EqualTo(new MsgType("A").Value)); + string msg2 = "a;sldkfjadls;k|35=A|a;sldkfja;sdlfk".Replace('|', Message.SOH); + Assert.That(Message.IdentifyType(msg2).Value, Is.EqualTo(new MsgType("A").Value)); + string msg3 = "8=FIX4.2|9=12||35=B|10=031|".Replace('|', Message.SOH); + Assert.That(Message.IdentifyType(msg3).Value, Is.EqualTo(new MsgType("B").Value)); + + // no 35 + string err1 = "8=FIX.4.4|49=Sender|".Replace('|', Message.SOH); + Assert.Throws(delegate { Message.IdentifyType(err1); }); + // no SOH at end of 35 + string err2 = "8=FIX.4.4|35=A".Replace('|', Message.SOH); + Assert.Throws(delegate { Message.IdentifyType(err2); }); + } - [Test] - public void ExtractStringTest() - { - string str1 = "8=FIX.4.2|9=46|35=0|34=3|49=TW|".Replace('|', Message.SOH); - int pos = 0; - StringField sf1 = Message.ExtractField(str1, ref pos); - Assert.That(pos, Is.EqualTo(10)); - Assert.That(sf1.Tag, Is.EqualTo(8)); - Assert.That(sf1.Value, Is.EqualTo("FIX.4.2")); - StringField sf2 = Message.ExtractField(str1, ref pos); - Assert.That(pos, Is.EqualTo(15)); - Assert.That(sf2.Tag, Is.EqualTo(9)); - Assert.That(sf2.Value, Is.EqualTo("46")); - } + [Test] + public void ExtractStringTest() + { + string str1 = "8=FIX.4.2|9=46|35=0|34=3|49=TW|".Replace('|', Message.SOH); + int pos = 0; + StringField sf1 = Message.ExtractField(str1, ref pos); + Assert.That(pos, Is.EqualTo(10)); + Assert.That(sf1.Tag, Is.EqualTo(8)); + Assert.That(sf1.Value, Is.EqualTo("FIX.4.2")); + StringField sf2 = Message.ExtractField(str1, ref pos); + Assert.That(pos, Is.EqualTo(15)); + Assert.That(sf2.Tag, Is.EqualTo(9)); + Assert.That(sf2.Value, Is.EqualTo("46")); + } - [Test] - public void ExtractStringErrorsTest() - { - int pos = 0; - Assert.Throws(typeof(MessageParseError), - delegate { Message.ExtractField("=", ref pos); }); - Assert.Throws(typeof(MessageParseError), - delegate { Message.ExtractField("35=A", ref pos); }); - Assert.Throws(typeof(MessageParseError), - delegate { Message.ExtractField("\x01" + "35=A", ref pos); }); - Assert.Throws(typeof(MessageParseError), - delegate { Message.ExtractField("35=\x01", ref pos); }); - } + [Test] + public void ExtractStringErrorsTest() + { + int pos = 0; + Assert.Throws(typeof(MessageParseError), + delegate { Message.ExtractField("=", ref pos); }); + Assert.Throws(typeof(MessageParseError), + delegate { Message.ExtractField("35=A", ref pos); }); + Assert.Throws(typeof(MessageParseError), + delegate { Message.ExtractField("\x01" + "35=A", ref pos); }); + Assert.Throws(typeof(MessageParseError), + delegate { Message.ExtractField("35=\x01", ref pos); }); + } - [Test] - public void CheckSumTest() - { - string str1 = "8=FIX.4.2|9=45|35=0|34=3|49=TW|52=20000426-12:05:06|56=ISLD|".Replace('|', Message.SOH); + [Test] + public void CheckSumTest() + { + string str1 = "8=FIX.4.2|9=45|35=0|34=3|49=TW|52=20000426-12:05:06|56=ISLD|".Replace('|', Message.SOH); - int chksum = 0; - foreach (char c in str1) - chksum += c; - chksum %= 256; + int chksum = 0; + foreach (char c in str1) + chksum += c; + chksum %= 256; - str1 += "10=218\x01"; // checksum field - Message msg = new Message(); - try - { - msg.FromString(str1, true, null, null, _defaultMsgFactory); - } - catch (InvalidMessage e) - { - Assert.Fail("Unexpected exception (InvalidMessage): " + e.Message); - } - Assert.That(msg.CheckSum(), Is.EqualTo(chksum)); + str1 += "10=218\x01"; // checksum field + Message msg = new Message(); + try + { + msg.FromString(str1, true, null, null, _defaultMsgFactory); } - - [Test] - public void FromStringTestWithNoDataDictionary() + catch (InvalidMessage e) { - string str1 = "8=FIX.4.2|9=55|35=0|34=3|49=TW|52=20000426-12:05:06|56=ISLD|1=acct123|10=123|" - .Replace('|', Message.SOH); - - Message msg = new(); - try - { - msg.FromString(str1, true, null, null, _defaultMsgFactory); - } - catch (InvalidMessage e) - { - Assert.Fail("Unexpected exception (InvalidMessage): " + e.Message); - } - StringField f1 = new StringField(8); - StringField f2 = new StringField(9); - StringField f3 = new StringField(35); - StringField f4 = new StringField(34); - StringField f5 = new StringField(49); - StringField f6 = new StringField(52); - StringField f7 = new StringField(56); - StringField f8 = new StringField(10); - StringField f9 = new StringField(1); - msg.Header.GetField(f1); - msg.Header.GetField(f2); - msg.Header.GetField(f3); - msg.Header.GetField(f4); - msg.Header.GetField(f5); - msg.Header.GetField(f6); - msg.Header.GetField(f7); - msg.GetField(f9); - msg.Trailer.GetField(f8); - Assert.That(f1.Value, Is.EqualTo("FIX.4.2")); - Assert.That(f2.Value, Is.EqualTo("55")); - Assert.That(f3.Value, Is.EqualTo("0")); - Assert.That(f4.Value, Is.EqualTo("3")); - Assert.That(f5.Value, Is.EqualTo("TW")); - Assert.That(f6.Value, Is.EqualTo("20000426-12:05:06")); - Assert.That(f7.Value, Is.EqualTo("ISLD")); - Assert.That(f8.Value, Is.EqualTo("123")); - Assert.That(f9.Value, Is.EqualTo("acct123")); + Assert.Fail("Unexpected exception (InvalidMessage): " + e.Message); } + Assert.That(msg.CheckSum(), Is.EqualTo(chksum)); + } - [Test] - public void FromString_Groups_NoFactory() + [Test] + public void FromStringTestWithNoDataDictionary() + { + string str1 = "8=FIX.4.2|9=55|35=0|34=3|49=TW|52=20000426-12:05:06|56=ISLD|1=acct123|10=123|" + .Replace('|', Message.SOH); + + Message msg = new(); + try { - // issue 179 - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - - string msgStr = - ("8=FIX.4.4|9=638|35=8|34=360|49=BLPTSOX|52=20130321-15:21:23|56=THINKTSOX|57=6804469|128=ZERO|" - // non-group body fields - + "6=122.255|11=61101189|14=1990000|15=GBP|17=VCON:20130321:50018:5:12|22=4|31=122.255|32=1990000|" - + "37=116|38=1990000|39=2|48=GB0032452392|54=1|55=[N/A]|60=20130321-15:21:23|64=20130322|75=20130321|" - + "106=UK TSY 4 1/4% 2036|118=2436321.85|150=F|151=0|157=15|159=3447.35|192=0|198=3739:20130321:50018:5|" - + "223=0.0425|228=1|236=0.0291371041|238=0|381=2432874.5|423=1|470=GB|541=20360307|" - // NoPartyIDs - + "453=6|" - + "448=VCON|447=D|452=1|802=1|523=14|803=4|" - + "448=TFOLIO:6804469|447=D|452=12|" - + "448=TFOLIO|447=D|452=11|" - + "448=THINKFOLIO LTD|447=D|452=13|" - + "448=SXT|447=D|452=16|" - + "448=TFOLIO:6804469|447=D|452=36|" - + "10=152|").Replace('|', Message.SOH); - - QuickFix.FIX44.ExecutionReport msg = new QuickFix.FIX44.ExecutionReport(); - msg.FromString(msgStr, true, dd, dd, null); // <-- null factory! - - //Console.WriteLine(msg.ToString()); - - QuickFix.FIX44.ExecutionReport.NoPartyIDsGroup partyGroup = new QuickFix.FIX44.ExecutionReport.NoPartyIDsGroup(); - msg.GetGroup(2, partyGroup); - - Assert.That(partyGroup.IsSetNoPartySubIDs(), Is.False); + msg.FromString(str1, true, null, null, _defaultMsgFactory); } - - [Test] - public void FromString_DoNotCorrectCounter() + catch (InvalidMessage e) { - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX42"); + Assert.Fail("Unexpected exception (InvalidMessage): " + e.Message); + } + StringField f1 = new StringField(8); + StringField f2 = new StringField(9); + StringField f3 = new StringField(35); + StringField f4 = new StringField(34); + StringField f5 = new StringField(49); + StringField f6 = new StringField(52); + StringField f7 = new StringField(56); + StringField f8 = new StringField(10); + StringField f9 = new StringField(1); + msg.Header.GetField(f1); + msg.Header.GetField(f2); + msg.Header.GetField(f3); + msg.Header.GetField(f4); + msg.Header.GetField(f5); + msg.Header.GetField(f6); + msg.Header.GetField(f7); + msg.GetField(f9); + msg.Trailer.GetField(f8); + Assert.That(f1.Value, Is.EqualTo("FIX.4.2")); + Assert.That(f2.Value, Is.EqualTo("55")); + Assert.That(f3.Value, Is.EqualTo("0")); + Assert.That(f4.Value, Is.EqualTo("3")); + Assert.That(f5.Value, Is.EqualTo("TW")); + Assert.That(f6.Value, Is.EqualTo("20000426-12:05:06")); + Assert.That(f7.Value, Is.EqualTo("ISLD")); + Assert.That(f8.Value, Is.EqualTo("123")); + Assert.That(f9.Value, Is.EqualTo("acct123")); + } - QuickFix.FIX42.NewOrderSingle n = new QuickFix.FIX42.NewOrderSingle(); + [Test] + public void FromString_Groups_NoFactory() + { + // issue 179 + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + + string msgStr = + ("8=FIX.4.4|9=638|35=8|34=360|49=BLPTSOX|52=20130321-15:21:23|56=THINKTSOX|57=6804469|128=ZERO|" + // non-group body fields + + "6=122.255|11=61101189|14=1990000|15=GBP|17=VCON:20130321:50018:5:12|22=4|31=122.255|32=1990000|" + + "37=116|38=1990000|39=2|48=GB0032452392|54=1|55=[N/A]|60=20130321-15:21:23|64=20130322|75=20130321|" + + "106=UK TSY 4 1/4% 2036|118=2436321.85|150=F|151=0|157=15|159=3447.35|192=0|198=3739:20130321:50018:5|" + + "223=0.0425|228=1|236=0.0291371041|238=0|381=2432874.5|423=1|470=GB|541=20360307|" + // NoPartyIDs + + "453=6|" + + "448=VCON|447=D|452=1|802=1|523=14|803=4|" + + "448=TFOLIO:6804469|447=D|452=12|" + + "448=TFOLIO|447=D|452=11|" + + "448=THINKFOLIO LTD|447=D|452=13|" + + "448=SXT|447=D|452=16|" + + "448=TFOLIO:6804469|447=D|452=36|" + + "10=152|").Replace('|', Message.SOH); + + QuickFix.FIX44.ExecutionReport msg = new QuickFix.FIX44.ExecutionReport(); + msg.FromString(msgStr, true, dd, dd, null); // <-- null factory! + + //Console.WriteLine(msg.ToString()); + + QuickFix.FIX44.ExecutionReport.NoPartyIDsGroup partyGroup = new QuickFix.FIX44.ExecutionReport.NoPartyIDsGroup(); + msg.GetGroup(2, partyGroup); + + Assert.That(partyGroup.IsSetNoPartySubIDs(), Is.False); + } - string s = ("8=FIX.4.2|9=148|35=D|34=2|49=TW|52=20111011-15:06:23.103|56=ISLD|" - + "11=ID|21=1|40=1|54=1|38=200.00|55=INTC|" - + "386=3|336=PRE-OPEN|336=AFTER-HOURS|" - + "60=20111011-15:06:23.103|" - + "10=35|").Replace('|', Message.SOH); + [Test] + public void FromString_DoNotCorrectCounter() + { + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX42"); - n.FromString(s, true, dd, dd, _defaultMsgFactory); - Assert.That(n.NoTradingSessions.ToStringField(), Is.EqualTo("386=3")); - Assert.That(n.ConstructString(), Does.Contain("386=3")); //should not be "corrected" to 2! - } + QuickFix.FIX42.NewOrderSingle n = new QuickFix.FIX42.NewOrderSingle(); - [Test] - public void FromString_GroupDelimiterIssue() - { - // 349 - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX42"); + string s = ("8=FIX.4.2|9=148|35=D|34=2|49=TW|52=20111011-15:06:23.103|56=ISLD|" + + "11=ID|21=1|40=1|54=1|38=200.00|55=INTC|" + + "386=3|336=PRE-OPEN|336=AFTER-HOURS|" + + "60=20111011-15:06:23.103|" + + "10=35|").Replace('|', Message.SOH); - QuickFix.FIX42.News n = new QuickFix.FIX42.News(); + n.FromString(s, true, dd, dd, _defaultMsgFactory); + Assert.That(n.NoTradingSessions.ToStringField(), Is.EqualTo("386=3")); + Assert.That(n.ConstructString(), Does.Contain("386=3")); //should not be "corrected" to 2! + } - string s = ("8=FIX.4.2|9=91|35=B|34=2|49=TW|52=20111011-15:06:23.103|56=ISLD|" - + "148=headline|33=3|" - + "58=line1|354=3|355=uno|" // first group, has delimiter - + "354=3|355=dos|" // second group, missing delimiter - + "354=4|355=tres|" // third group, also missing delimiter - + "10=193|").Replace('|', Message.SOH); + [Test] + public void FromString_GroupDelimiterIssue() + { + // 349 + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX42"); - Assert.Throws(delegate { n.FromString(s, true, dd, dd, _defaultMsgFactory); }); - } + QuickFix.FIX42.News n = new QuickFix.FIX42.News(); - [Test] - public void ConstructStringFieldOrder() - { - Message msg = new Message(); - msg.Header.SetField(new MsgType("A")); - msg.Header.SetField(new BeginString("FIX.4.2")); - msg.Header.SetField(new SenderCompID("SENDER")); - msg.Header.SetField(new TargetCompID("TARGET")); - msg.Header.SetField(new MsgSeqNum(42)); - string expect = "8=FIX.4.2|9=31|35=A|34=42|49=SENDER|56=TARGET|10=200|".Replace('|', Message.SOH); - Assert.That(msg.ConstructString(), Is.EqualTo(expect)); - } + string s = ("8=FIX.4.2|9=91|35=B|34=2|49=TW|52=20111011-15:06:23.103|56=ISLD|" + + "148=headline|33=3|" + + "58=line1|354=3|355=uno|" // first group, has delimiter + + "354=3|355=dos|" // second group, missing delimiter + + "354=4|355=tres|" // third group, also missing delimiter + + "10=193|").Replace('|', Message.SOH); - [Test] - public void IsHeaderFieldTest() - { - Assert.That(Message.IsHeaderField(Tags.BeginString, null), Is.EqualTo(true)); - Assert.That(Message.IsHeaderField(Tags.TargetCompID, null), Is.EqualTo(true)); - Assert.That(Message.IsHeaderField(Tags.Account, null), Is.EqualTo(false)); - - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - dd.Header.AddField( - new QuickFix.DataDictionary.DDField(901109, "FakeField", new Dictionary(), "STRING")); - - Assert.That(Message.IsHeaderField(Tags.TargetCompID, dd), Is.EqualTo(true)); - Assert.That(Message.IsHeaderField(Tags.Account, dd), Is.EqualTo(false)); - Assert.That(Message.IsHeaderField(901109, dd), Is.EqualTo(true)); - } + Assert.Throws(delegate { n.FromString(s, true, dd, dd, _defaultMsgFactory); }); + } - [Test] - public void IsTrailerFieldTest() - { - Assert.That(Message.IsTrailerField(Tags.CheckSum), Is.EqualTo(true)); - Assert.That(Message.IsTrailerField(Tags.Price), Is.EqualTo(false)); - } + [Test] + public void ConstructStringFieldOrder() + { + Message msg = new Message(); + msg.Header.SetField(new MsgType("A")); + msg.Header.SetField(new BeginString("FIX.4.2")); + msg.Header.SetField(new SenderCompID("SENDER")); + msg.Header.SetField(new TargetCompID("TARGET")); + msg.Header.SetField(new MsgSeqNum(42)); + string expect = "8=FIX.4.2|9=31|35=A|34=42|49=SENDER|56=TARGET|10=200|".Replace('|', Message.SOH); + Assert.That(msg.ConstructString(), Is.EqualTo(expect)); + } - [Test] - public void EnumeratorTest() - { - string msgStr = "8=FIX.4.2|9=55|35=0|34=3|49=TW|52=20000426-12:05:06|56=ISLD|1=acct123|10=123|" - .Replace('|', Message.SOH); - Message msg = new Message(msgStr); - - int numHeaderFields = 0; - foreach (KeyValuePair unused in msg.Header) - ++numHeaderFields; - Assert.That(numHeaderFields, Is.EqualTo(7)); - - int numTrailerFields = 0; - foreach (KeyValuePair unused in msg.Trailer) - ++numTrailerFields; - Assert.That(numTrailerFields, Is.EqualTo(1)); - - int numBodyFields = 0; - foreach (KeyValuePair unused in msg) - ++numBodyFields; - Assert.That(numBodyFields, Is.EqualTo(1)); - } + [Test] + public void IsHeaderFieldTest() + { + Assert.That(Message.IsHeaderField(Tags.BeginString, null), Is.EqualTo(true)); + Assert.That(Message.IsHeaderField(Tags.TargetCompID, null), Is.EqualTo(true)); + Assert.That(Message.IsHeaderField(Tags.Account, null), Is.EqualTo(false)); + + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + dd.Header.AddField( + new QuickFix.DataDictionary.DDField(901109, "FakeField", new Dictionary(), "STRING")); + + Assert.That(Message.IsHeaderField(Tags.TargetCompID, dd), Is.EqualTo(true)); + Assert.That(Message.IsHeaderField(Tags.Account, dd), Is.EqualTo(false)); + Assert.That(Message.IsHeaderField(901109, dd), Is.EqualTo(true)); + } - [Test] - public void RepeatedTagDetection() - { - string msgStr = ("8=FIX.4.2|9=72|35=0|34=3|49=TW|49=BOGUS|52=20000426-12:05:06|56=ISLD|" - + "1=acct123|1=bogus|10=052|10=000|").Replace('|', Message.SOH); - Message msg = new Message(msgStr); - Assert.That(msg.Header.RepeatedTags.Count, Is.EqualTo(1)); - Assert.That(msg.Header.RepeatedTags[0].Tag, Is.EqualTo(49)); + [Test] + public void IsTrailerFieldTest() + { + Assert.That(Message.IsTrailerField(Tags.CheckSum), Is.EqualTo(true)); + Assert.That(Message.IsTrailerField(Tags.Price), Is.EqualTo(false)); + } - Assert.That(msg.Trailer.RepeatedTags.Count, Is.EqualTo(1)); - Assert.That(msg.Trailer.RepeatedTags[0].Tag, Is.EqualTo(10)); + [Test] + public void EnumeratorTest() + { + string msgStr = "8=FIX.4.2|9=55|35=0|34=3|49=TW|52=20000426-12:05:06|56=ISLD|1=acct123|10=123|" + .Replace('|', Message.SOH); + Message msg = new Message(msgStr); + + int numHeaderFields = 0; + foreach (KeyValuePair unused in msg.Header) + ++numHeaderFields; + Assert.That(numHeaderFields, Is.EqualTo(7)); + + int numTrailerFields = 0; + foreach (KeyValuePair unused in msg.Trailer) + ++numTrailerFields; + Assert.That(numTrailerFields, Is.EqualTo(1)); + + int numBodyFields = 0; + foreach (KeyValuePair unused in msg) + ++numBodyFields; + Assert.That(numBodyFields, Is.EqualTo(1)); + } - Assert.That(msg.RepeatedTags.Count, Is.EqualTo(1)); - Assert.That(msg.RepeatedTags[0].Tag, Is.EqualTo(1)); - } + [Test] + public void RepeatedTagDetection() + { + string msgStr = ("8=FIX.4.2|9=72|35=0|34=3|49=TW|49=BOGUS|52=20000426-12:05:06|56=ISLD|" + + "1=acct123|1=bogus|10=052|10=000|").Replace('|', Message.SOH); + Message msg = new Message(msgStr); + Assert.That(msg.Header.RepeatedTags.Count, Is.EqualTo(1)); + Assert.That(msg.Header.RepeatedTags[0].Tag, Is.EqualTo(49)); - [Test] - public void AddGroupGetGroupTest() - { - var nos = new QuickFix.FIX42.NewOrderSingle(); - var noTradingSessions = new QuickFix.FIX42.NewOrderSingle.NoTradingSessionsGroup(); - noTradingSessions.SetField(new StringField(336, "OHHAI")); - nos.AddGroup(noTradingSessions); - var noTradingSessionsRE = nos.GetGroup(1, Tags.NoTradingSessions); - Assert.That(noTradingSessionsRE.GetString(336), Is.EqualTo("OHHAI")); - - var nos2 = new QuickFix.FIX42.NewOrderSingle(); - var grp = new Group(200, 300); - grp.SetField(new StringField(300, "Dude")); - nos2.AddGroup(grp); - Assert.That(nos2.GetGroup(1, 200).GetString(300), Is.EqualTo("Dude")); - } + Assert.That(msg.Trailer.RepeatedTags.Count, Is.EqualTo(1)); + Assert.That(msg.Trailer.RepeatedTags[0].Tag, Is.EqualTo(10)); - [Test] - public void RepeatingGroupParseGroupTest() { - string data = ("8=FIX.4.4|9=309|35=8|49=ASX|56=CL1_FIX44|34=4|52=20060324-01:05:58|" - + "17=X-B-WOW-1494E9A0:58BD3F9D-1109|150=D|39=0|11=184271|38=200|198=1494E9A0:58BD3F9D|" - + "526=4324|37=B-WOW-1494E9A0:58BD3F9D|55=WOW|54=1|151=200|14=0|40=2|44=15|59=1|6=0|" - + "453=3|" - + "448=AAA35791|447=D|452=3|802=1|523=OHAI123|" - + "448=8|447=D|452=4|448=FIX11|447=D|452=36|" - + "60=20060320-03:34:29|10=169|").Replace('|', Message.SOH); - var msg = new QuickFix.FIX44.ExecutionReport(); - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - msg.FromString(data, false, dd, dd, _defaultMsgFactory); - - var grp = msg.GetGroup(1, Tags.NoPartyIDs); - Assert.That(grp.GetString(Tags.PartyID), Is.EqualTo("AAA35791")); - grp = msg.GetGroup(3, Tags.NoPartyIDs); - Assert.That(grp.GetString(Tags.PartyID), Is.EqualTo("FIX11")); - } + Assert.That(msg.RepeatedTags.Count, Is.EqualTo(1)); + Assert.That(msg.RepeatedTags[0].Tag, Is.EqualTo(1)); + } - [Test] - public void NestedRepeatingGroupParseGroupTest() { - String data = ("8=FIX.4.4|9=309|35=8|49=ASX|56=CL1_FIX44|34=4|52=20060324-01:05:58|" - + "17=X-B-WOW-1494E9A0:58BD3F9D-1109|150=D|39=0|11=184271|38=200|198=1494E9A0:58BD3F9D|" - + "526=4324|37=B-WOW-1494E9A0:58BD3F9D|55=WOW|54=1|151=200|14=0|40=2|44=15|59=1|6=0|" - + "453=3|" - + "448=AAA35791|447=D|452=3|802=1|523=OHAI123|" - + "448=8|447=D|452=4|" - + "448=FIX11|447=D|452=36|" - + "60=20060320-03:34:29|10=169|").Replace('|', Message.SOH); - var msg = new QuickFix.FIX44.ExecutionReport(); - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - msg.FromString(data, false, dd, dd, _defaultMsgFactory); - - var subGrp = msg.GetGroup(1, Tags.NoPartyIDs).GetGroup(1, Tags.NoPartySubIDs); - Assert.That(subGrp.GetString(Tags.PartySubID), Is.EqualTo("OHAI123")); - } + [Test] + public void AddGroupGetGroupTest() + { + var nos = new QuickFix.FIX42.NewOrderSingle(); + var noTradingSessions = new QuickFix.FIX42.NewOrderSingle.NoTradingSessionsGroup(); + noTradingSessions.SetField(new StringField(336, "OHHAI")); + nos.AddGroup(noTradingSessions); + var noTradingSessionsRE = nos.GetGroup(1, Tags.NoTradingSessions); + Assert.That(noTradingSessionsRE.GetString(336), Is.EqualTo("OHHAI")); + + var nos2 = new QuickFix.FIX42.NewOrderSingle(); + var grp = new Group(200, 300); + grp.SetField(new StringField(300, "Dude")); + nos2.AddGroup(grp); + Assert.That(nos2.GetGroup(1, 200).GetString(300), Is.EqualTo("Dude")); + } - [Test] - public void ReadXmlDataTest() { - // Use tag 212/XmlDataLen to properly read 213/XmlData - - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX42"); - - QuickFix.FIX42.NewOrderSingle n = new QuickFix.FIX42.NewOrderSingle(); - - string s = ("8=FIX.4.2|9=495|35=n|34=31420|369=1003|" - + "52=20200701-20:34:33.978|49=CME|50=84|" - + "56=DUMMY11|57=SID1|143=US,IL|212=392|" - + "213=8=FIX.4.2|9=356|35=8|34=36027|" - + "369=18623|52=20200701-20:34:33.977|49=CME|50=84|" - + "56=M2L000N|57=DUMMY|143=US,IL|1=00331|" - + "6=0|11=ACP1593635673935|14=0|17=84618:1342652|20=0|" - + "37=84778833500|38=10|39=0|40=2|" - + "41=0|44=139.203125|48=204527|54=1|55=ZN|" - + "59=0|60=20200701-20:34:33.976|107=ZNH1|150=0|" - + "151=10|167=FUT|432=20200701|1028=Y|1031=Y|" - + "5979=1593635673976364291|9717=ACP1593635673935|10=124||" - + "10=028|").Replace('|', Message.SOH); - - n.FromString(s, true, dd, dd, _defaultMsgFactory); - - //verify that the data field was read correctly - Assert.That(n.Header.GetString(213).Length, Is.EqualTo(n.Header.GetInt(212))); - } + [Test] + public void RepeatingGroupParseGroupTest() { + string data = ("8=FIX.4.4|9=309|35=8|49=ASX|56=CL1_FIX44|34=4|52=20060324-01:05:58|" + + "17=X-B-WOW-1494E9A0:58BD3F9D-1109|150=D|39=0|11=184271|38=200|198=1494E9A0:58BD3F9D|" + + "526=4324|37=B-WOW-1494E9A0:58BD3F9D|55=WOW|54=1|151=200|14=0|40=2|44=15|59=1|6=0|" + + "453=3|" + + "448=AAA35791|447=D|452=3|802=1|523=OHAI123|" + + "448=8|447=D|452=4|448=FIX11|447=D|452=36|" + + "60=20060320-03:34:29|10=169|").Replace('|', Message.SOH); + var msg = new QuickFix.FIX44.ExecutionReport(); + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + msg.FromString(data, false, dd, dd, _defaultMsgFactory); + + var grp = msg.GetGroup(1, Tags.NoPartyIDs); + Assert.That(grp.GetString(Tags.PartyID), Is.EqualTo("AAA35791")); + grp = msg.GetGroup(3, Tags.NoPartyIDs); + Assert.That(grp.GetString(Tags.PartyID), Is.EqualTo("FIX11")); + } - [Test] - public void XmlDataWithoutLengthTest() { - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX42"); + [Test] + public void NestedRepeatingGroupParseGroupTest() { + String data = ("8=FIX.4.4|9=309|35=8|49=ASX|56=CL1_FIX44|34=4|52=20060324-01:05:58|" + + "17=X-B-WOW-1494E9A0:58BD3F9D-1109|150=D|39=0|11=184271|38=200|198=1494E9A0:58BD3F9D|" + + "526=4324|37=B-WOW-1494E9A0:58BD3F9D|55=WOW|54=1|151=200|14=0|40=2|44=15|59=1|6=0|" + + "453=3|" + + "448=AAA35791|447=D|452=3|802=1|523=OHAI123|" + + "448=8|447=D|452=4|" + + "448=FIX11|447=D|452=36|" + + "60=20060320-03:34:29|10=169|").Replace('|', Message.SOH); + var msg = new QuickFix.FIX44.ExecutionReport(); + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + msg.FromString(data, false, dd, dd, _defaultMsgFactory); + + var subGrp = msg.GetGroup(1, Tags.NoPartyIDs).GetGroup(1, Tags.NoPartySubIDs); + Assert.That(subGrp.GetString(Tags.PartySubID), Is.EqualTo("OHAI123")); + } - QuickFix.FIX42.NewOrderSingle n = new QuickFix.FIX42.NewOrderSingle(); + [Test] + public void ReadXmlDataTest() { + // Use tag 212/XmlDataLen to properly read 213/XmlData + + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX42"); + + QuickFix.FIX42.NewOrderSingle n = new QuickFix.FIX42.NewOrderSingle(); + + string s = ("8=FIX.4.2|9=495|35=n|34=31420|369=1003|" + + "52=20200701-20:34:33.978|49=CME|50=84|" + + "56=DUMMY11|57=SID1|143=US,IL|212=392|" + + "213=8=FIX.4.2|9=356|35=8|34=36027|" + + "369=18623|52=20200701-20:34:33.977|49=CME|50=84|" + + "56=M2L000N|57=DUMMY|143=US,IL|1=00331|" + + "6=0|11=ACP1593635673935|14=0|17=84618:1342652|20=0|" + + "37=84778833500|38=10|39=0|40=2|" + + "41=0|44=139.203125|48=204527|54=1|55=ZN|" + + "59=0|60=20200701-20:34:33.976|107=ZNH1|150=0|" + + "151=10|167=FUT|432=20200701|1028=Y|1031=Y|" + + "5979=1593635673976364291|9717=ACP1593635673935|10=124||" + + "10=028|").Replace('|', Message.SOH); + + n.FromString(s, true, dd, dd, _defaultMsgFactory); + + //verify that the data field was read correctly + Assert.That(n.Header.GetString(213).Length, Is.EqualTo(n.Header.GetInt(212))); + } - string s = ("8=FIX.4.2|9=495|35=n|34=31420|369=1003|" - + "52=20200701-20:34:33.978|49=CME|50=84|" - + "56=DUMMY11|57=SID1|143=US,IL|" - + "213=oops my length field 212 is missing|" - + "10=028|").Replace('|', Message.SOH); + [Test] + public void XmlDataWithoutLengthTest() { + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX42"); - FieldNotFoundException ex = - Assert.Throws(delegate { n.FromString(s, true, dd, dd, _defaultMsgFactory); })!; - Assert.That(ex.Message, Is.EqualTo("field not found for tag: 212")); - } + QuickFix.FIX42.NewOrderSingle n = new QuickFix.FIX42.NewOrderSingle(); - [Test] - public void HeaderGroupParsingTest() - { - string data = "8=FIX.4.4|9=40|35=A|627=2|628=FOO|628=BAR|98=0|384=2|372=D|385=R|372=8|385=S|10=228|" - .Replace('|', Message.SOH); - - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - var nos = new QuickFix.FIX44.Logon(); - nos.FromString(data, false, dd, dd, _defaultMsgFactory); - Group hops = nos.Header.GetGroup(1, Tags.NoHops); - Assert.That(hops.GetString(Tags.HopCompID), Is.EqualTo("FOO")); - hops = nos.Header.GetGroup(2, Tags.NoHops); - Assert.That(hops.GetString(Tags.HopCompID), Is.EqualTo("BAR")); - } + string s = ("8=FIX.4.2|9=495|35=n|34=31420|369=1003|" + + "52=20200701-20:34:33.978|49=CME|50=84|" + + "56=DUMMY11|57=SID1|143=US,IL|" + + "213=oops my length field 212 is missing|" + + "10=028|").Replace('|', Message.SOH); - [Test] - public void TempExtraLogoutField() - { - string data = "8=FIX.4.4|9=40|35=5|58=this is a logout|789=100|10=228|" - .Replace('|', Message.SOH); - - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - var logout = new QuickFix.FIX44.Logout(); - logout.FromString(data, false, dd, dd, _defaultMsgFactory); - Assert.That(logout.GetInt(Tags.NextExpectedMsgSeqNum), Is.EqualTo(100)); - } + FieldNotFoundException ex = + Assert.Throws(delegate { n.FromString(s, true, dd, dd, _defaultMsgFactory); })!; + Assert.That(ex.Message, Is.EqualTo("field not found for tag: 212")); + } - [Test] - public void TempExtraLogoutFieldFIX42() - { - string data = "8=FIX.4.2|9=40|35=5|58=this is a logout|789=100|10=228|" - .Replace('|', Message.SOH); - - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX42"); - var logout = new QuickFix.FIX44.Logout(); - logout.FromString(data, false, dd, dd, _defaultMsgFactory); - Assert.That(logout.GetInt(Tags.NextExpectedMsgSeqNum), Is.EqualTo(100)); - } + [Test] + public void HeaderGroupParsingTest() + { + string data = "8=FIX.4.4|9=40|35=A|627=2|628=FOO|628=BAR|98=0|384=2|372=D|385=R|372=8|385=S|10=228|" + .Replace('|', Message.SOH); + + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + var nos = new QuickFix.FIX44.Logon(); + nos.FromString(data, false, dd, dd, _defaultMsgFactory); + Group hops = nos.Header.GetGroup(1, Tags.NoHops); + Assert.That(hops.GetString(Tags.HopCompID), Is.EqualTo("FOO")); + hops = nos.Header.GetGroup(2, Tags.NoHops); + Assert.That(hops.GetString(Tags.HopCompID), Is.EqualTo("BAR")); + } - [Test] - public void MsgType() - { - Assert.That(QuickFix.FIX42.News.MsgType, Is.EqualTo("B")); - } + [Test] + public void TempExtraLogoutField() + { + string data = "8=FIX.4.4|9=40|35=5|58=this is a logout|789=100|10=228|" + .Replace('|', Message.SOH); + + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + var logout = new QuickFix.FIX44.Logout(); + logout.FromString(data, false, dd, dd, _defaultMsgFactory); + Assert.That(logout.GetInt(Tags.NextExpectedMsgSeqNum), Is.EqualTo(100)); + } - [Test] - public void ExtractBeginString() - { - string m1 = "8=FIX4.2|9999=99999|".Replace('|', Message.SOH);; - string m2 = "987=pants|xxxxxxxxxxxxxxxxxxxxxx".Replace('|', Message.SOH);; + [Test] + public void TempExtraLogoutFieldFIX42() + { + string data = "8=FIX.4.2|9=40|35=5|58=this is a logout|789=100|10=228|" + .Replace('|', Message.SOH); + + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX42"); + var logout = new QuickFix.FIX44.Logout(); + logout.FromString(data, false, dd, dd, _defaultMsgFactory); + Assert.That(logout.GetInt(Tags.NextExpectedMsgSeqNum), Is.EqualTo(100)); + } - Assert.That(Message.ExtractBeginString(m1), Is.EqualTo("FIX4.2")); - Assert.That(Message.ExtractBeginString(m2), Is.EqualTo("pants")); - } + [Test] + public void MsgType() + { + Assert.That(QuickFix.FIX42.News.MsgType, Is.EqualTo("B")); + } - [Test] - public void ExtractFieldTypes() - { - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX42"); - - QuickFix.FIX42.NewOrderSingle n = new QuickFix.FIX42.NewOrderSingle(); - - string s = ("8=FIX.4.2|9=137|35=D|34=3|49=CLIENT1|" - + "52=20110901-18:41:56.917|56=EXECUTOR|11=asdf|21=1|" - + "38=5.5|40=1|54=1|55=ibm|59=1|60=20110901-13:41:31.804|" - + "377=Y|201=1|" - + "10=63|").Replace('|', Message.SOH); - n.FromString(s, true, dd, dd, _defaultMsgFactory); - - // string values are good? - Assert.That(n.SolicitedFlag.ToString(), Is.EqualTo("Y")); //bool, 377 - Assert.That(n.Side.ToString(), Is.EqualTo("1")); //char, 54 - Assert.That(n.TransactTime.ToString(), Is.EqualTo("20110901-13:41:31.804")); //datetime, 60 - Assert.That(n.OrderQty.ToString(), Is.EqualTo("5.5")); //decimal, 38 - Assert.That(n.PutOrCall.ToString(), Is.EqualTo("1")); //int, 201 - Assert.That(n.ClOrdID.ToString(), Is.EqualTo("asdf")); //string, 11 - - // type-converted values are good? - Assert.That(n.SolicitedFlag.Value, Is.EqualTo(true)); - Assert.That(n.Side.Value, Is.EqualTo('1')); - Assert.That(n.TransactTime.Value, Is.EqualTo(DateTime.Parse("2011-09-01 13:41:31.804"))); - Assert.That(n.OrderQty.Value, Is.EqualTo(5.5m)); - Assert.That(n.PutOrCall.Value, Is.EqualTo(1)); - Assert.That(n.ClOrdID.Value, Is.EqualTo("asdf")); - } + [Test] + public void ExtractBeginString() + { + string m1 = "8=FIX4.2|9999=99999|".Replace('|', Message.SOH);; + string m2 = "987=pants|xxxxxxxxxxxxxxxxxxxxxx".Replace('|', Message.SOH);; - [Test] - public void ExtractFieldTest() - { - string msgstr = "100=200|300=400|500=600|".Replace('|', Message.SOH); - int n = 0; + Assert.That(Message.ExtractBeginString(m1), Is.EqualTo("FIX4.2")); + Assert.That(Message.ExtractBeginString(m2), Is.EqualTo("pants")); + } - var x = QuickFix.Message.ExtractField(msgstr, ref n); - Assert.That(n, Is.EqualTo(8)); - Assert.That(x.ToStringField(), Is.EqualTo("100=200")); + [Test] + public void ExtractFieldTypes() + { + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX42"); + + QuickFix.FIX42.NewOrderSingle n = new QuickFix.FIX42.NewOrderSingle(); + + string s = ("8=FIX.4.2|9=137|35=D|34=3|49=CLIENT1|" + + "52=20110901-18:41:56.917|56=EXECUTOR|11=asdf|21=1|" + + "38=5.5|40=1|54=1|55=ibm|59=1|60=20110901-13:41:31.804|" + + "377=Y|201=1|" + + "10=63|").Replace('|', Message.SOH); + n.FromString(s, true, dd, dd, _defaultMsgFactory); + + // string values are good? + Assert.That(n.SolicitedFlag.ToString(), Is.EqualTo("Y")); //bool, 377 + Assert.That(n.Side.ToString(), Is.EqualTo("1")); //char, 54 + Assert.That(n.TransactTime.ToString(), Is.EqualTo("20110901-13:41:31.804")); //datetime, 60 + Assert.That(n.OrderQty.ToString(), Is.EqualTo("5.5")); //decimal, 38 + Assert.That(n.PutOrCall.ToString(), Is.EqualTo("1")); //int, 201 + Assert.That(n.ClOrdID.ToString(), Is.EqualTo("asdf")); //string, 11 + + // type-converted values are good? + Assert.That(n.SolicitedFlag.Value, Is.EqualTo(true)); + Assert.That(n.Side.Value, Is.EqualTo('1')); + Assert.That(n.TransactTime.Value, Is.EqualTo(DateTime.Parse("2011-09-01 13:41:31.804"))); + Assert.That(n.OrderQty.Value, Is.EqualTo(5.5m)); + Assert.That(n.PutOrCall.Value, Is.EqualTo(1)); + Assert.That(n.ClOrdID.Value, Is.EqualTo("asdf")); + } - x = QuickFix.Message.ExtractField(msgstr, ref n); - Assert.That(n, Is.EqualTo(16)); - Assert.That(x.ToStringField(), Is.EqualTo("300=400")); + [Test] + public void ExtractFieldTest() + { + string msgstr = "100=200|300=400|500=600|".Replace('|', Message.SOH); + int n = 0; - x = QuickFix.Message.ExtractField(msgstr, ref n); - Assert.That(n, Is.EqualTo(24)); - Assert.That(x.ToStringField(), Is.EqualTo("500=600")); - } + var x = QuickFix.Message.ExtractField(msgstr, ref n); + Assert.That(n, Is.EqualTo(8)); + Assert.That(x.ToStringField(), Is.EqualTo("100=200")); - [Test] - public void RepeatingGroup() - { - QuickFix.DataDictionary.DataDictionary dd = new(); - dd.LoadFIXSpec("FIX42"); + x = QuickFix.Message.ExtractField(msgstr, ref n); + Assert.That(n, Is.EqualTo(16)); + Assert.That(x.ToStringField(), Is.EqualTo("300=400")); - QuickFix.FIX42.News news = new QuickFix.FIX42.News(new Headline("Foo headline")); + x = QuickFix.Message.ExtractField(msgstr, ref n); + Assert.That(n, Is.EqualTo(24)); + Assert.That(x.ToStringField(), Is.EqualTo("500=600")); + } - QuickFix.FIX42.News.LinesOfTextGroup group1 = new(); - group1.Text = new Text("line1"); - group1.EncodedTextLen = new EncodedTextLen(3); - group1.EncodedText = new EncodedText("aaa"); - news.AddGroup(group1); + [Test] + public void RepeatingGroup() + { + QuickFix.DataDictionary.DataDictionary dd = new(); + dd.LoadFIXSpec("FIX42"); - QuickFix.FIX42.News.LinesOfTextGroup group2 = new(); - group2.Text = new Text("line2"); - group2.EncodedText = new EncodedText("bbb"); - news.AddGroup(group2); + QuickFix.FIX42.News news = new QuickFix.FIX42.News(new Headline("Foo headline")); - string raw = news.ConstructString(); + QuickFix.FIX42.News.LinesOfTextGroup group1 = new(); + group1.Text = new Text("line1"); + group1.EncodedTextLen = new EncodedTextLen(3); + group1.EncodedText = new EncodedText("aaa"); + news.AddGroup(group1); - Assert.That(raw.Replace(Message.SOH, '|'), Does.Contain("33=2|58=line1|354=3|355=aaa|58=line2|355=bbb|")); - } + QuickFix.FIX42.News.LinesOfTextGroup group2 = new(); + group2.Text = new Text("line2"); + group2.EncodedText = new EncodedText("bbb"); + news.AddGroup(group2); - [Test] - public void RepeatingGroup_ReuseObject() - { - QuickFix.DataDictionary.DataDictionary dd = new(); - dd.LoadFIXSpec("FIX42"); + string raw = news.ConstructString(); - QuickFix.FIX42.News news = new QuickFix.FIX42.News(new Headline("Foo headline")); + Assert.That(raw.Replace(Message.SOH, '|'), Does.Contain("33=2|58=line1|354=3|355=aaa|58=line2|355=bbb|")); + } - QuickFix.FIX42.News.LinesOfTextGroup group = new(); - group.Text = new Text("line1"); - news.AddGroup(group); - group.Text = new Text("line2"); - news.AddGroup(group); + [Test] + public void RepeatingGroup_ReuseObject() + { + QuickFix.DataDictionary.DataDictionary dd = new(); + dd.LoadFIXSpec("FIX42"); - string raw = news.ConstructString(); - Assert.That(raw.Replace(Message.SOH, '|'), Does.Contain("|33=2|58=line1|58=line2|")); - } + QuickFix.FIX42.News news = new QuickFix.FIX42.News(new Headline("Foo headline")); - [Test] - public void ReverseRoute() - { - string str1 = "8=FIX.4.2|9=55|35=0|34=3|49=TW|52=20000426-12:05:06|56=ISLD|1=acct123|10=123|" - .Replace('|', Message.SOH); + QuickFix.FIX42.News.LinesOfTextGroup group = new(); + group.Text = new Text("line1"); + news.AddGroup(group); + group.Text = new Text("line2"); + news.AddGroup(group); - Message msg = new Message(); - try - { - msg.FromString(str1, true, null, null, _defaultMsgFactory); - } - catch (InvalidMessage e) - { - Assert.Fail("Unexpected exception (InvalidMessage): " + e.Message); - } - Header header = new Header(); - header.SetField(new BeginString("FIX.4.2")); - header.SetField(new SenderCompID("SENDER")); - header.SetField(new SenderSubID("SENDERSUB")); - header.SetField(new SenderLocationID("SENDERLOC")); - header.SetField(new TargetCompID("TARGET")); - header.SetField(new TargetSubID("TARGETSUB")); - header.SetField(new TargetLocationID("TARGETLOC")); - - msg.ReverseRoute(header); - - Assert.That(msg.Header.GetString(Tags.BeginString), Is.EqualTo("FIX.4.2")); - Assert.That(msg.Header.GetString(Tags.TargetCompID), Is.EqualTo("SENDER")); - Assert.That(msg.Header.GetString(Tags.TargetSubID), Is.EqualTo("SENDERSUB")); - Assert.That(msg.Header.GetString(Tags.TargetLocationID), Is.EqualTo("SENDERLOC")); - Assert.That(msg.Header.GetString(Tags.SenderCompID), Is.EqualTo("TARGET")); - Assert.That(msg.Header.GetString(Tags.SenderSubID), Is.EqualTo("TARGETSUB")); - Assert.That(msg.Header.GetString(Tags.SenderLocationID), Is.EqualTo("TARGETLOC")); - } + string raw = news.ConstructString(); + Assert.That(raw.Replace(Message.SOH, '|'), Does.Contain("|33=2|58=line1|58=line2|")); + } - [Test] - public void TestGetSetSessionId() - { - SessionID sessionId = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "SENDERLOC", "TARGET", "TARGETSUB", "TARGETLOC"); - Message msg = new Message(); - - msg.SetSessionID(sessionId); - - Assert.That(msg.Header.GetString(Tags.BeginString), Is.EqualTo("FIX.4.2")); - Assert.That(msg.Header.GetString(Tags.SenderCompID), Is.EqualTo("SENDER")); - Assert.That(msg.Header.GetString(Tags.SenderSubID), Is.EqualTo("SENDERSUB")); - Assert.That(msg.Header.GetString(Tags.SenderLocationID), Is.EqualTo("SENDERLOC")); - Assert.That(msg.Header.GetString(Tags.TargetCompID), Is.EqualTo("TARGET")); - Assert.That(msg.Header.GetString(Tags.TargetSubID), Is.EqualTo("TARGETSUB")); - Assert.That(msg.Header.GetString(Tags.TargetLocationID), Is.EqualTo("TARGETLOC")); - - SessionID getSessionId = msg.GetSessionID(msg); - Assert.That(getSessionId.BeginString, Is.EqualTo("FIX.4.2")); - Assert.That(getSessionId.SenderCompID, Is.EqualTo("SENDER")); - Assert.That(getSessionId.SenderSubID, Is.EqualTo("SENDERSUB")); - Assert.That(getSessionId.SenderLocationID, Is.EqualTo("SENDERLOC")); - Assert.That(getSessionId.TargetCompID, Is.EqualTo("TARGET")); - Assert.That(getSessionId.TargetSubID, Is.EqualTo("TARGETSUB")); - Assert.That(getSessionId.TargetLocationID, Is.EqualTo("TARGETLOC")); - - //// - sessionId = new SessionID("FIX.4.2", "SENDER", "TARGET"); - msg = new Message(); - - msg.SetSessionID(sessionId); - - Assert.That(msg.Header.GetString(Tags.BeginString), Is.EqualTo("FIX.4.2")); - Assert.That(msg.Header.GetString(Tags.SenderCompID), Is.EqualTo("SENDER")); - Assert.That(msg.Header.IsSetField(Tags.SenderSubID), Is.False); - Assert.That(msg.Header.IsSetField(Tags.SenderLocationID), Is.False); - Assert.That(msg.Header.GetString(Tags.TargetCompID), Is.EqualTo("TARGET")); - Assert.That(msg.Header.IsSetField(Tags.TargetSubID), Is.False); - Assert.That(msg.Header.IsSetField(Tags.TargetLocationID), Is.False); - - getSessionId = msg.GetSessionID(msg); - Assert.That(getSessionId.BeginString, Is.EqualTo("FIX.4.2")); - Assert.That(getSessionId.SenderCompID, Is.EqualTo("SENDER")); - Assert.That(getSessionId.SenderSubID, Is.EqualTo("")); - Assert.That(getSessionId.SenderLocationID, Is.EqualTo("")); - Assert.That(getSessionId.TargetCompID, Is.EqualTo("TARGET")); - Assert.That(getSessionId.TargetSubID, Is.EqualTo("")); - Assert.That(getSessionId.TargetLocationID, Is.EqualTo("")); - } + [Test] + public void ReverseRoute() + { + string str1 = "8=FIX.4.2|9=55|35=0|34=3|49=TW|52=20000426-12:05:06|56=ISLD|1=acct123|10=123|" + .Replace('|', Message.SOH); - [TestCase("8=FIX.4.4|9=104|35=W|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=1|269=0|272=20111012|273=22:15:30.444|10=19|", "W")] - [TestCase("8=FIX.4.4|9=104|35=AW|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=1|269=0|272=20111012|273=22:15:30.444|10=19|", "AW")] - [TestCase("8=FIX.4.4|9=68|35=*|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=0|10=9|", "*")] - public void GetMsgTypeTest(string message, string expectedMessageType) + Message msg = new Message(); + try { - var msgStr = message.Replace('|', Message.SOH); - Assert.That(Message.GetMsgType(msgStr), Is.EqualTo(expectedMessageType)); + msg.FromString(str1, true, null, null, _defaultMsgFactory); } - - [TestCase("")] - [TestCase("8=FIX.4.4|9=68|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=0|10=9|")] - [TestCase("8=FIX.4.4|9=68|35=|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=0|10=9|")] - [TestCase("8=FIX.4.4|9=68|35=")] - public void GetInvalidMsgTypeTest(string message) + catch (InvalidMessage e) { - var msgStr = message.Replace('|', Message.SOH); - Assert.Throws(() => Message.GetMsgType(msgStr)); + Assert.Fail("Unexpected exception (InvalidMessage): " + e.Message); } + Header header = new Header(); + header.SetField(new BeginString("FIX.4.2")); + header.SetField(new SenderCompID("SENDER")); + header.SetField(new SenderSubID("SENDERSUB")); + header.SetField(new SenderLocationID("SENDERLOC")); + header.SetField(new TargetCompID("TARGET")); + header.SetField(new TargetSubID("TARGETSUB")); + header.SetField(new TargetLocationID("TARGETLOC")); + + msg.ReverseRoute(header); + + Assert.That(msg.Header.GetString(Tags.BeginString), Is.EqualTo("FIX.4.2")); + Assert.That(msg.Header.GetString(Tags.TargetCompID), Is.EqualTo("SENDER")); + Assert.That(msg.Header.GetString(Tags.TargetSubID), Is.EqualTo("SENDERSUB")); + Assert.That(msg.Header.GetString(Tags.TargetLocationID), Is.EqualTo("SENDERLOC")); + Assert.That(msg.Header.GetString(Tags.SenderCompID), Is.EqualTo("TARGET")); + Assert.That(msg.Header.GetString(Tags.SenderSubID), Is.EqualTo("TARGETSUB")); + Assert.That(msg.Header.GetString(Tags.SenderLocationID), Is.EqualTo("TARGETLOC")); + } - [Test] - public void RepeatingGroup_DelimiterFieldFirst() - { - QuickFix.FIX44.MarketDataRequest msg = new(); - msg.MDReqID = new MDReqID("fooMdReqID"); - msg.SubscriptionRequestType = new SubscriptionRequestType('1'); - msg.MarketDepth = new MarketDepth(0); - - // this group is irrelevant to the test, but it's required in the message - QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup entryTypesGroup = new(); - entryTypesGroup.MDEntryType = new MDEntryType('0'); - msg.AddGroup(entryTypesGroup); - entryTypesGroup.MDEntryType = new MDEntryType('1'); - msg.AddGroup(entryTypesGroup); - - QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symGroup = new(); - symGroup.Symbol = new Symbol("FOO1"); - symGroup.SecurityID = new SecurityID("secid1"); - msg.AddGroup(symGroup); - symGroup.Symbol = new Symbol("FOO2"); - symGroup.SecurityID = new SecurityID("secid2"); - msg.AddGroup(symGroup); - - string msgString = msg.ConstructString(); - string expected = "146=2|55=FOO1|48=secid1|55=FOO2|48=secid2|".Replace('|', Message.SOH); - - Assert.That(msgString, Does.Contain(expected)); - } + [Test] + public void TestGetSetSessionId() + { + SessionID sessionId = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "SENDERLOC", "TARGET", "TARGETSUB", "TARGETLOC"); + Message msg = new Message(); + + msg.SetSessionID(sessionId); + + Assert.That(msg.Header.GetString(Tags.BeginString), Is.EqualTo("FIX.4.2")); + Assert.That(msg.Header.GetString(Tags.SenderCompID), Is.EqualTo("SENDER")); + Assert.That(msg.Header.GetString(Tags.SenderSubID), Is.EqualTo("SENDERSUB")); + Assert.That(msg.Header.GetString(Tags.SenderLocationID), Is.EqualTo("SENDERLOC")); + Assert.That(msg.Header.GetString(Tags.TargetCompID), Is.EqualTo("TARGET")); + Assert.That(msg.Header.GetString(Tags.TargetSubID), Is.EqualTo("TARGETSUB")); + Assert.That(msg.Header.GetString(Tags.TargetLocationID), Is.EqualTo("TARGETLOC")); + + SessionID getSessionId = msg.GetSessionID(msg); + Assert.That(getSessionId.BeginString, Is.EqualTo("FIX.4.2")); + Assert.That(getSessionId.SenderCompID, Is.EqualTo("SENDER")); + Assert.That(getSessionId.SenderSubID, Is.EqualTo("SENDERSUB")); + Assert.That(getSessionId.SenderLocationID, Is.EqualTo("SENDERLOC")); + Assert.That(getSessionId.TargetCompID, Is.EqualTo("TARGET")); + Assert.That(getSessionId.TargetSubID, Is.EqualTo("TARGETSUB")); + Assert.That(getSessionId.TargetLocationID, Is.EqualTo("TARGETLOC")); + + //// + sessionId = new SessionID("FIX.4.2", "SENDER", "TARGET"); + msg = new Message(); + + msg.SetSessionID(sessionId); + + Assert.That(msg.Header.GetString(Tags.BeginString), Is.EqualTo("FIX.4.2")); + Assert.That(msg.Header.GetString(Tags.SenderCompID), Is.EqualTo("SENDER")); + Assert.That(msg.Header.IsSetField(Tags.SenderSubID), Is.False); + Assert.That(msg.Header.IsSetField(Tags.SenderLocationID), Is.False); + Assert.That(msg.Header.GetString(Tags.TargetCompID), Is.EqualTo("TARGET")); + Assert.That(msg.Header.IsSetField(Tags.TargetSubID), Is.False); + Assert.That(msg.Header.IsSetField(Tags.TargetLocationID), Is.False); + + getSessionId = msg.GetSessionID(msg); + Assert.That(getSessionId.BeginString, Is.EqualTo("FIX.4.2")); + Assert.That(getSessionId.SenderCompID, Is.EqualTo("SENDER")); + Assert.That(getSessionId.SenderSubID, Is.EqualTo("")); + Assert.That(getSessionId.SenderLocationID, Is.EqualTo("")); + Assert.That(getSessionId.TargetCompID, Is.EqualTo("TARGET")); + Assert.That(getSessionId.TargetSubID, Is.EqualTo("")); + Assert.That(getSessionId.TargetLocationID, Is.EqualTo("")); + } - [Test] - public void RepeatingGroup_FieldOrder() - { - QuickFix.FIX44.MarketDataRequest msg = new(); - msg.MDReqID = new MDReqID("fooMdReqID"); - msg.SubscriptionRequestType = new SubscriptionRequestType('1'); - msg.MarketDepth = new MarketDepth(0); - - // this group is irrelevant to the test, but it's required in the message - QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup entryTypesGroup = new(); - entryTypesGroup.MDEntryType = new MDEntryType('0'); - msg.AddGroup(entryTypesGroup); - entryTypesGroup.MDEntryType = new MDEntryType('1'); - msg.AddGroup(entryTypesGroup); - - QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symGroup = new(); - // spec order of fields is 55,65,48,22 - symGroup.Symbol = new Symbol("FOO1"); - symGroup.SymbolSfx = new SymbolSfx("sfx1"); - symGroup.SecurityID = new SecurityID("secid1"); - symGroup.SecurityIDSource = new SecurityIDSource("src1"); - msg.AddGroup(symGroup); - symGroup.Symbol = new Symbol("FOO2"); - symGroup.SymbolSfx = new SymbolSfx("sfx2"); - symGroup.SecurityID = new SecurityID("secid2"); - symGroup.SecurityIDSource = new SecurityIDSource("src2"); - msg.AddGroup(symGroup); - - string msgString = msg.ConstructString(); - string expected = "146=2|55=FOO1|65=sfx1|48=secid1|22=src1|55=FOO2|65=sfx2|48=secid2|22=src2|" - .Replace('|', Message.SOH); - - Assert.That(msgString, Does.Contain(expected)); - } + [TestCase("8=FIX.4.4|9=104|35=W|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=1|269=0|272=20111012|273=22:15:30.444|10=19|", "W")] + [TestCase("8=FIX.4.4|9=104|35=AW|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=1|269=0|272=20111012|273=22:15:30.444|10=19|", "AW")] + [TestCase("8=FIX.4.4|9=68|35=*|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=0|10=9|", "*")] + public void GetMsgTypeTest(string message, string expectedMessageType) + { + var msgStr = message.Replace('|', Message.SOH); + Assert.That(Message.GetMsgType(msgStr), Is.EqualTo(expectedMessageType)); + } - [Test] - public void ConstructString_FIX50() - { - QuickFix.FIX50.News msg = new(); - msg.Headline = new Headline("FOO"); + [TestCase("")] + [TestCase("8=FIX.4.4|9=68|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=0|10=9|")] + [TestCase("8=FIX.4.4|9=68|35=|34=3|49=sender|52=20110909-09:09:09.999|56=target|55=sym|268=0|10=9|")] + [TestCase("8=FIX.4.4|9=68|35=")] + public void GetInvalidMsgTypeTest(string message) + { + var msgStr = message.Replace('|', Message.SOH); + Assert.Throws(() => Message.GetMsgType(msgStr)); + } - Assert.That(msg.ConstructString(), Does.StartWith("8=FIXT.1.1" + Message.SOH)); - } + [Test] + public void RepeatingGroup_DelimiterFieldFirst() + { + QuickFix.FIX44.MarketDataRequest msg = new(); + msg.MDReqID = new MDReqID("fooMdReqID"); + msg.SubscriptionRequestType = new SubscriptionRequestType('1'); + msg.MarketDepth = new MarketDepth(0); + + // this group is irrelevant to the test, but it's required in the message + QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup entryTypesGroup = new(); + entryTypesGroup.MDEntryType = new MDEntryType('0'); + msg.AddGroup(entryTypesGroup); + entryTypesGroup.MDEntryType = new MDEntryType('1'); + msg.AddGroup(entryTypesGroup); + + QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symGroup = new(); + symGroup.Symbol = new Symbol("FOO1"); + symGroup.SecurityID = new SecurityID("secid1"); + msg.AddGroup(symGroup); + symGroup.Symbol = new Symbol("FOO2"); + symGroup.SecurityID = new SecurityID("secid2"); + msg.AddGroup(symGroup); + + string msgString = msg.ConstructString(); + string expected = "146=2|55=FOO1|48=secid1|55=FOO2|48=secid2|".Replace('|', Message.SOH); + + Assert.That(msgString, Does.Contain(expected)); + } - [Test] - public void RepeatingGroup_SubgroupCounterTagAppearsOnlyOnce() - { - // issue #11 bug, as reported by karabiberoglu's further-down post - - QuickFix.FIX44.CollateralInquiry ci = new(); - ci.CollInquiryID = new CollInquiryID("CollateralInquiry"); - - // group - QuickFix.FIX44.CollateralInquiry.NoPartyIDsGroup noParty = new(); - noParty.PartyID = new PartyID("ABC"); - noParty.PartyIDSource = new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE); - noParty.PartyRole = new PartyRole(PartyRole.CLEARING_FIRM); - - // group in group - QuickFix.FIX44.CollateralInquiry.NoPartyIDsGroup.NoPartySubIDsGroup noPartySub = new(); - noPartySub.PartySubID = new PartySubID("subABC"); - noPartySub.PartySubIDType = new PartySubIDType(PartySubIDType.FIRM); - noParty.AddGroup(noPartySub); - noPartySub.PartySubID = new PartySubID("subDEF"); - noPartySub.PartySubIDType = new PartySubIDType(PartySubIDType.LOCATION); - noParty.AddGroup(noPartySub); - - ci.AddGroup(noParty); - - string msgString = ci.ConstructString(); - string expected = String.Join(Message.SOH, new string[] { - "909=CollateralInquiry", // top-level fields (non-header) - "453=1", //NoPartyIDs - "448=ABC","447=D","452=4", - "802=2", //NoPartySubIDs - "523=subABC","803=1", - "523=subDEF","803=31", - "10=" - }); - - //Console.WriteLine(ci.ToString()); - Assert.That(msgString, Does.Contain(expected)); - } + [Test] + public void RepeatingGroup_FieldOrder() + { + QuickFix.FIX44.MarketDataRequest msg = new(); + msg.MDReqID = new MDReqID("fooMdReqID"); + msg.SubscriptionRequestType = new SubscriptionRequestType('1'); + msg.MarketDepth = new MarketDepth(0); + + // this group is irrelevant to the test, but it's required in the message + QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup entryTypesGroup = new(); + entryTypesGroup.MDEntryType = new MDEntryType('0'); + msg.AddGroup(entryTypesGroup); + entryTypesGroup.MDEntryType = new MDEntryType('1'); + msg.AddGroup(entryTypesGroup); + + QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symGroup = new(); + // spec order of fields is 55,65,48,22 + symGroup.Symbol = new Symbol("FOO1"); + symGroup.SymbolSfx = new SymbolSfx("sfx1"); + symGroup.SecurityID = new SecurityID("secid1"); + symGroup.SecurityIDSource = new SecurityIDSource("src1"); + msg.AddGroup(symGroup); + symGroup.Symbol = new Symbol("FOO2"); + symGroup.SymbolSfx = new SymbolSfx("sfx2"); + symGroup.SecurityID = new SecurityID("secid2"); + symGroup.SecurityIDSource = new SecurityIDSource("src2"); + msg.AddGroup(symGroup); + + string msgString = msg.ConstructString(); + string expected = "146=2|55=FOO1|65=sfx1|48=secid1|22=src1|55=FOO2|65=sfx2|48=secid2|22=src2|" + .Replace('|', Message.SOH); + + Assert.That(msgString, Does.Contain(expected)); + } - [Test] - public void Issue56_GetGroup_by_tag_and_return() - { - // setup - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - - string msgStr = ("8=FIX.4.2|9=87|35=B|34=3|49=CLIENT1|52=20111012-22:15:55.474|56=EXECUTOR|" - + "148=AAAAAAA|33=2|58=L1|58=L2|10=016|").Replace('|', Message.SOH); - QuickFix.FIX42.News msg = new QuickFix.FIX42.News(); - msg.FromString(msgStr, false, dd, dd, _defaultMsgFactory); - Assert.That(msg.GroupCount(Tags.LinesOfText), Is.EqualTo(2)); // for sanity - - // the test - var grp1 = msg.GetGroup(1, Tags.LinesOfText); - Assert.That(grp1, Is.InstanceOf()); - Assert.That((grp1 as QuickFix.FIX42.News.LinesOfTextGroup)!.Text.Value, Is.EqualTo("L1")); - - var grp2 = msg.GetGroup(2, Tags.LinesOfText); - Assert.That(grp2, Is.InstanceOf()); - Assert.That((grp2 as QuickFix.FIX42.News.LinesOfTextGroup)!.Text.Value, Is.EqualTo("L2")); - } + [Test] + public void ConstructString_FIX50() + { + QuickFix.FIX50.News msg = new(); + msg.Headline = new Headline("FOO"); - [Test] - public void Issue56_GetGroup_by_reference() - { - // setup - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); + Assert.That(msg.ConstructString(), Does.StartWith("8=FIXT.1.1" + Message.SOH)); + } - string msgStr = ("8=FIX.4.2|9=87|35=B|34=3|49=CLIENT1|52=20111012-22:15:55.474|56=EXECUTOR|" - + "148=AAAAAAA|33=2|58=L1|58=L2|10=016|").Replace('|', Message.SOH); - QuickFix.FIX42.News msg = new QuickFix.FIX42.News(); - msg.FromString(msgStr, false, dd, dd, _defaultMsgFactory); - Assert.That(msg.GroupCount(Tags.LinesOfText), Is.EqualTo(2)); // for sanity + [Test] + public void RepeatingGroup_SubgroupCounterTagAppearsOnlyOnce() + { + // issue #11 bug, as reported by karabiberoglu's further-down post + + QuickFix.FIX44.CollateralInquiry ci = new(); + ci.CollInquiryID = new CollInquiryID("CollateralInquiry"); + + // group + QuickFix.FIX44.CollateralInquiry.NoPartyIDsGroup noParty = new(); + noParty.PartyID = new PartyID("ABC"); + noParty.PartyIDSource = new PartyIDSource(PartyIDSource.PROPRIETARY_CUSTOM_CODE); + noParty.PartyRole = new PartyRole(PartyRole.CLEARING_FIRM); + + // group in group + QuickFix.FIX44.CollateralInquiry.NoPartyIDsGroup.NoPartySubIDsGroup noPartySub = new(); + noPartySub.PartySubID = new PartySubID("subABC"); + noPartySub.PartySubIDType = new PartySubIDType(PartySubIDType.FIRM); + noParty.AddGroup(noPartySub); + noPartySub.PartySubID = new PartySubID("subDEF"); + noPartySub.PartySubIDType = new PartySubIDType(PartySubIDType.LOCATION); + noParty.AddGroup(noPartySub); + + ci.AddGroup(noParty); + + string msgString = ci.ConstructString(); + string expected = String.Join(Message.SOH, new string[] { + "909=CollateralInquiry", // top-level fields (non-header) + "453=1", //NoPartyIDs + "448=ABC","447=D","452=4", + "802=2", //NoPartySubIDs + "523=subABC","803=1", + "523=subDEF","803=31", + "10=" + }); + + //Console.WriteLine(ci.ToString()); + Assert.That(msgString, Does.Contain(expected)); + } - // the test - QuickFix.FIX42.News.LinesOfTextGroup grp = new QuickFix.FIX42.News.LinesOfTextGroup(); // for return value + [Test] + public void Issue56_GetGroup_by_tag_and_return() + { + // setup + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + + string msgStr = ("8=FIX.4.2|9=87|35=B|34=3|49=CLIENT1|52=20111012-22:15:55.474|56=EXECUTOR|" + + "148=AAAAAAA|33=2|58=L1|58=L2|10=016|").Replace('|', Message.SOH); + QuickFix.FIX42.News msg = new QuickFix.FIX42.News(); + msg.FromString(msgStr, false, dd, dd, _defaultMsgFactory); + Assert.That(msg.GroupCount(Tags.LinesOfText), Is.EqualTo(2)); // for sanity + + // the test + var grp1 = msg.GetGroup(1, Tags.LinesOfText); + Assert.That(grp1, Is.InstanceOf()); + Assert.That((grp1 as QuickFix.FIX42.News.LinesOfTextGroup)!.Text.Value, Is.EqualTo("L1")); + + var grp2 = msg.GetGroup(2, Tags.LinesOfText); + Assert.That(grp2, Is.InstanceOf()); + Assert.That((grp2 as QuickFix.FIX42.News.LinesOfTextGroup)!.Text.Value, Is.EqualTo("L2")); + } - msg.GetGroup(1, grp); - Assert.That(grp.Text.Value, Is.EqualTo("L1")); + [Test] + public void Issue56_GetGroup_by_reference() + { + // setup + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); - msg.GetGroup(2, grp); - Assert.That(grp.Text.Value, Is.EqualTo("L2")); - } + string msgStr = ("8=FIX.4.2|9=87|35=B|34=3|49=CLIENT1|52=20111012-22:15:55.474|56=EXECUTOR|" + + "148=AAAAAAA|33=2|58=L1|58=L2|10=016|").Replace('|', Message.SOH); + QuickFix.FIX42.News msg = new QuickFix.FIX42.News(); + msg.FromString(msgStr, false, dd, dd, _defaultMsgFactory); + Assert.That(msg.GroupCount(Tags.LinesOfText), Is.EqualTo(2)); // for sanity - [Test] - public void MissingDelimiterField() - { - // issue 101 + // the test + QuickFix.FIX42.News.LinesOfTextGroup grp = new QuickFix.FIX42.News.LinesOfTextGroup(); // for return value - QuickFix.DataDictionary.DataDictionary dd = new(); - dd.LoadFIXSpec("FIX44"); + msg.GetGroup(1, grp); + Assert.That(grp.Text.Value, Is.EqualTo("L1")); - // message is missing 703 - string msgStr = ("8=FIX.4.4|9=230|35=AP|34=3|49=XXXXX|52=20120731-14:06:37.848|56=FixKevindemo" - + "1=20050500001|55=EURUSD|453=0|581=1|702=1|704=0|705=20000|710=634792896000000000|715=20120802" - + "721=P-DEA30E1PHC0IW7V|730=1.22608|731=1|734=1.22608|753=1|708=20000|10=030|") - .Replace('|', Message.SOH); + msg.GetGroup(2, grp); + Assert.That(grp.Text.Value, Is.EqualTo("L2")); + } - QuickFix.FIX44.PositionReport msg = new(); + [Test] + public void MissingDelimiterField() + { + // issue 101 - GroupDelimiterTagException ex = - Assert.Throws(delegate { msg.FromString(msgStr, true, dd, dd, _defaultMsgFactory); })!; - Assert.That(ex.Field, Is.EqualTo(702)); - Assert.That(ex.Message, Is.EqualTo("Group 702's first entry does not start with delimiter 703")); - } + QuickFix.DataDictionary.DataDictionary dd = new(); + dd.LoadFIXSpec("FIX44"); - [Test] - public void DateOnlyTimeOnlyConvertProblem() - { - // issue 135 + // message is missing 703 + string msgStr = ("8=FIX.4.4|9=230|35=AP|34=3|49=XXXXX|52=20120731-14:06:37.848|56=FixKevindemo" + + "1=20050500001|55=EURUSD|453=0|581=1|702=1|704=0|705=20000|710=634792896000000000|715=20120802" + + "721=P-DEA30E1PHC0IW7V|730=1.22608|731=1|734=1.22608|753=1|708=20000|10=030|") + .Replace('|', Message.SOH); - QuickFix.DataDictionary.DataDictionary dd = new(); - dd.LoadFIXSpec("FIX44"); + QuickFix.FIX44.PositionReport msg = new(); - string msgStr = ("8=FIX.4.4|9=332|35=W|34=2|49=MA|52=20121024-12:21:42.170|56=xxxx|" - + "22=4|48=BE0932900518|55=[N/A]|262=1b145288-9c9a-4911-a084-7341c69d3e6b|762=EURO_EUR|268=2|" - + "269=0|270=97.625|15=EUR|271=1246000|272=20121024|273=07:30:47|276=I|282=BEARGB21XXX|299=15478575|" - + "269=1|270=108.08|15=EUR|271=884000|272=20121024|273=07:30:47|276=I|282=BEARGB21XXX|299=15467902|10=77|") - .Replace('|', Message.SOH); + GroupDelimiterTagException ex = + Assert.Throws(delegate { msg.FromString(msgStr, true, dd, dd, _defaultMsgFactory); })!; + Assert.That(ex.Field, Is.EqualTo(702)); + Assert.That(ex.Message, Is.EqualTo("Group 702's first entry does not start with delimiter 703")); + } - QuickFix.FIX44.MarketDataSnapshotFullRefresh msg = new(); + [Test] + public void DateOnlyTimeOnlyConvertProblem() + { + // issue 135 - msg.FromString(msgStr, true, dd, dd, _defaultMsgFactory); - QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup gentry1 = new(); - msg.GetGroup(1, gentry1); - Assert.That(gentry1.MDEntryDate.Value, Is.EqualTo(new DateTime(2012, 10, 24))); - Assert.That(gentry1.MDEntryTime.Value.TimeOfDay, Is.EqualTo(new DateTime(2012, 10, 24, 7, 30, 47).TimeOfDay)); - Assert.That(gentry1.MDEntryDate.Value + gentry1.MDEntryTime.Value.TimeOfDay, Is.EqualTo(new DateTime(2012, 10, 24, 7, 30, 47))); - } + QuickFix.DataDictionary.DataDictionary dd = new(); + dd.LoadFIXSpec("FIX44"); - [Test] - public void SendDateOnlyTimeOnlyConvertProblem() - { - // issue 135 - QuickFix.FIX44.MarketDataSnapshotFullRefresh msg = new(); - msg.MDReqID = new MDReqID("1b145288-9c9a-4911-a084-7341c69d3e6b"); - msg.Symbol = new Symbol("[N/A]"); - msg.SecurityIDSource = new SecurityIDSource(SecurityIDSource.ISIN_NUMBER); - msg.SecurityID = new SecurityID("BE0932900518"); - msg.SecuritySubType = new SecuritySubType("EURO_EUR"); - msg.NoMDEntries = new NoMDEntries(2); - QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup grp = new(); - grp.MDEntryType = new MDEntryType(MDEntryType.BID); - grp.MDEntryPx = new MDEntryPx((decimal)97.625); - grp.Currency = new Currency("EUR"); - grp.MDEntrySize = new MDEntrySize(1246000); - grp.MDEntryDate = new MDEntryDate(new DateTime(2012, 10, 24)); - grp.MDEntryTime = new MDEntryTime(new DateTime(1, 1, 1, 7, 30, 47), false); - grp.QuoteCondition = new QuoteCondition(QuoteCondition.NON_FIRM); - grp.MDEntryOriginator = new MDEntryOriginator("BEARGB21XXX"); - grp.QuoteEntryID = new QuoteEntryID("15478575"); - msg.AddGroup(grp); - - grp = new QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup(); - grp.MDEntryType = new MDEntryType(MDEntryType.OFFER); - grp.MDEntryPx = new MDEntryPx((decimal)108.08); - grp.Currency = new Currency("EUR"); - grp.MDEntrySize = new MDEntrySize(884000); - grp.MDEntryDate = new MDEntryDate(new DateTime(2012, 10, 24)); - grp.MDEntryTime = new MDEntryTime(new DateTime(1, 1, 1, 7, 30, 47), false); - grp.QuoteCondition = new QuoteCondition(QuoteCondition.NON_FIRM); - grp.MDEntryOriginator = new MDEntryOriginator("BEARGB21XXX"); - grp.QuoteEntryID = new QuoteEntryID("15467902"); - msg.AddGroup(grp); - - string msgString = msg.ConstructString(); - - string expected = - ("35=W|22=4|48=BE0932900518|55=[N/A]|262=1b145288-9c9a-4911-a084-7341c69d3e6b|762=EURO_EUR|268=2|" - + "269=0|270=97.625|15=EUR|271=1246000|272=20121024|273=07:30:47|276=I|282=BEARGB21XXX|299=15478575|" - + "269=1|270=108.08|15=EUR|271=884000|272=20121024|273=07:30:47|276=I|282=BEARGB21XXX|299=15467902|") - .Replace('|', Message.SOH); - - Assert.That(msgString, Does.Contain(expected)); - } + string msgStr = ("8=FIX.4.4|9=332|35=W|34=2|49=MA|52=20121024-12:21:42.170|56=xxxx|" + + "22=4|48=BE0932900518|55=[N/A]|262=1b145288-9c9a-4911-a084-7341c69d3e6b|762=EURO_EUR|268=2|" + + "269=0|270=97.625|15=EUR|271=1246000|272=20121024|273=07:30:47|276=I|282=BEARGB21XXX|299=15478575|" + + "269=1|270=108.08|15=EUR|271=884000|272=20121024|273=07:30:47|276=I|282=BEARGB21XXX|299=15467902|10=77|") + .Replace('|', Message.SOH); - [Test] - public void MessageHasDecimalWithNoLeadingZero() - { - // issue 160 - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); + QuickFix.FIX44.MarketDataSnapshotFullRefresh msg = new(); - string msgStr = ("8=FIX.4.4|9=122|35=8|34=2|49=sender|52=20121024-12:21:42.170|56=target|" - + "37=orderid|17=execid|150=0|39=0|" - + "55=ibm|228=.23|" // Instrument component; 228 is a float type in the spec - + "54=1|151=1|14=1|6=1|10=45|").Replace('|', Message.SOH); + msg.FromString(msgStr, true, dd, dd, _defaultMsgFactory); + QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup gentry1 = new(); + msg.GetGroup(1, gentry1); + Assert.That(gentry1.MDEntryDate.Value, Is.EqualTo(new DateTime(2012, 10, 24))); + Assert.That(gentry1.MDEntryTime.Value.TimeOfDay, Is.EqualTo(new DateTime(2012, 10, 24, 7, 30, 47).TimeOfDay)); + Assert.That(gentry1.MDEntryDate.Value + gentry1.MDEntryTime.Value.TimeOfDay, Is.EqualTo(new DateTime(2012, 10, 24, 7, 30, 47))); + } - QuickFix.FIX44.ExecutionReport msg = new QuickFix.FIX44.ExecutionReport(); - msg.FromString(msgStr, true, dd, dd, _defaultMsgFactory); + [Test] + public void SendDateOnlyTimeOnlyConvertProblem() + { + // issue 135 + QuickFix.FIX44.MarketDataSnapshotFullRefresh msg = new(); + msg.MDReqID = new MDReqID("1b145288-9c9a-4911-a084-7341c69d3e6b"); + msg.Symbol = new Symbol("[N/A]"); + msg.SecurityIDSource = new SecurityIDSource(SecurityIDSource.ISIN_NUMBER); + msg.SecurityID = new SecurityID("BE0932900518"); + msg.SecuritySubType = new SecuritySubType("EURO_EUR"); + msg.NoMDEntries = new NoMDEntries(2); + QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup grp = new(); + grp.MDEntryType = new MDEntryType(MDEntryType.BID); + grp.MDEntryPx = new MDEntryPx((decimal)97.625); + grp.Currency = new Currency("EUR"); + grp.MDEntrySize = new MDEntrySize(1246000); + grp.MDEntryDate = new MDEntryDate(new DateTime(2012, 10, 24)); + grp.MDEntryTime = new MDEntryTime(new DateTime(1, 1, 1, 7, 30, 47), false); + grp.QuoteCondition = new QuoteCondition(QuoteCondition.NON_FIRM); + grp.MDEntryOriginator = new MDEntryOriginator("BEARGB21XXX"); + grp.QuoteEntryID = new QuoteEntryID("15478575"); + msg.AddGroup(grp); + + grp = new QuickFix.FIX44.MarketDataIncrementalRefresh.NoMDEntriesGroup(); + grp.MDEntryType = new MDEntryType(MDEntryType.OFFER); + grp.MDEntryPx = new MDEntryPx((decimal)108.08); + grp.Currency = new Currency("EUR"); + grp.MDEntrySize = new MDEntrySize(884000); + grp.MDEntryDate = new MDEntryDate(new DateTime(2012, 10, 24)); + grp.MDEntryTime = new MDEntryTime(new DateTime(1, 1, 1, 7, 30, 47), false); + grp.QuoteCondition = new QuoteCondition(QuoteCondition.NON_FIRM); + grp.MDEntryOriginator = new MDEntryOriginator("BEARGB21XXX"); + grp.QuoteEntryID = new QuoteEntryID("15467902"); + msg.AddGroup(grp); + + string msgString = msg.ConstructString(); + + string expected = + ("35=W|22=4|48=BE0932900518|55=[N/A]|262=1b145288-9c9a-4911-a084-7341c69d3e6b|762=EURO_EUR|268=2|" + + "269=0|270=97.625|15=EUR|271=1246000|272=20121024|273=07:30:47|276=I|282=BEARGB21XXX|299=15478575|" + + "269=1|270=108.08|15=EUR|271=884000|272=20121024|273=07:30:47|276=I|282=BEARGB21XXX|299=15467902|") + .Replace('|', Message.SOH); + + Assert.That(msgString, Does.Contain(expected)); + } - Assert.That(msg.Factor.Value, Is.EqualTo(0.23)); - } + [Test] + public void MessageHasDecimalWithNoLeadingZero() + { + // issue 160 + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); - [Test] - public void IsAdmin_IsApp() - { - // issue 173 - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX42"); + string msgStr = ("8=FIX.4.4|9=122|35=8|34=2|49=sender|52=20121024-12:21:42.170|56=target|" + + "37=orderid|17=execid|150=0|39=0|" + + "55=ibm|228=.23|" // Instrument component; 228 is a float type in the spec + + "54=1|151=1|14=1|6=1|10=45|").Replace('|', Message.SOH); - string newsStr = "8=FIX4.2|9=5|35=B|10=133|".Replace('|', Message.SOH); - QuickFix.FIX42.News news = new QuickFix.FIX42.News(); - news.FromString(newsStr, true, dd, dd, _defaultMsgFactory); + QuickFix.FIX44.ExecutionReport msg = new QuickFix.FIX44.ExecutionReport(); + msg.FromString(msgStr, true, dd, dd, _defaultMsgFactory); - string hbStr = "8=FIX.4.2|9=16|35=0|34=3|49=TW|10=1|".Replace('|', Message.SOH); - QuickFix.FIX42.Heartbeat heartbeat = new QuickFix.FIX42.Heartbeat(); - heartbeat.FromString(hbStr, true, dd, dd, _defaultMsgFactory); + Assert.That(msg.Factor.Value, Is.EqualTo(0.23)); + } - Assert.That(news.IsAdmin(), Is.False); - Assert.That(news.IsApp(), Is.True); + [Test] + public void IsAdmin_IsApp() + { + // issue 173 + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX42"); - Assert.That(heartbeat.IsAdmin(), Is.True); - Assert.That(heartbeat.IsApp(), Is.False); - } + string newsStr = "8=FIX4.2|9=5|35=B|10=133|".Replace('|', Message.SOH); + QuickFix.FIX42.News news = new QuickFix.FIX42.News(); + news.FromString(newsStr, true, dd, dd, _defaultMsgFactory); - [Test] - public void TripleNestedGroups_Issue95() - { - // Parser screws up on triple-nested groups. Contributes to ResendRequest failures. - string msgStr = ("8=FIX.4.4|9=999|35=R|34=6|49=sendercompid|52=20130225-10:44:59.149|56=targetcompid|" - + "131=quotereqid|" - + "146=1|" // NoRelatedSym - + "55=ABC|65=CD|48=securityid|22=1|" // group - + "711=1|" // NoUnderlyings - + "311=underlyingsymbol|312=WI|309=underlyingsecurityid|305=1|" - + "10=999|").Replace('|', Message.SOH); - - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - - Message msg = new Message(); - msg.FromString(msgStr, false, dd, dd, _defaultMsgFactory); - - // make sure no fields were dropped in parsing - Assert.That(msg.ConstructString().Length, Is.EqualTo(msgStr.Length)); - - // make sure repeating groups are not rearranged - // 1 level deep - Assert.That(msg.ConstructString(), Does.Contain("55=ABC|65=CD|48=securityid|22=1|".Replace('|', Message.SOH))); - - // 2 levels deep - Assert.That(msg.ConstructString(), Does.Contain("311=underlyingsymbol|312=WI|309=underlyingsecurityid|305=1|".Replace('|', Message.SOH))); - } + string hbStr = "8=FIX.4.2|9=16|35=0|34=3|49=TW|10=1|".Replace('|', Message.SOH); + QuickFix.FIX42.Heartbeat heartbeat = new QuickFix.FIX42.Heartbeat(); + heartbeat.FromString(hbStr, true, dd, dd, _defaultMsgFactory); - [Test] - public void SetFieldsTest() - { - var message = new Message(); - var allocId = new AllocID("123456"); - var allocAccount = new AllocAccount("QuickFixAccount"); - var allocAccountType = new AllocAccountType(AllocAccountType.HOUSE_TRADER); - message.SetFields(new IField[] { allocAccount, allocAccountType, allocId }); + Assert.That(news.IsAdmin(), Is.False); + Assert.That(news.IsApp(), Is.True); - Assert.That(message.IsSetField(Tags.AllocID), Is.EqualTo(true)); - Assert.That(message.GetString(Tags.AllocID), Is.EqualTo("123456")); + Assert.That(heartbeat.IsAdmin(), Is.True); + Assert.That(heartbeat.IsApp(), Is.False); + } - Assert.That(message.IsSetField(Tags.AllocAccount), Is.EqualTo(true)); - Assert.That(message.GetString(Tags.AllocAccount), Is.EqualTo("QuickFixAccount")); + [Test] + public void TripleNestedGroups_Issue95() + { + // Parser screws up on triple-nested groups. Contributes to ResendRequest failures. + string msgStr = ("8=FIX.4.4|9=999|35=R|34=6|49=sendercompid|52=20130225-10:44:59.149|56=targetcompid|" + + "131=quotereqid|" + + "146=1|" // NoRelatedSym + + "55=ABC|65=CD|48=securityid|22=1|" // group + + "711=1|" // NoUnderlyings + + "311=underlyingsymbol|312=WI|309=underlyingsecurityid|305=1|" + + "10=999|").Replace('|', Message.SOH); + + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + + Message msg = new Message(); + msg.FromString(msgStr, false, dd, dd, _defaultMsgFactory); + + // make sure no fields were dropped in parsing + Assert.That(msg.ConstructString().Length, Is.EqualTo(msgStr.Length)); + + // make sure repeating groups are not rearranged + // 1 level deep + Assert.That(msg.ConstructString(), Does.Contain("55=ABC|65=CD|48=securityid|22=1|".Replace('|', Message.SOH))); + + // 2 levels deep + Assert.That(msg.ConstructString(), Does.Contain("311=underlyingsymbol|312=WI|309=underlyingsecurityid|305=1|".Replace('|', Message.SOH))); + } - Assert.That(message.IsSetField(Tags.AllocAccountType), Is.EqualTo(true)); - Assert.That(message.GetInt(Tags.AllocAccountType), Is.EqualTo(AllocAccountType.HOUSE_TRADER)); - } + [Test] + public void SetFieldsTest() + { + var message = new Message(); + var allocId = new AllocID("123456"); + var allocAccount = new AllocAccount("QuickFixAccount"); + var allocAccountType = new AllocAccountType(AllocAccountType.HOUSE_TRADER); + message.SetFields(new IField[] { allocAccount, allocAccountType, allocId }); - [Test] - public void ChecksumIsLastFieldOfTrailer() - { - // issue 473 - QuickFix.FIX42.News msg = new QuickFix.FIX42.News(new Headline("foobar")); - msg.LinesOfText = new LinesOfText(0); + Assert.That(message.IsSetField(Tags.AllocID), Is.EqualTo(true)); + Assert.That(message.GetString(Tags.AllocID), Is.EqualTo("123456")); - msg.Trailer.SetField(new Signature("woot")); - msg.Trailer.SetField(new SignatureLength(4)); + Assert.That(message.IsSetField(Tags.AllocAccount), Is.EqualTo(true)); + Assert.That(message.GetString(Tags.AllocAccount), Is.EqualTo("QuickFixAccount")); - string foo = msg.ConstructString().Replace(Message.SOH, '|'); - Assert.That(foo, Does.EndWith("|10=099|")); - } + Assert.That(message.IsSetField(Tags.AllocAccountType), Is.EqualTo(true)); + Assert.That(message.GetInt(Tags.AllocAccountType), Is.EqualTo(AllocAccountType.HOUSE_TRADER)); + } - [Test] - [Category("JSON")] - public void JsonNestedRepeatingGroupParseGroupTest() - { - // Given the following string in FIX JSON Encoding: - string json = @" - { - ""Header"": { - ""BeginString"":""FIX.4.4"", - ""MsgSeqNum"":""360"", - ""MsgType"":""8"", - ""SenderCompID"":""BLPTSOX"", - ""SendingTime"":""20130321-15:21:23"", - ""TargetCompID"":""THINKTSOX"" - }, - ""Body"": { - ""31337"":""custom body field"", - ""AvgPx"":""122.255"", - ""ClOrdID"":""61101189"", - ""CumQty"":""1990000"", - ""ExecID"":""VCON:20130321:50018:5:12"", - ""LastPx"":""122.255"", - ""LastQty"":""1990000"", - ""OrderID"":""116"", - ""OrderQty"":""1990000"", - ""OrdStatus"":""2"", - ""Side"":""1"", - ""Symbol"":""[N/A]"", - ""TransactTime"":""20130321-15:21:23"", - ""ExecType"":""F"", - ""LeavesQty"":""0"", - ""NoPartyIDs"": [ - { - ""PartyIDSource"":""D"", - ""PartyID"":""OHAI"", - ""PartyRole"":""1"", - ""NoPartySubIDs"": [ - { - ""PartySubID"":""14"", - ""PartySubIDType"":""4"", - ""31338"":""custom group field"" - } - ] - }, - { ""PartyIDSource"":""D"", ""PartyID"":""TFOLIO:6804469"", ""PartyRole"":""12"" }, - { ""PartyIDSource"":""D"", ""PartyID"":""TFOLIO"", ""PartyRole"":""11"" }, - { ""PartyIDSource"":""D"", ""PartyID"":""THINKFOLIO LTD"", ""PartyRole"":""13"" }, - { ""PartyIDSource"":""D"", ""PartyID"":""SXT"", ""PartyRole"":""16"" }, - { ""PartyIDSource"":""D"", ""PartyID"":""TFOLIO:6804469"", ""PartyRole"":""36"" } - ] - }, - ""Trailer"": { - } + [Test] + public void ChecksumIsLastFieldOfTrailer() + { + // issue 473 + QuickFix.FIX42.News msg = new QuickFix.FIX42.News(new Headline("foobar")); + msg.LinesOfText = new LinesOfText(0); + + msg.Trailer.SetField(new Signature("woot")); + msg.Trailer.SetField(new SignatureLength(4)); + + string foo = msg.ConstructString().Replace(Message.SOH, '|'); + Assert.That(foo, Does.EndWith("|10=099|")); + } + + [Test] + [Category("JSON")] + public void JsonNestedRepeatingGroupParseGroupTest() + { + // Given the following string in FIX JSON Encoding: + string json = @" + { + ""Header"": { + ""BeginString"":""FIX.4.4"", + ""MsgSeqNum"":""360"", + ""MsgType"":""8"", + ""SenderCompID"":""BLPTSOX"", + ""SendingTime"":""20130321-15:21:23"", + ""TargetCompID"":""THINKTSOX"" + }, + ""Body"": { + ""31337"":""custom body field"", + ""AvgPx"":""122.255"", + ""ClOrdID"":""61101189"", + ""CumQty"":""1990000"", + ""ExecID"":""VCON:20130321:50018:5:12"", + ""LastPx"":""122.255"", + ""LastQty"":""1990000"", + ""OrderID"":""116"", + ""OrderQty"":""1990000"", + ""OrdStatus"":""2"", + ""Side"":""1"", + ""Symbol"":""[N/A]"", + ""TransactTime"":""20130321-15:21:23"", + ""ExecType"":""F"", + ""LeavesQty"":""0"", + ""NoPartyIDs"": [ + { + ""PartyIDSource"":""D"", + ""PartyID"":""OHAI"", + ""PartyRole"":""1"", + ""NoPartySubIDs"": [ + { + ""PartySubID"":""14"", + ""PartySubIDType"":""4"", + ""31338"":""custom group field"" + } + ] + }, + { ""PartyIDSource"":""D"", ""PartyID"":""TFOLIO:6804469"", ""PartyRole"":""12"" }, + { ""PartyIDSource"":""D"", ""PartyID"":""TFOLIO"", ""PartyRole"":""11"" }, + { ""PartyIDSource"":""D"", ""PartyID"":""THINKFOLIO LTD"", ""PartyRole"":""13"" }, + { ""PartyIDSource"":""D"", ""PartyID"":""SXT"", ""PartyRole"":""16"" }, + { ""PartyIDSource"":""D"", ""PartyID"":""TFOLIO:6804469"", ""PartyRole"":""36"" } + ] + }, + ""Trailer"": { } - "; - - // When the JSON is parsed into a QuickFIX Message - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX44"); - var msg = new Message(); - msg.FromJson(json, true, dd, dd, _defaultMsgFactory); - //TestContext.Out.WriteLine(msg.ToString().Replace(Message.SOH, "|")); - - // Then the Header of the Message should contain: - Assert.That(msg.Header.GetString(Tags.BeginString), Is.EqualTo("FIX.4.4")); - Assert.That(msg.Header.GetString(Tags.MsgSeqNum), Is.EqualTo("360")); - Assert.That(msg.Header.GetString(Tags.BodyLength), Is.EqualTo("446")); - - // And the Body of the Message should contain: - Assert.That(msg.GetString(31337), Is.EqualTo("custom body field")); - Assert.That(msg.GetString(Tags.AvgPx), Is.EqualTo("122.255")); - Assert.That(msg.GetString(Tags.Symbol), Is.EqualTo("[N/A]")); - Assert.That(msg.GetString(Tags.OrdStatus), Is.EqualTo("2")); - Assert.That(msg.GetString(Tags.TransactTime), Is.EqualTo("20130321-15:21:23")); - - // And the NoPartyIDs Group should contain: - Assert.That(msg.GetString(Tags.NoPartyIDs), Is.EqualTo("6")); - - var noPartyGrp = msg.GetGroup(1, Tags.NoPartyIDs); - Assert.That(noPartyGrp.GetString(Tags.PartyID), Is.EqualTo("OHAI")); - Assert.That(noPartyGrp.GetString(Tags.PartyIDSource), Is.EqualTo("D")); - Assert.That(noPartyGrp.GetString(Tags.NoPartySubIDs), Is.EqualTo("1")); - - var noPartySubGrp = noPartyGrp.GetGroup(1, Tags.NoPartySubIDs); - Assert.That(noPartySubGrp.GetString(Tags.PartySubID), Is.EqualTo("14")); - Assert.That(noPartySubGrp.GetString(Tags.PartySubIDType), Is.EqualTo("4")); - Assert.That(noPartySubGrp.GetString(31338), Is.EqualTo("custom group field")); - } + } + "; + + // When the JSON is parsed into a QuickFIX Message + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX44"); + var msg = new Message(); + msg.FromJson(json, true, dd, dd, _defaultMsgFactory); + //TestContext.Out.WriteLine(msg.ToString().Replace(Message.SOH, "|")); + + // Then the Header of the Message should contain: + Assert.That(msg.Header.GetString(Tags.BeginString), Is.EqualTo("FIX.4.4")); + Assert.That(msg.Header.GetString(Tags.MsgSeqNum), Is.EqualTo("360")); + Assert.That(msg.Header.GetString(Tags.BodyLength), Is.EqualTo("446")); + + // And the Body of the Message should contain: + Assert.That(msg.GetString(31337), Is.EqualTo("custom body field")); + Assert.That(msg.GetString(Tags.AvgPx), Is.EqualTo("122.255")); + Assert.That(msg.GetString(Tags.Symbol), Is.EqualTo("[N/A]")); + Assert.That(msg.GetString(Tags.OrdStatus), Is.EqualTo("2")); + Assert.That(msg.GetString(Tags.TransactTime), Is.EqualTo("20130321-15:21:23")); + + // And the NoPartyIDs Group should contain: + Assert.That(msg.GetString(Tags.NoPartyIDs), Is.EqualTo("6")); + + var noPartyGrp = msg.GetGroup(1, Tags.NoPartyIDs); + Assert.That(noPartyGrp.GetString(Tags.PartyID), Is.EqualTo("OHAI")); + Assert.That(noPartyGrp.GetString(Tags.PartyIDSource), Is.EqualTo("D")); + Assert.That(noPartyGrp.GetString(Tags.NoPartySubIDs), Is.EqualTo("1")); + + var noPartySubGrp = noPartyGrp.GetGroup(1, Tags.NoPartySubIDs); + Assert.That(noPartySubGrp.GetString(Tags.PartySubID), Is.EqualTo("14")); + Assert.That(noPartySubGrp.GetString(Tags.PartySubIDType), Is.EqualTo("4")); + Assert.That(noPartySubGrp.GetString(31338), Is.EqualTo("custom group field")); + } - private QuickFix.FIX44.News CreateStringResultInput() { - QuickFix.FIX44.News msg = new(); - msg.Header.SetField(new BeginString(QuickFix.FixValues.BeginString.FIX44)); - msg.Header.SetField(new MsgType("B")); - msg.SetField(new Headline("myHeadline")); - - QuickFix.FIX44.News.LinesOfTextGroup grp1 = new() { Text = new Text("line1") }; - QuickFix.FIX44.News.LinesOfTextGroup grp2 = new() { Text = new Text("line2") }; - msg.AddGroup(grp1); - msg.AddGroup(grp2); - return msg; - } + private QuickFix.FIX44.News CreateStringResultInput() { + QuickFix.FIX44.News msg = new(); + msg.Header.SetField(new BeginString(QuickFix.FixValues.BeginString.FIX44)); + msg.Header.SetField(new MsgType("B")); + msg.SetField(new Headline("myHeadline")); + + QuickFix.FIX44.News.LinesOfTextGroup grp1 = new() { Text = new Text("line1") }; + QuickFix.FIX44.News.LinesOfTextGroup grp2 = new() { Text = new Text("line2") }; + msg.AddGroup(grp1); + msg.AddGroup(grp2); + return msg; + } - [Test] - public void ToStringTest() { - QuickFix.FIX44.News msg = CreateStringResultInput(); - // ToString() does not add BodyLength or CheckSum -- it does not change object state - string expected = "8=FIX.4.4|35=B|148=myHeadline|33=2|58=line1|58=line2|"; - Assert.That(expected, Is.EqualTo(msg.ToString().Replace(Message.SOH, '|'))); - } + [Test] + public void ToStringTest() { + QuickFix.FIX44.News msg = CreateStringResultInput(); + // ToString() does not add BodyLength or CheckSum -- it does not change object state + string expected = "8=FIX.4.4|35=B|148=myHeadline|33=2|58=line1|58=line2|"; + Assert.That(expected, Is.EqualTo(msg.ToString().Replace(Message.SOH, '|'))); + } - [Test] - public void ConstructStringTest() { - QuickFix.FIX44.News msg = CreateStringResultInput(); - // ConstructString() adds BodyLength and CheckSum - string expected = "8=FIX.4.4|9=43|35=B|148=myHeadline|33=2|58=line1|58=line2|10=161|"; - Assert.That(expected, Is.EqualTo(msg.ConstructString().Replace(Message.SOH, '|'))); + [Test] + public void ConstructStringTest() { + QuickFix.FIX44.News msg = CreateStringResultInput(); + // ConstructString() adds BodyLength and CheckSum + string expected = "8=FIX.4.4|9=43|35=B|148=myHeadline|33=2|58=line1|58=line2|10=161|"; + Assert.That(expected, Is.EqualTo(msg.ConstructString().Replace(Message.SOH, '|'))); - // the object state is changed - Assert.That(expected, Is.EqualTo(msg.ToString().Replace(Message.SOH, '|'))); - } + // the object state is changed + Assert.That(expected, Is.EqualTo(msg.ToString().Replace(Message.SOH, '|'))); + } - [Test] - public void FromString_EndsWithGroup() { - QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); - dd.LoadFIXSpec("FIX42"); + [Test] + public void FromString_EndsWithGroup() { + QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary(); + dd.LoadFIXSpec("FIX42"); - string s = ("8=FIX.4.2|9=91|35=B|34=2|49=TW|52=20111011-15:06:23.103|56=ISLD|" - + "148=headline|33=1|" - + "58=line1|354=3|355=uno|" - // no checksum! - ).Replace('|', Message.SOH); + string s = ("8=FIX.4.2|9=91|35=B|34=2|49=TW|52=20111011-15:06:23.103|56=ISLD|" + + "148=headline|33=1|" + + "58=line1|354=3|355=uno|" + // no checksum! + ).Replace('|', Message.SOH); - QuickFix.FIX42.News n = new QuickFix.FIX42.News(); - n.FromString(s, false, dd, dd); + QuickFix.FIX42.News n = new QuickFix.FIX42.News(); + n.FromString(s, false, dd, dd); - Assert.That(n.ToString().Replace(Message.SOH, '|'), Is.EqualTo( - "8=FIX.4.2|9=91|35=B|34=2|49=TW|52=20111011-15:06:23.103|56=ISLD|148=headline|33=1|58=line1|354=3|355=uno|" - )); - } + Assert.That(n.ToString().Replace(Message.SOH, '|'), Is.EqualTo( + "8=FIX.4.2|9=91|35=B|34=2|49=TW|52=20111011-15:06:23.103|56=ISLD|148=headline|33=1|58=line1|354=3|355=uno|" + )); } } diff --git a/UnitTests/MessageToXmlTests.cs b/UnitTests/MessageToXmlTests.cs index a224d8ca2..459f3d957 100644 --- a/UnitTests/MessageToXmlTests.cs +++ b/UnitTests/MessageToXmlTests.cs @@ -4,127 +4,126 @@ using NUnit.Framework; using QuickFix; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class MessageToXmlTests { - [TestFixture] - public class MessageToXmlTests + private readonly IMessageFactory _defaultMsgFactory = new DefaultMessageFactory(); + + [Test] + public void ToXMLTest() + { + string str1 = "8=FIX.4.2\x01" + "9=55\x01" + "35=0\x01" + "34=3\x01" + "49=TW\x01" + + "52=20000426-12:05:06\x01" + "56=ISLD\x01" + "1=acct123\x01" + "10=123\x01"; + Message msg = new Message(); + msg.FromString(str1, true, null, null, _defaultMsgFactory); + + string expected = @"
"; + Assert.That(msg.ToXML(), Is.EqualTo(expected)); + } + + + [Test] + public void ToXMLWithGroupsTest() { - private readonly IMessageFactory _defaultMsgFactory = new DefaultMessageFactory(); - - [Test] - public void ToXMLTest() - { - string str1 = "8=FIX.4.2\x01" + "9=55\x01" + "35=0\x01" + "34=3\x01" + "49=TW\x01" + - "52=20000426-12:05:06\x01" + "56=ISLD\x01" + "1=acct123\x01" + "10=123\x01"; - Message msg = new Message(); - msg.FromString(str1, true, null, null, _defaultMsgFactory); - - string expected = @"
"; - Assert.That(msg.ToXML(), Is.EqualTo(expected)); - } - - - [Test] - public void ToXMLWithGroupsTest() - { - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "fix", "FIX44.xml")); - - string[] msgFields = { - // header - "8=FIX.4.4","9=638", "35=8", "34=360", "49=BLPTSOX", "52=20130321-15:21:23", "56=THINKTSOX", "57=6804469", "128=ZERO", - // non-group body fields - "6=122.255", "11=61101189", "14=1990000", "15=GBP", "17=VCON:20130321:50018:5:12", "22=4", "31=122.255", "32=1990000", - "37=116", "38=1990000", "39=2", "48=GB0032452392", "54=1", "55=[N/A]", "60=20130321-15:21:23", "64=20130322", "75=20130321", - "106=UK TSY 4 1/4% 2036", "118=2436321.85", "150=F", "151=0", "157=15", "159=3447.35", "192=0", "198=3739:20130321:50018:5", - "223=0.0425", "228=1", "236=0.0291371041", "238=0", "381=2432874.5", "423=1", "470=GB", "541=20360307", - // NoPartyIDs - "453=6", - "448=VCON", "447=D", "452=1", "802=1", "523=14", "803=4", - "448=TFOLIO:6804469", "447=D", "452=12", - "448=TFOLIO", "447=D", "452=11", - "448=THINKFOLIO LTD", "447=D", "452=13", - "448=SXT", "447=D", "452=16", - "448=TFOLIO:6804469", "447=D", "452=36", - "10=152" - }; - string msgStr = string.Join(Message.SOH, msgFields) + Message.SOH; - - QuickFix.FIX44.ExecutionReport msg = new QuickFix.FIX44.ExecutionReport(); - msg.FromString(msgStr, true, dd, dd, null); // <-- null factory! - - string expected = @"
"; - Assert.That(msg.ToXML(dataDictionary: dd), Is.EqualTo(expected)); - - // If no DD, then output can't have field names - Assert.That(msg.ToXML(), Does.Contain(@"")); - } - - [Test] - public void ToJSONWithGroupsTest() - { - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "fix", "FIX44.xml")); - - string[] msgFields = { - // header - "8=FIX.4.4","9=638", "35=8", "34=360", "49=BLPTSOX", "52=20130321-15:21:23", "56=THINKTSOX", "57=6804469", "128=ZERO", - // non-group body fields - "6=122.255", "11=61101189", "14=1990000", "15=GBP", "17=VCON:20130321:50018:5:12", "22=4", "31=122.255", "32=1990000", - "37=116", "38=1990000", "39=2", "48=GB0032452392", "54=1", "55=[N/A]", "60=20130321-15:21:23", "64=20130322", "75=20130321", - "106=UK TSY 4 1/4% 2036", "118=2436321.85", "150=F", "151=0", "157=15", "159=3447.35", "192=0", "198=3739:20130321:50018:5", - "223=0.0425", "228=1", "236=0.0291371041", "238=0", "381=2432874.5", "423=1", "470=GB", "541=20360307", - // NoPartyIDs - "453=6", - "448=VCON", "447=D", "452=1", "802=1", "523=14", "803=4", - "448=TFOLIO:6804469", "447=D", "452=12", - "448=TFOLIO", "447=D", "452=11", - "448=THINKFOLIO LTD", "447=D", "452=13", - "448=SXT", "447=D", "452=16", - "448=TFOLIO:6804469", "447=D", "452=36", - "10=152" - }; - string msgStr = string.Join(Message.SOH, msgFields) + Message.SOH; - - QuickFix.FIX44.ExecutionReport msg = new QuickFix.FIX44.ExecutionReport(); - msg.FromString(msgStr, true, dd, dd, null); // <-- null factory! - - // CASE 1: params (dd, false) => tags converted to names, enums are not converted - const string expected = "{\"Header\":{\"BeginString\":\"FIX.4.4\",\"BodyLength\":\"638\",\"MsgSeqNum\":\"360\",\"MsgType\":\"8\",\"SenderCompID\":\"BLPTSOX\",\"SendingTime\":\"20130321-15:21:23\",\"TargetCompID\":\"THINKTSOX\",\"TargetSubID\":\"6804469\",\"DeliverToCompID\":\"ZERO\"},\"Body\":{\"AvgPx\":\"122.255\",\"ClOrdID\":\"61101189\",\"CumQty\":\"1990000\",\"Currency\":\"GBP\",\"ExecID\":\"VCON:20130321:50018:5:12\",\"SecurityIDSource\":\"4\",\"LastPx\":\"122.255\",\"LastQty\":\"1990000\",\"OrderID\":\"116\",\"OrderQty\":\"1990000\",\"OrdStatus\":\"2\",\"SecurityID\":\"GB0032452392\",\"Side\":\"1\",\"Symbol\":\"[N/A]\",\"TransactTime\":\"20130321-15:21:23\",\"SettlDate\":\"20130322\",\"TradeDate\":\"20130321\",\"Issuer\":\"UK TSY 4 1/4% 2036\",\"NetMoney\":\"2436321.85\",\"ExecType\":\"F\",\"LeavesQty\":\"0\",\"NumDaysInterest\":\"15\",\"AccruedInterestAmt\":\"3447.35\",\"OrderQty2\":\"0\",\"SecondaryOrderID\":\"3739:20130321:50018:5\",\"CouponRate\":\"0.0425\",\"Factor\":\"1\",\"Yield\":\"0.0291371041\",\"Concession\":\"0\",\"GrossTradeAmt\":\"2432874.5\",\"PriceType\":\"1\",\"CountryOfIssue\":\"GB\",\"MaturityDate\":\"20360307\",\"NoPartyIDs\":[{\"PartyIDSource\":\"D\",\"PartyID\":\"VCON\",\"PartyRole\":\"1\",\"NoPartySubIDs\":[{\"PartySubID\":\"14\",\"PartySubIDType\":\"4\"}]},{\"PartyIDSource\":\"D\",\"PartyID\":\"TFOLIO:6804469\",\"PartyRole\":\"12\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"TFOLIO\",\"PartyRole\":\"11\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"THINKFOLIO LTD\",\"PartyRole\":\"13\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"SXT\",\"PartyRole\":\"16\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"TFOLIO:6804469\",\"PartyRole\":\"36\"}]},\"Trailer\":{}}"; - Assert.That(msg.ToJSON(dataDictionary: dd, convertEnumsToDescriptions: false), Is.EqualTo(expected)); - - // CASE 2: params (dd, true) => tags converted to names, enums are converted to names - Assert.That(msg.ToJSON(dataDictionary: dd, convertEnumsToDescriptions: true), Does.Contain("\"MsgType\":\"EXECUTION_REPORT\"")); - - // CASE 3: params (null, false) => tags are numbers, enums are not converted - Assert.That(msg.ToJSON(dataDictionary: null), Does.Contain("\"35\":\"8\"")); - - // CASE 4: params (dd, false, tagsToMask) => tags converted to names, all instances of tags 49 (SenderCompID) and 448 (PartyID) are masked with default value [HIDDEN] - const string defaultMaskExpected = "{\"Header\":{\"BeginString\":\"FIX.4.4\",\"BodyLength\":\"638\",\"MsgSeqNum\":\"360\",\"MsgType\":\"8\",\"SenderCompID\":\"[HIDDEN]\",\"SendingTime\":\"20130321-15:21:23\",\"TargetCompID\":\"THINKTSOX\",\"TargetSubID\":\"6804469\",\"DeliverToCompID\":\"ZERO\"},\"Body\":{\"AvgPx\":\"122.255\",\"ClOrdID\":\"61101189\",\"CumQty\":\"1990000\",\"Currency\":\"GBP\",\"ExecID\":\"VCON:20130321:50018:5:12\",\"SecurityIDSource\":\"4\",\"LastPx\":\"122.255\",\"LastQty\":\"1990000\",\"OrderID\":\"116\",\"OrderQty\":\"1990000\",\"OrdStatus\":\"2\",\"SecurityID\":\"GB0032452392\",\"Side\":\"1\",\"Symbol\":\"[N/A]\",\"TransactTime\":\"20130321-15:21:23\",\"SettlDate\":\"20130322\",\"TradeDate\":\"20130321\",\"Issuer\":\"UK TSY 4 1/4% 2036\",\"NetMoney\":\"2436321.85\",\"ExecType\":\"F\",\"LeavesQty\":\"0\",\"NumDaysInterest\":\"15\",\"AccruedInterestAmt\":\"3447.35\",\"OrderQty2\":\"0\",\"SecondaryOrderID\":\"3739:20130321:50018:5\",\"CouponRate\":\"0.0425\",\"Factor\":\"1\",\"Yield\":\"0.0291371041\",\"Concession\":\"0\",\"GrossTradeAmt\":\"2432874.5\",\"PriceType\":\"1\",\"CountryOfIssue\":\"GB\",\"MaturityDate\":\"20360307\",\"NoPartyIDs\":[{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"1\",\"NoPartySubIDs\":[{\"PartySubID\":\"14\",\"PartySubIDType\":\"4\"}]},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"12\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"11\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"13\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"16\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"36\"}]},\"Trailer\":{}}"; - List tagsToMask = [49,448]; - Assert.That(msg.ToJSON(dataDictionary: dd, convertEnumsToDescriptions: false, tagsToMask), Is.EqualTo(defaultMaskExpected)); - - // CASE 5: params (dd, false, tagsToMask, customMaskText) => tags converted to names, all instances of tags 49 (SenderCompID) and 448 (PartyID) are masked with custom mask text MASK - const string customMaskExpected = "{\"Header\":{\"BeginString\":\"FIX.4.4\",\"BodyLength\":\"638\",\"MsgSeqNum\":\"360\",\"MsgType\":\"8\",\"SenderCompID\":\"MASK\",\"SendingTime\":\"20130321-15:21:23\",\"TargetCompID\":\"THINKTSOX\",\"TargetSubID\":\"6804469\",\"DeliverToCompID\":\"ZERO\"},\"Body\":{\"AvgPx\":\"122.255\",\"ClOrdID\":\"61101189\",\"CumQty\":\"1990000\",\"Currency\":\"GBP\",\"ExecID\":\"VCON:20130321:50018:5:12\",\"SecurityIDSource\":\"4\",\"LastPx\":\"122.255\",\"LastQty\":\"1990000\",\"OrderID\":\"116\",\"OrderQty\":\"1990000\",\"OrdStatus\":\"2\",\"SecurityID\":\"GB0032452392\",\"Side\":\"1\",\"Symbol\":\"[N/A]\",\"TransactTime\":\"20130321-15:21:23\",\"SettlDate\":\"20130322\",\"TradeDate\":\"20130321\",\"Issuer\":\"UK TSY 4 1/4% 2036\",\"NetMoney\":\"2436321.85\",\"ExecType\":\"F\",\"LeavesQty\":\"0\",\"NumDaysInterest\":\"15\",\"AccruedInterestAmt\":\"3447.35\",\"OrderQty2\":\"0\",\"SecondaryOrderID\":\"3739:20130321:50018:5\",\"CouponRate\":\"0.0425\",\"Factor\":\"1\",\"Yield\":\"0.0291371041\",\"Concession\":\"0\",\"GrossTradeAmt\":\"2432874.5\",\"PriceType\":\"1\",\"CountryOfIssue\":\"GB\",\"MaturityDate\":\"20360307\",\"NoPartyIDs\":[{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"1\",\"NoPartySubIDs\":[{\"PartySubID\":\"14\",\"PartySubIDType\":\"4\"}]},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"12\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"11\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"13\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"16\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"36\"}]},\"Trailer\":{}}"; - Assert.That(msg.ToJSON(dataDictionary: dd, convertEnumsToDescriptions: false, tagsToMask, "MASK"), Is.EqualTo(customMaskExpected)); - - // EXCEPTION CASE: params (null, true) => Exception - var ex = Assert.Throws(delegate { msg.ToJSON(null, true); })!; - Assert.That(ex.Message, - Does.Contain("Must be non-null if 'convertEnumsToDescriptions' is true. (Parameter 'dataDictionary')")); - } - - [Test] - public void ToJSONWithNewLineTest() - { - var dd = new QuickFix.DataDictionary.DataDictionary(); - dd.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "fix", "FIX44.xml")); - - var msg = new Message(); - msg.SetField(new QuickFix.Fields.Text("Some text.\r\n With some more text")); - - const string expected = "{\"Header\":{},\"Body\":{\"Text\":\"Some text.\\r\\n With some more text\"},\"Trailer\":{}}"; - Assert.That(msg.ToJSON(dd), Is.EqualTo(expected)); - } + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "fix", "FIX44.xml")); + + string[] msgFields = { + // header + "8=FIX.4.4","9=638", "35=8", "34=360", "49=BLPTSOX", "52=20130321-15:21:23", "56=THINKTSOX", "57=6804469", "128=ZERO", + // non-group body fields + "6=122.255", "11=61101189", "14=1990000", "15=GBP", "17=VCON:20130321:50018:5:12", "22=4", "31=122.255", "32=1990000", + "37=116", "38=1990000", "39=2", "48=GB0032452392", "54=1", "55=[N/A]", "60=20130321-15:21:23", "64=20130322", "75=20130321", + "106=UK TSY 4 1/4% 2036", "118=2436321.85", "150=F", "151=0", "157=15", "159=3447.35", "192=0", "198=3739:20130321:50018:5", + "223=0.0425", "228=1", "236=0.0291371041", "238=0", "381=2432874.5", "423=1", "470=GB", "541=20360307", + // NoPartyIDs + "453=6", + "448=VCON", "447=D", "452=1", "802=1", "523=14", "803=4", + "448=TFOLIO:6804469", "447=D", "452=12", + "448=TFOLIO", "447=D", "452=11", + "448=THINKFOLIO LTD", "447=D", "452=13", + "448=SXT", "447=D", "452=16", + "448=TFOLIO:6804469", "447=D", "452=36", + "10=152" + }; + string msgStr = string.Join(Message.SOH, msgFields) + Message.SOH; + + QuickFix.FIX44.ExecutionReport msg = new QuickFix.FIX44.ExecutionReport(); + msg.FromString(msgStr, true, dd, dd, null); // <-- null factory! + + string expected = @"
"; + Assert.That(msg.ToXML(dataDictionary: dd), Is.EqualTo(expected)); + + // If no DD, then output can't have field names + Assert.That(msg.ToXML(), Does.Contain(@"")); + } + + [Test] + public void ToJSONWithGroupsTest() + { + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "fix", "FIX44.xml")); + + string[] msgFields = { + // header + "8=FIX.4.4","9=638", "35=8", "34=360", "49=BLPTSOX", "52=20130321-15:21:23", "56=THINKTSOX", "57=6804469", "128=ZERO", + // non-group body fields + "6=122.255", "11=61101189", "14=1990000", "15=GBP", "17=VCON:20130321:50018:5:12", "22=4", "31=122.255", "32=1990000", + "37=116", "38=1990000", "39=2", "48=GB0032452392", "54=1", "55=[N/A]", "60=20130321-15:21:23", "64=20130322", "75=20130321", + "106=UK TSY 4 1/4% 2036", "118=2436321.85", "150=F", "151=0", "157=15", "159=3447.35", "192=0", "198=3739:20130321:50018:5", + "223=0.0425", "228=1", "236=0.0291371041", "238=0", "381=2432874.5", "423=1", "470=GB", "541=20360307", + // NoPartyIDs + "453=6", + "448=VCON", "447=D", "452=1", "802=1", "523=14", "803=4", + "448=TFOLIO:6804469", "447=D", "452=12", + "448=TFOLIO", "447=D", "452=11", + "448=THINKFOLIO LTD", "447=D", "452=13", + "448=SXT", "447=D", "452=16", + "448=TFOLIO:6804469", "447=D", "452=36", + "10=152" + }; + string msgStr = string.Join(Message.SOH, msgFields) + Message.SOH; + + QuickFix.FIX44.ExecutionReport msg = new QuickFix.FIX44.ExecutionReport(); + msg.FromString(msgStr, true, dd, dd, null); // <-- null factory! + + // CASE 1: params (dd, false) => tags converted to names, enums are not converted + const string expected = "{\"Header\":{\"BeginString\":\"FIX.4.4\",\"BodyLength\":\"638\",\"MsgSeqNum\":\"360\",\"MsgType\":\"8\",\"SenderCompID\":\"BLPTSOX\",\"SendingTime\":\"20130321-15:21:23\",\"TargetCompID\":\"THINKTSOX\",\"TargetSubID\":\"6804469\",\"DeliverToCompID\":\"ZERO\"},\"Body\":{\"AvgPx\":\"122.255\",\"ClOrdID\":\"61101189\",\"CumQty\":\"1990000\",\"Currency\":\"GBP\",\"ExecID\":\"VCON:20130321:50018:5:12\",\"SecurityIDSource\":\"4\",\"LastPx\":\"122.255\",\"LastQty\":\"1990000\",\"OrderID\":\"116\",\"OrderQty\":\"1990000\",\"OrdStatus\":\"2\",\"SecurityID\":\"GB0032452392\",\"Side\":\"1\",\"Symbol\":\"[N/A]\",\"TransactTime\":\"20130321-15:21:23\",\"SettlDate\":\"20130322\",\"TradeDate\":\"20130321\",\"Issuer\":\"UK TSY 4 1/4% 2036\",\"NetMoney\":\"2436321.85\",\"ExecType\":\"F\",\"LeavesQty\":\"0\",\"NumDaysInterest\":\"15\",\"AccruedInterestAmt\":\"3447.35\",\"OrderQty2\":\"0\",\"SecondaryOrderID\":\"3739:20130321:50018:5\",\"CouponRate\":\"0.0425\",\"Factor\":\"1\",\"Yield\":\"0.0291371041\",\"Concession\":\"0\",\"GrossTradeAmt\":\"2432874.5\",\"PriceType\":\"1\",\"CountryOfIssue\":\"GB\",\"MaturityDate\":\"20360307\",\"NoPartyIDs\":[{\"PartyIDSource\":\"D\",\"PartyID\":\"VCON\",\"PartyRole\":\"1\",\"NoPartySubIDs\":[{\"PartySubID\":\"14\",\"PartySubIDType\":\"4\"}]},{\"PartyIDSource\":\"D\",\"PartyID\":\"TFOLIO:6804469\",\"PartyRole\":\"12\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"TFOLIO\",\"PartyRole\":\"11\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"THINKFOLIO LTD\",\"PartyRole\":\"13\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"SXT\",\"PartyRole\":\"16\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"TFOLIO:6804469\",\"PartyRole\":\"36\"}]},\"Trailer\":{}}"; + Assert.That(msg.ToJSON(dataDictionary: dd, convertEnumsToDescriptions: false), Is.EqualTo(expected)); + + // CASE 2: params (dd, true) => tags converted to names, enums are converted to names + Assert.That(msg.ToJSON(dataDictionary: dd, convertEnumsToDescriptions: true), Does.Contain("\"MsgType\":\"EXECUTION_REPORT\"")); + + // CASE 3: params (null, false) => tags are numbers, enums are not converted + Assert.That(msg.ToJSON(dataDictionary: null), Does.Contain("\"35\":\"8\"")); + + // CASE 4: params (dd, false, tagsToMask) => tags converted to names, all instances of tags 49 (SenderCompID) and 448 (PartyID) are masked with default value [HIDDEN] + const string defaultMaskExpected = "{\"Header\":{\"BeginString\":\"FIX.4.4\",\"BodyLength\":\"638\",\"MsgSeqNum\":\"360\",\"MsgType\":\"8\",\"SenderCompID\":\"[HIDDEN]\",\"SendingTime\":\"20130321-15:21:23\",\"TargetCompID\":\"THINKTSOX\",\"TargetSubID\":\"6804469\",\"DeliverToCompID\":\"ZERO\"},\"Body\":{\"AvgPx\":\"122.255\",\"ClOrdID\":\"61101189\",\"CumQty\":\"1990000\",\"Currency\":\"GBP\",\"ExecID\":\"VCON:20130321:50018:5:12\",\"SecurityIDSource\":\"4\",\"LastPx\":\"122.255\",\"LastQty\":\"1990000\",\"OrderID\":\"116\",\"OrderQty\":\"1990000\",\"OrdStatus\":\"2\",\"SecurityID\":\"GB0032452392\",\"Side\":\"1\",\"Symbol\":\"[N/A]\",\"TransactTime\":\"20130321-15:21:23\",\"SettlDate\":\"20130322\",\"TradeDate\":\"20130321\",\"Issuer\":\"UK TSY 4 1/4% 2036\",\"NetMoney\":\"2436321.85\",\"ExecType\":\"F\",\"LeavesQty\":\"0\",\"NumDaysInterest\":\"15\",\"AccruedInterestAmt\":\"3447.35\",\"OrderQty2\":\"0\",\"SecondaryOrderID\":\"3739:20130321:50018:5\",\"CouponRate\":\"0.0425\",\"Factor\":\"1\",\"Yield\":\"0.0291371041\",\"Concession\":\"0\",\"GrossTradeAmt\":\"2432874.5\",\"PriceType\":\"1\",\"CountryOfIssue\":\"GB\",\"MaturityDate\":\"20360307\",\"NoPartyIDs\":[{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"1\",\"NoPartySubIDs\":[{\"PartySubID\":\"14\",\"PartySubIDType\":\"4\"}]},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"12\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"11\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"13\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"16\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"[HIDDEN]\",\"PartyRole\":\"36\"}]},\"Trailer\":{}}"; + List tagsToMask = [49,448]; + Assert.That(msg.ToJSON(dataDictionary: dd, convertEnumsToDescriptions: false, tagsToMask), Is.EqualTo(defaultMaskExpected)); + + // CASE 5: params (dd, false, tagsToMask, customMaskText) => tags converted to names, all instances of tags 49 (SenderCompID) and 448 (PartyID) are masked with custom mask text MASK + const string customMaskExpected = "{\"Header\":{\"BeginString\":\"FIX.4.4\",\"BodyLength\":\"638\",\"MsgSeqNum\":\"360\",\"MsgType\":\"8\",\"SenderCompID\":\"MASK\",\"SendingTime\":\"20130321-15:21:23\",\"TargetCompID\":\"THINKTSOX\",\"TargetSubID\":\"6804469\",\"DeliverToCompID\":\"ZERO\"},\"Body\":{\"AvgPx\":\"122.255\",\"ClOrdID\":\"61101189\",\"CumQty\":\"1990000\",\"Currency\":\"GBP\",\"ExecID\":\"VCON:20130321:50018:5:12\",\"SecurityIDSource\":\"4\",\"LastPx\":\"122.255\",\"LastQty\":\"1990000\",\"OrderID\":\"116\",\"OrderQty\":\"1990000\",\"OrdStatus\":\"2\",\"SecurityID\":\"GB0032452392\",\"Side\":\"1\",\"Symbol\":\"[N/A]\",\"TransactTime\":\"20130321-15:21:23\",\"SettlDate\":\"20130322\",\"TradeDate\":\"20130321\",\"Issuer\":\"UK TSY 4 1/4% 2036\",\"NetMoney\":\"2436321.85\",\"ExecType\":\"F\",\"LeavesQty\":\"0\",\"NumDaysInterest\":\"15\",\"AccruedInterestAmt\":\"3447.35\",\"OrderQty2\":\"0\",\"SecondaryOrderID\":\"3739:20130321:50018:5\",\"CouponRate\":\"0.0425\",\"Factor\":\"1\",\"Yield\":\"0.0291371041\",\"Concession\":\"0\",\"GrossTradeAmt\":\"2432874.5\",\"PriceType\":\"1\",\"CountryOfIssue\":\"GB\",\"MaturityDate\":\"20360307\",\"NoPartyIDs\":[{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"1\",\"NoPartySubIDs\":[{\"PartySubID\":\"14\",\"PartySubIDType\":\"4\"}]},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"12\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"11\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"13\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"16\"},{\"PartyIDSource\":\"D\",\"PartyID\":\"MASK\",\"PartyRole\":\"36\"}]},\"Trailer\":{}}"; + Assert.That(msg.ToJSON(dataDictionary: dd, convertEnumsToDescriptions: false, tagsToMask, "MASK"), Is.EqualTo(customMaskExpected)); + + // EXCEPTION CASE: params (null, true) => Exception + var ex = Assert.Throws(delegate { msg.ToJSON(null, true); })!; + Assert.That(ex.Message, + Does.Contain("Must be non-null if 'convertEnumsToDescriptions' is true. (Parameter 'dataDictionary')")); + } + + [Test] + public void ToJSONWithNewLineTest() + { + var dd = new QuickFix.DataDictionary.DataDictionary(); + dd.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "fix", "FIX44.xml")); + + var msg = new Message(); + msg.SetField(new QuickFix.Fields.Text("Some text.\r\n With some more text")); + + const string expected = "{\"Header\":{},\"Body\":{\"Text\":\"Some text.\\r\\n With some more text\"},\"Trailer\":{}}"; + Assert.That(msg.ToJSON(dd), Is.EqualTo(expected)); } } diff --git a/UnitTests/SessionIDTest.cs b/UnitTests/SessionIDTest.cs index 9239459ea..449a03e51 100644 --- a/UnitTests/SessionIDTest.cs +++ b/UnitTests/SessionIDTest.cs @@ -1,89 +1,88 @@ using NUnit.Framework; using QuickFix; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class SessionIDTest { - [TestFixture] - public class SessionIDTest + [SetUp] + public void Init() { - [SetUp] - public void Init() - { - } + } - [Test] - public void TestNoLocationSubOrQualifierConstructor() - { - SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET"); - Assert.That(sessionID.BeginString, Is.EqualTo("FIX.4.2")); - Assert.That(sessionID.SenderCompID, Is.EqualTo("SENDER")); - Assert.That(sessionID.SenderSubID, Is.EqualTo("")); - Assert.That(sessionID.SenderLocationID, Is.EqualTo("")); - Assert.That(sessionID.TargetCompID, Is.EqualTo("TARGET")); - Assert.That(sessionID.TargetSubID, Is.EqualTo("")); - Assert.That(sessionID.TargetLocationID, Is.EqualTo("")); - Assert.That(sessionID.SessionQualifier, Is.EqualTo("")); - } + [Test] + public void TestNoLocationSubOrQualifierConstructor() + { + SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET"); + Assert.That(sessionID.BeginString, Is.EqualTo("FIX.4.2")); + Assert.That(sessionID.SenderCompID, Is.EqualTo("SENDER")); + Assert.That(sessionID.SenderSubID, Is.EqualTo("")); + Assert.That(sessionID.SenderLocationID, Is.EqualTo("")); + Assert.That(sessionID.TargetCompID, Is.EqualTo("TARGET")); + Assert.That(sessionID.TargetSubID, Is.EqualTo("")); + Assert.That(sessionID.TargetLocationID, Is.EqualTo("")); + Assert.That(sessionID.SessionQualifier, Is.EqualTo("")); + } - [Test] - public void TestNoLocationConstructor() - { - SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "TARGET", "TARGETSUB"); - Assert.That(sessionID.BeginString, Is.EqualTo("FIX.4.2")); - Assert.That(sessionID.SenderCompID, Is.EqualTo("SENDER")); - Assert.That(sessionID.SenderSubID, Is.EqualTo("SENDERSUB")); - Assert.That(sessionID.SenderLocationID, Is.EqualTo("")); - Assert.That(sessionID.TargetCompID, Is.EqualTo("TARGET")); - Assert.That(sessionID.TargetSubID, Is.EqualTo("TARGETSUB")); - Assert.That(sessionID.TargetLocationID, Is.EqualTo("")); - Assert.That(sessionID.SessionQualifier, Is.EqualTo("")); - } + [Test] + public void TestNoLocationConstructor() + { + SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "TARGET", "TARGETSUB"); + Assert.That(sessionID.BeginString, Is.EqualTo("FIX.4.2")); + Assert.That(sessionID.SenderCompID, Is.EqualTo("SENDER")); + Assert.That(sessionID.SenderSubID, Is.EqualTo("SENDERSUB")); + Assert.That(sessionID.SenderLocationID, Is.EqualTo("")); + Assert.That(sessionID.TargetCompID, Is.EqualTo("TARGET")); + Assert.That(sessionID.TargetSubID, Is.EqualTo("TARGETSUB")); + Assert.That(sessionID.TargetLocationID, Is.EqualTo("")); + Assert.That(sessionID.SessionQualifier, Is.EqualTo("")); + } - [Test] - public void TestNoLocationOrSubConstructor() - { - SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET", "QUALIFIER"); - Assert.That(sessionID.BeginString, Is.EqualTo("FIX.4.2")); - Assert.That(sessionID.SenderCompID, Is.EqualTo("SENDER")); - Assert.That(sessionID.SenderSubID, Is.EqualTo("")); - Assert.That(sessionID.SenderLocationID, Is.EqualTo("")); - Assert.That(sessionID.TargetCompID, Is.EqualTo("TARGET")); - Assert.That(sessionID.TargetSubID, Is.EqualTo("")); - Assert.That(sessionID.TargetLocationID, Is.EqualTo("")); - Assert.That(sessionID.SessionQualifier, Is.EqualTo("QUALIFIER")); - } + [Test] + public void TestNoLocationOrSubConstructor() + { + SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET", "QUALIFIER"); + Assert.That(sessionID.BeginString, Is.EqualTo("FIX.4.2")); + Assert.That(sessionID.SenderCompID, Is.EqualTo("SENDER")); + Assert.That(sessionID.SenderSubID, Is.EqualTo("")); + Assert.That(sessionID.SenderLocationID, Is.EqualTo("")); + Assert.That(sessionID.TargetCompID, Is.EqualTo("TARGET")); + Assert.That(sessionID.TargetSubID, Is.EqualTo("")); + Assert.That(sessionID.TargetLocationID, Is.EqualTo("")); + Assert.That(sessionID.SessionQualifier, Is.EqualTo("QUALIFIER")); + } - [Test] - public void TestAllFieldsConstructor() - { - SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "SENDERLOC", "TARGET", "TARGETSUB", "TARGETLOC", "QUALIFIER"); - Assert.That(sessionID.BeginString, Is.EqualTo("FIX.4.2")); - Assert.That(sessionID.SenderCompID, Is.EqualTo("SENDER")); - Assert.That(sessionID.SenderSubID, Is.EqualTo("SENDERSUB")); - Assert.That(sessionID.SenderLocationID, Is.EqualTo("SENDERLOC")); - Assert.That(sessionID.TargetCompID, Is.EqualTo("TARGET")); - Assert.That(sessionID.TargetSubID, Is.EqualTo("TARGETSUB")); - Assert.That(sessionID.TargetLocationID, Is.EqualTo("TARGETLOC")); - Assert.That(sessionID.SessionQualifier, Is.EqualTo("QUALIFIER")); - } + [Test] + public void TestAllFieldsConstructor() + { + SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "SENDERLOC", "TARGET", "TARGETSUB", "TARGETLOC", "QUALIFIER"); + Assert.That(sessionID.BeginString, Is.EqualTo("FIX.4.2")); + Assert.That(sessionID.SenderCompID, Is.EqualTo("SENDER")); + Assert.That(sessionID.SenderSubID, Is.EqualTo("SENDERSUB")); + Assert.That(sessionID.SenderLocationID, Is.EqualTo("SENDERLOC")); + Assert.That(sessionID.TargetCompID, Is.EqualTo("TARGET")); + Assert.That(sessionID.TargetSubID, Is.EqualTo("TARGETSUB")); + Assert.That(sessionID.TargetLocationID, Is.EqualTo("TARGETLOC")); + Assert.That(sessionID.SessionQualifier, Is.EqualTo("QUALIFIER")); + } - [Test] - public void TestToString() - { - SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET"); - Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER->TARGET")); + [Test] + public void TestToString() + { + SessionID sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET"); + Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER->TARGET")); - sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET", "QUALIFIER"); - Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER->TARGET:QUALIFIER")); + sessionID = new SessionID("FIX.4.2", "SENDER", "TARGET", "QUALIFIER"); + Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER->TARGET:QUALIFIER")); - sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "TARGET", "TARGETSUB"); - Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER/SENDERSUB->TARGET/TARGETSUB")); + sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "TARGET", "TARGETSUB"); + Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER/SENDERSUB->TARGET/TARGETSUB")); - sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "SENDERLOC", "TARGET", "TARGETSUB", "TARGETLOC"); - Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER/SENDERSUB/SENDERLOC->TARGET/TARGETSUB/TARGETLOC")); + sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "SENDERLOC", "TARGET", "TARGETSUB", "TARGETLOC"); + Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER/SENDERSUB/SENDERLOC->TARGET/TARGETSUB/TARGETLOC")); - sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "SENDERLOC", "TARGET", "TARGETSUB", "TARGETLOC", "QUALIFIER"); - Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER/SENDERSUB/SENDERLOC->TARGET/TARGETSUB/TARGETLOC:QUALIFIER")); - } + sessionID = new SessionID("FIX.4.2", "SENDER", "SENDERSUB", "SENDERLOC", "TARGET", "TARGETSUB", "TARGETLOC", "QUALIFIER"); + Assert.That(sessionID.ToString(), Is.EqualTo("FIX.4.2:SENDER/SENDERSUB/SENDERLOC->TARGET/TARGETSUB/TARGETLOC:QUALIFIER")); } } diff --git a/UnitTests/SessionScheduleTests.cs b/UnitTests/SessionScheduleTests.cs index 1db2883a6..fb7861bf3 100755 --- a/UnitTests/SessionScheduleTests.cs +++ b/UnitTests/SessionScheduleTests.cs @@ -3,710 +3,709 @@ using NUnit.Framework; using QuickFix; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class SessionScheduleTests { - [TestFixture] - public class SessionScheduleTests + #region Properties + /// + /// Windows/*nix-agnostic time zone ID + /// (because it would be too easy if they could settle on a standard list of ids, right?) + /// + private static string EasternStandardTimeZoneId { - #region Properties - /// - /// Windows/*nix-agnostic time zone ID - /// (because it would be too easy if they could settle on a standard list of ids, right?) - /// - private static string EasternStandardTimeZoneId + get { - get - { - return TimeZoneInfo.GetSystemTimeZones().Any(x => x.Id == "Eastern Standard Time") - ? "Eastern Standard Time" - : "America/New_York"; - } + return TimeZoneInfo.GetSystemTimeZones().Any(x => x.Id == "Eastern Standard Time") + ? "Eastern Standard Time" + : "America/New_York"; } + } - /// - /// Windows/*nix-agnostic time zone ID - /// (because it would be too easy if they could settle on a standard list of ids, right?) - /// - private static string PacificStandardTimeZoneId + /// + /// Windows/*nix-agnostic time zone ID + /// (because it would be too easy if they could settle on a standard list of ids, right?) + /// + private static string PacificStandardTimeZoneId + { + get { - get - { - return TimeZoneInfo.GetSystemTimeZones().Any(x => x.Id == "Pacific Standard Time") - ? "Pacific Standard Time" - : "America/Los_Angeles"; - } + return TimeZoneInfo.GetSystemTimeZones().Any(x => x.Id == "Pacific Standard Time") + ? "Pacific Standard Time" + : "America/Los_Angeles"; } - #endregion + } + #endregion - private const string DtFmt = "yyyyMMdd-HH:mm:ss"; + private const string DtFmt = "yyyyMMdd-HH:mm:ss"; - [Test] - public void TestCtor_BasicDailySchedule() - { - SettingsDictionary settings = new SettingsDictionary(); - Exception ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; - Assert.That(ex.Message, Does.Contain("No value for key: StartTime")); + [Test] + public void TestCtor_BasicDailySchedule() + { + SettingsDictionary settings = new SettingsDictionary(); + Exception ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; + Assert.That(ex.Message, Does.Contain("No value for key: StartTime")); - settings.SetString(SessionSettings.START_TIME, "00:00:00"); - ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; - Assert.That(ex.Message, Does.Contain("No value for key: EndTime")); + settings.SetString(SessionSettings.START_TIME, "00:00:00"); + ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; + Assert.That(ex.Message, Does.Contain("No value for key: EndTime")); - settings.SetString(SessionSettings.END_TIME, "00:0blkajsdf"); - ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; - Assert.That(ex.Message, Does.Contain("String '00:0blkajsdf' was not recognized as a valid TimeSpan")); + settings.SetString(SessionSettings.END_TIME, "00:0blkajsdf"); + ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; + Assert.That(ex.Message, Does.Contain("String '00:0blkajsdf' was not recognized as a valid TimeSpan")); - settings.SetString(SessionSettings.END_TIME, "00:00:00"); - Assert.DoesNotThrow(delegate { new SessionSchedule(settings); }); - } + settings.SetString(SessionSettings.END_TIME, "00:00:00"); + Assert.DoesNotThrow(delegate { new SessionSchedule(settings); }); + } - [Test] - public void TestCtor_WeeklongSession() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "00:00:00"); - settings.SetString(SessionSettings.END_TIME, "00:00:00"); + [Test] + public void TestCtor_WeeklongSession() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "00:00:00"); + settings.SetString(SessionSettings.END_TIME, "00:00:00"); - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Thursday); - Exception ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; - Assert.That(ex.Message, Does.Contain("StartDay used without EndDay")); + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Thursday); + Exception ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; + Assert.That(ex.Message, Does.Contain("StartDay used without EndDay")); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); - Assert.DoesNotThrow(delegate { new SessionSchedule(settings); }); - } + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); + Assert.DoesNotThrow(delegate { new SessionSchedule(settings); }); + } - [Test] - public void TestCtor_WeekdaysSession() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.WEEKDAYS, "Sun,Tue,Fri"); + [Test] + public void TestCtor_WeekdaysSession() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.WEEKDAYS, "Sun,Tue,Fri"); - Exception ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; - Assert.That(ex.Message, Does.Contain("No value for key: StartTime")); + Exception ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; + Assert.That(ex.Message, Does.Contain("No value for key: StartTime")); - settings.SetString(SessionSettings.START_TIME, "00:00:00"); - settings.SetString(SessionSettings.END_TIME, "00:00:00"); - Assert.DoesNotThrow(delegate { new SessionSchedule(settings); }); + settings.SetString(SessionSettings.START_TIME, "00:00:00"); + settings.SetString(SessionSettings.END_TIME, "00:00:00"); + Assert.DoesNotThrow(delegate { new SessionSchedule(settings); }); - settings.SetString(SessionSettings.START_DAY, "Tue"); - ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; - Assert.That(ex.Message, Does.Contain("StartDay/EndDay are not compatible with 'Weekdays' setting")); - } + settings.SetString(SessionSettings.START_DAY, "Tue"); + ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; + Assert.That(ex.Message, Does.Contain("StartDay/EndDay are not compatible with 'Weekdays' setting")); + } - [Test] - public void TestCtor_NonStopSession() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetBool(SessionSettings.NON_STOP_SESSION, true); - Assert.DoesNotThrow(delegate { new SessionSchedule(settings); }); - - settings.SetString(SessionSettings.START_DAY, "Monday"); - Exception ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; - Assert.That(ex.Message, Does.Contain("NonStopSession is not compatible with StartDay/EndDay and StartTime/EndTime")); - - settings = new SettingsDictionary(); - settings.SetBool(SessionSettings.NON_STOP_SESSION, true); - settings.SetString(SessionSettings.START_TIME, "05:00:00"); - ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; - Assert.That(ex.Message, Does.Contain("NonStopSession is not compatible with StartDay/EndDay and StartTime/EndTime")); - } + [Test] + public void TestCtor_NonStopSession() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetBool(SessionSettings.NON_STOP_SESSION, true); + Assert.DoesNotThrow(delegate { new SessionSchedule(settings); }); + + settings.SetString(SessionSettings.START_DAY, "Monday"); + Exception ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; + Assert.That(ex.Message, Does.Contain("NonStopSession is not compatible with StartDay/EndDay and StartTime/EndTime")); + + settings = new SettingsDictionary(); + settings.SetBool(SessionSettings.NON_STOP_SESSION, true); + settings.SetString(SessionSettings.START_TIME, "05:00:00"); + ex = Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); })!; + Assert.That(ex.Message, Does.Contain("NonStopSession is not compatible with StartDay/EndDay and StartTime/EndTime")); + } - [Test] - public void TestDailyIsSessionTimeAllDay() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "00:00:00"); - settings.SetString(SessionSettings.END_TIME, "00:00:00"); + [Test] + public void TestDailyIsSessionTimeAllDay() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "00:00:00"); + settings.SetString(SessionSettings.END_TIME, "00:00:00"); - SessionSchedule sched = new SessionSchedule(settings); + SessionSchedule sched = new SessionSchedule(settings); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 0, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 23, 59, 59, DateTimeKind.Utc)), Is.True); - } + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 0, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 23, 59, 59, DateTimeKind.Utc)), Is.True); + } - [Test] - public void TestWeeklySessionSameDayAllWeek() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "00:00:00"); - settings.SetString(SessionSettings.END_TIME, "00:00:00"); - - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Monday); - SessionSchedule sched = new SessionSchedule(settings); - - //a sunday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 23, 59, 59, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 0, 0, 0, DateTimeKind.Utc)), Is.True); - - //a monday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 23, 59, 59, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 0, 0, DateTimeKind.Utc)), Is.True); - - //a tuesday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 0, 0, DateTimeKind.Utc)), Is.True); - } + [Test] + public void TestWeeklySessionSameDayAllWeek() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "00:00:00"); + settings.SetString(SessionSettings.END_TIME, "00:00:00"); + + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Monday); + SessionSchedule sched = new SessionSchedule(settings); + + //a sunday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 23, 59, 59, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 0, 0, 0, DateTimeKind.Utc)), Is.True); + + //a monday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 23, 59, 59, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 0, 0, DateTimeKind.Utc)), Is.True); + + //a tuesday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 0, 0, DateTimeKind.Utc)), Is.True); + } - [Test] - public void TestWeeklySessionSameDayMostWeek() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "05:00:00"); - settings.SetString(SessionSettings.END_TIME, "00:00:00"); - - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Monday); - SessionSchedule sched = new SessionSchedule(settings); - - //a sunday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 23, 59, 59, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 0, 0, 0, DateTimeKind.Utc)), Is.True); - - //a monday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 0, 1, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 4, 0, 1, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 23, 59, 59, DateTimeKind.Utc)), Is.True); - - //a tuesday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 0, 0, DateTimeKind.Utc)), Is.True); - } + [Test] + public void TestWeeklySessionSameDayMostWeek() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "05:00:00"); + settings.SetString(SessionSettings.END_TIME, "00:00:00"); + + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Monday); + SessionSchedule sched = new SessionSchedule(settings); + + //a sunday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 23, 59, 59, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 0, 0, 0, DateTimeKind.Utc)), Is.True); + + //a monday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 0, 1, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 4, 0, 1, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 23, 59, 59, DateTimeKind.Utc)), Is.True); + + //a tuesday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 0, 0, DateTimeKind.Utc)), Is.True); + } - [Test] - public void TestWeeklySessionSameDayOneDay() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "00:00:00"); - settings.SetString(SessionSettings.END_TIME, "05:00:00"); - - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Monday); - SessionSchedule sched = new SessionSchedule(settings); - - //a sunday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 23, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 0, 0, 0, DateTimeKind.Utc)), Is.False); - - //a monday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 0, 1, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 4, 0, 1, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 6, 59, 59, DateTimeKind.Utc)), Is.False); - - //a tuesday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 0, 0, DateTimeKind.Utc)), Is.False); - } + [Test] + public void TestWeeklySessionSameDayOneDay() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "00:00:00"); + settings.SetString(SessionSettings.END_TIME, "05:00:00"); + + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Monday); + SessionSchedule sched = new SessionSchedule(settings); + + //a sunday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 23, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 0, 0, 0, DateTimeKind.Utc)), Is.False); + + //a monday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 0, 1, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 4, 0, 1, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 6, 59, 59, DateTimeKind.Utc)), Is.False); + + //a tuesday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 0, 0, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestWeeklySessionMultiDay() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "00:00:00"); - settings.SetString(SessionSettings.END_TIME, "00:00:00"); + [Test] + public void TestWeeklySessionMultiDay() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "00:00:00"); + settings.SetString(SessionSettings.END_TIME, "00:00:00"); - //only on monday-thur (note end time) - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); + //only on monday-thur (note end time) + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); - SessionSchedule sched = new SessionSchedule(settings); + SessionSchedule sched = new SessionSchedule(settings); - //a monday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 0, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 9, 43, 0, DateTimeKind.Utc)), Is.True); + //a monday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 0, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 9, 43, 0, DateTimeKind.Utc)), Is.True); - // a thursday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 20, 23, 59, 59, DateTimeKind.Utc)), Is.True); + // a thursday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 20, 23, 59, 59, DateTimeKind.Utc)), Is.True); - //a fri, sat, sun - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 23, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 0, 0, 0, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 9, 43, 0, DateTimeKind.Utc)), Is.False); - } + //a fri, sat, sun + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 23, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 0, 0, 0, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 9, 43, 0, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestWeeklySessionMultiDayOverlap() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "00:00:00"); - settings.SetString(SessionSettings.END_TIME, "00:00:00"); + [Test] + public void TestWeeklySessionMultiDayOverlap() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "00:00:00"); + settings.SetString(SessionSettings.END_TIME, "00:00:00"); - //only on wed-sunday night - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Wednesday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Monday); + //only on wed-sunday night + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Wednesday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Monday); - SessionSchedule sched = new SessionSchedule(settings); + SessionSchedule sched = new SessionSchedule(settings); - //wed-monday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 19, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 20, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 9, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 9, 43, 0, DateTimeKind.Utc)), Is.True); + //wed-monday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 19, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 20, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 9, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 16, 9, 43, 0, DateTimeKind.Utc)), Is.True); - //monday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 9, 43, 0, DateTimeKind.Utc)), Is.False); + //monday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 9, 43, 0, DateTimeKind.Utc)), Is.False); - //tuesday - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.False); - } + //tuesday + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 9, 43, 0, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestWeeklySessionMultiDayHours() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "07:00:00"); - settings.SetString(SessionSettings.END_TIME, "15:00:00"); - - //only on monday-fri - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); - - SessionSchedule sched = new SessionSchedule(settings); - - //Monday Scenarios - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 6, 59, 0, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 7, 30, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 15, 30, 0, DateTimeKind.Utc)), Is.True); - - //Midweek Scenarios - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 19, 6, 59, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 19, 7, 30, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 19, 15, 30, 0, DateTimeKind.Utc)), Is.True); - - //Friday Scenarios - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 6, 59, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 7, 30, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 15, 30, 0, DateTimeKind.Utc)), Is.False); - - //Weekend - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 6, 59, 0, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 7, 30, 0, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 15, 30, 0, DateTimeKind.Utc)), Is.False); - } + [Test] + public void TestWeeklySessionMultiDayHours() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "07:00:00"); + settings.SetString(SessionSettings.END_TIME, "15:00:00"); + + //only on monday-fri + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); + + SessionSchedule sched = new SessionSchedule(settings); + + //Monday Scenarios + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 6, 59, 0, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 7, 30, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 15, 30, 0, DateTimeKind.Utc)), Is.True); + + //Midweek Scenarios + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 19, 6, 59, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 19, 7, 30, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 19, 15, 30, 0, DateTimeKind.Utc)), Is.True); + + //Friday Scenarios + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 6, 59, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 7, 30, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 15, 30, 0, DateTimeKind.Utc)), Is.False); + + //Weekend + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 6, 59, 0, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 7, 30, 0, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 15, 30, 0, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestWeeklySessionMultiDayHoursOverlap() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "15:00:00"); - settings.SetString(SessionSettings.END_TIME, "07:00:00"); + [Test] + public void TestWeeklySessionMultiDayHoursOverlap() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "15:00:00"); + settings.SetString(SessionSettings.END_TIME, "07:00:00"); - //only on monday-fri - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); + //only on monday-fri + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); - SessionSchedule sched = new SessionSchedule(settings); + SessionSchedule sched = new SessionSchedule(settings); - //weekdays - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 15, 30, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 6, 30, 0, DateTimeKind.Utc)), Is.False, "foo"); + //weekdays + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 15, 30, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 6, 30, 0, DateTimeKind.Utc)), Is.False, "foo"); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 5, 30, 59, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 15, 30, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 6, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 7, 00, 1, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 15, 30, 0, DateTimeKind.Utc)), Is.False); - } + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 5, 30, 59, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 21, 15, 30, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 6, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 7, 00, 1, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 22, 15, 30, 0, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestDailyIsSessionTime() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "00:12:00"); - settings.SetString(SessionSettings.END_TIME, "06:00:23"); + [Test] + public void TestDailyIsSessionTime() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "00:12:00"); + settings.SetString(SessionSettings.END_TIME, "06:00:23"); - SessionSchedule sched = new SessionSchedule(settings); + SessionSchedule sched = new SessionSchedule(settings); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 12, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 5, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 6, 0, 23, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 0, 12, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 5, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 6, 0, 23, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 11, 0, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 6, 0, 24, DateTimeKind.Utc)), Is.False); - } + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 11, 0, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 6, 0, 24, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestDailyIsSessionTimeWrapAround() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "06:00:23"); - settings.SetString(SessionSettings.END_TIME, "00:12:00"); + [Test] + public void TestDailyIsSessionTimeWrapAround() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "06:00:23"); + settings.SetString(SessionSettings.END_TIME, "00:12:00"); - SessionSchedule sched = new SessionSchedule(settings); + SessionSchedule sched = new SessionSchedule(settings); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 6, 0, 23, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 8, 43, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 12, 00, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 6, 0, 23, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 8, 43, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 12, 00, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 12, 1, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 6, 0, 22, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 0, 12, 1, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 18, 6, 0, 22, DateTimeKind.Utc)), Is.False); - } + } - [Test] - public void TestInvalidTimeZone() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "06:00:23"); - settings.SetString(SessionSettings.END_TIME, "00:12:00"); - settings.SetString(SessionSettings.TIME_ZONE, "Doh"); + [Test] + public void TestInvalidTimeZone() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "06:00:23"); + settings.SetString(SessionSettings.END_TIME, "00:12:00"); + settings.SetString(SessionSettings.TIME_ZONE, "Doh"); - Assert.Throws(typeof(TimeZoneNotFoundException), delegate { new SessionSchedule(settings); }); - } + Assert.Throws(typeof(TimeZoneNotFoundException), delegate { new SessionSchedule(settings); }); + } - [Test] - public void TestLocalTimeTimeZoneConflict() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "06:00:23"); - settings.SetString(SessionSettings.END_TIME, "00:12:00"); - settings.SetString(SessionSettings.TIME_ZONE, "Doh"); - settings.SetString(SessionSettings.USE_LOCAL_TIME, "Y"); - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); - - Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); }); - } + [Test] + public void TestLocalTimeTimeZoneConflict() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "06:00:23"); + settings.SetString(SessionSettings.END_TIME, "00:12:00"); + settings.SetString(SessionSettings.TIME_ZONE, "Doh"); + settings.SetString(SessionSettings.USE_LOCAL_TIME, "Y"); + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); + + Assert.Throws(typeof(ConfigError), delegate { new SessionSchedule(settings); }); + } - [Test] - public void TestTimeZone() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "09:30:00"); - settings.SetString(SessionSettings.END_TIME, "16:00:00"); - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); + [Test] + public void TestTimeZone() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "09:30:00"); + settings.SetString(SessionSettings.END_TIME, "16:00:00"); + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); - SessionSchedule sched = new SessionSchedule(settings); + SessionSchedule sched = new SessionSchedule(settings); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 13, 29, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 13, 30, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 20, 0, 0, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 20, 0, 1, DateTimeKind.Utc)), Is.False); - } + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 13, 29, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 13, 30, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 20, 0, 0, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2011, 10, 17, 20, 0, 1, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestNextEndTime_takesUtcOnly() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "09:30:00"); - settings.SetString(SessionSettings.END_TIME, "16:00:00"); - SessionSchedule sched = new SessionSchedule(settings); + [Test] + public void TestNextEndTime_takesUtcOnly() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "09:30:00"); + settings.SetString(SessionSettings.END_TIME, "16:00:00"); + SessionSchedule sched = new SessionSchedule(settings); - DateTime local = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Local); - DateTime none = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); + DateTime local = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Local); + DateTime none = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); - Assert.Throws(delegate { sched.NextEndTime(local); }); - Assert.Throws(delegate { sched.NextEndTime(none); }); - } + Assert.Throws(delegate { sched.NextEndTime(local); }); + Assert.Throws(delegate { sched.NextEndTime(none); }); + } - [Test] - public void TestNextEndTime_Daily() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "09:30:00"); - settings.SetString(SessionSettings.END_TIME, "16:00:00"); - SessionSchedule sched = new SessionSchedule(settings); - - Assert.That(sched.NextEndTime(new DateTime(2012, 10, 18, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121018-16:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 10, 18, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121018-16:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 10, 18, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121019-16:00:00")); - - // ========== - // Settings file is specified in a zone (est, -5) - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-5 - sched = new SessionSchedule(settings); - - Assert.That(sched.NextEndTime(new DateTime(2012, 12, 18, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121218-11:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 12, 18, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121218-11:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 12, 18, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121219-11:00:00")); - - // ========== - // Time zone during Daylight Savings - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "05:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "12:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-4 for DST - sched = new SessionSchedule(settings); - - Assert.That(sched.NextEndTime(new DateTime(2012, 06, 18, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20120618-12:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 06, 18, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20120618-12:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 06, 18, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20120619-12:00:00")); - } + [Test] + public void TestNextEndTime_Daily() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "09:30:00"); + settings.SetString(SessionSettings.END_TIME, "16:00:00"); + SessionSchedule sched = new SessionSchedule(settings); + + Assert.That(sched.NextEndTime(new DateTime(2012, 10, 18, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121018-16:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 10, 18, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121018-16:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 10, 18, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121019-16:00:00")); + + // ========== + // Settings file is specified in a zone (est, -5) + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-5 + sched = new SessionSchedule(settings); + + Assert.That(sched.NextEndTime(new DateTime(2012, 12, 18, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121218-11:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 12, 18, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121218-11:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 12, 18, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121219-11:00:00")); + + // ========== + // Time zone during Daylight Savings + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "05:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "12:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-4 for DST + sched = new SessionSchedule(settings); + + Assert.That(sched.NextEndTime(new DateTime(2012, 06, 18, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20120618-12:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 06, 18, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20120618-12:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 06, 18, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20120619-12:00:00")); + } - [Test] - public void TestNextEndTime_Weekly() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "09:30:00"); - settings.SetString(SessionSettings.END_TIME, "16:00:00"); - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); - SessionSchedule sched = new SessionSchedule(settings); - - // Oct 15 and 22 are Mondays, 19 and 26 are Fridays - Assert.That(sched.NextEndTime(new DateTime(2012, 10, 19, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121019-16:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 10, 19, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121019-16:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 10, 19, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121026-16:00:00")); - - // ========== - // Settings file is specified in a zone (est, -5) - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-5 - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); - sched = new SessionSchedule(settings); - - // Dec 14 and 21 are Fridays - Assert.That(sched.NextEndTime(new DateTime(2012, 12, 14, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121214-11:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 12, 14, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121214-11:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 12, 14, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20121221-11:00:00")); - - // ========== - // Time zone during Daylight Savings - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "05:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "12:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-4 for DST - settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); - settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); - sched = new SessionSchedule(settings); - - // June 15 and 22 are Fridays - Assert.That(sched.NextEndTime(new DateTime(2012, 06, 15, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20120615-12:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 06, 15, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20120615-12:00:00")); - Assert.That(sched.NextEndTime(new DateTime(2012, 06, 15, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), - Is.EqualTo("20120622-12:00:00")); - } + [Test] + public void TestNextEndTime_Weekly() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "09:30:00"); + settings.SetString(SessionSettings.END_TIME, "16:00:00"); + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); + SessionSchedule sched = new SessionSchedule(settings); + + // Oct 15 and 22 are Mondays, 19 and 26 are Fridays + Assert.That(sched.NextEndTime(new DateTime(2012, 10, 19, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121019-16:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 10, 19, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121019-16:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 10, 19, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121026-16:00:00")); + + // ========== + // Settings file is specified in a zone (est, -5) + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-5 + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); + sched = new SessionSchedule(settings); + + // Dec 14 and 21 are Fridays + Assert.That(sched.NextEndTime(new DateTime(2012, 12, 14, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121214-11:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 12, 14, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121214-11:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 12, 14, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20121221-11:00:00")); + + // ========== + // Time zone during Daylight Savings + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "05:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "12:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-4 for DST + settings.SetDay(SessionSettings.START_DAY, DayOfWeek.Monday); + settings.SetDay(SessionSettings.END_DAY, DayOfWeek.Friday); + sched = new SessionSchedule(settings); + + // June 15 and 22 are Fridays + Assert.That(sched.NextEndTime(new DateTime(2012, 06, 15, 15, 59, 59, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20120615-12:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 06, 15, 16, 00, 00, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20120615-12:00:00")); + Assert.That(sched.NextEndTime(new DateTime(2012, 06, 15, 16, 00, 01, DateTimeKind.Utc)).ToString(DtFmt), + Is.EqualTo("20120622-12:00:00")); + } - [Test] - public void TestIsNewSession_takesUtcOnly() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "09:30:00"); - settings.SetString(SessionSettings.END_TIME, "16:00:00"); - SessionSchedule sched = new SessionSchedule(settings); - - DateTime local = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Local); - DateTime utc = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Utc); - DateTime none = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); - - Assert.Throws(delegate { sched.IsNewSession(local, utc); }); - Assert.Throws(delegate { sched.IsNewSession(utc, local); }); - Assert.Throws(delegate { sched.IsNewSession(none, utc); }); - Assert.Throws(delegate { sched.IsNewSession(utc, none); }); - } + [Test] + public void TestIsNewSession_takesUtcOnly() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "09:30:00"); + settings.SetString(SessionSettings.END_TIME, "16:00:00"); + SessionSchedule sched = new SessionSchedule(settings); + + DateTime local = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Local); + DateTime utc = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Utc); + DateTime none = new DateTime(2001, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); + + Assert.Throws(delegate { sched.IsNewSession(local, utc); }); + Assert.Throws(delegate { sched.IsNewSession(utc, local); }); + Assert.Throws(delegate { sched.IsNewSession(none, utc); }); + Assert.Throws(delegate { sched.IsNewSession(utc, none); }); + } - [Test] - public void TestIsNewSession_Daily() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "09:30:00"); - settings.SetString(SessionSettings.END_TIME, "16:00:00"); - SessionSchedule sched = new SessionSchedule(settings); - - Assert.That(sched.IsNewSession( - new DateTime(2012, 10, 18, 15, 59, 58, DateTimeKind.Utc), - new DateTime(2012, 10, 18, 15, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsNewSession( - new DateTime(2012, 10, 18, 15, 59, 59, DateTimeKind.Utc), - new DateTime(2012, 10, 18, 16, 00, 00, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsNewSession( - new DateTime(2012, 10, 18, 16, 00, 00, DateTimeKind.Utc), - new DateTime(2012, 10, 18, 16, 00, 01, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsNewSession( - new DateTime(2012, 10, 18, 16, 00, 01, DateTimeKind.Utc), - new DateTime(2012, 10, 18, 16, 00, 02, DateTimeKind.Utc)), Is.False); - - // ========== - // Settings file is specified in a zone (est, -5) - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-5 - sched = new SessionSchedule(settings); - - Assert.That(sched.IsNewSession( - new DateTime(2012, 12, 18, 15, 59, 58, DateTimeKind.Utc), - new DateTime(2012, 12, 18, 15, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsNewSession( - new DateTime(2012, 12, 18, 15, 59, 59, DateTimeKind.Utc), - new DateTime(2012, 12, 18, 16, 00, 00, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsNewSession( - new DateTime(2012, 12, 18, 16, 00, 00, DateTimeKind.Utc), - new DateTime(2012, 12, 18, 16, 00, 01, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsNewSession( - new DateTime(2012, 12, 18, 16, 00, 01, DateTimeKind.Utc), - new DateTime(2012, 12, 18, 16, 00, 02, DateTimeKind.Utc)), Is.False); - - // ========== - // Time zone during Daylight savings - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "05:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "12:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-4 during dst - sched = new SessionSchedule(settings); - - Assert.That(sched.IsNewSession( - new DateTime(2012, 06, 18, 15, 59, 58, DateTimeKind.Utc), - new DateTime(2012, 06, 18, 15, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsNewSession( - new DateTime(2012, 06, 18, 15, 59, 59, DateTimeKind.Utc), - new DateTime(2012, 06, 18, 16, 00, 00, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsNewSession( - new DateTime(2012, 06, 18, 16, 00, 00, DateTimeKind.Utc), - new DateTime(2012, 06, 18, 16, 00, 01, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsNewSession( - new DateTime(2012, 06, 18, 16, 00, 01, DateTimeKind.Utc), - new DateTime(2012, 06, 18, 16, 00, 02, DateTimeKind.Utc)), Is.False); - } + [Test] + public void TestIsNewSession_Daily() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "09:30:00"); + settings.SetString(SessionSettings.END_TIME, "16:00:00"); + SessionSchedule sched = new SessionSchedule(settings); + + Assert.That(sched.IsNewSession( + new DateTime(2012, 10, 18, 15, 59, 58, DateTimeKind.Utc), + new DateTime(2012, 10, 18, 15, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsNewSession( + new DateTime(2012, 10, 18, 15, 59, 59, DateTimeKind.Utc), + new DateTime(2012, 10, 18, 16, 00, 00, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsNewSession( + new DateTime(2012, 10, 18, 16, 00, 00, DateTimeKind.Utc), + new DateTime(2012, 10, 18, 16, 00, 01, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsNewSession( + new DateTime(2012, 10, 18, 16, 00, 01, DateTimeKind.Utc), + new DateTime(2012, 10, 18, 16, 00, 02, DateTimeKind.Utc)), Is.False); + + // ========== + // Settings file is specified in a zone (est, -5) + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-5 + sched = new SessionSchedule(settings); + + Assert.That(sched.IsNewSession( + new DateTime(2012, 12, 18, 15, 59, 58, DateTimeKind.Utc), + new DateTime(2012, 12, 18, 15, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsNewSession( + new DateTime(2012, 12, 18, 15, 59, 59, DateTimeKind.Utc), + new DateTime(2012, 12, 18, 16, 00, 00, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsNewSession( + new DateTime(2012, 12, 18, 16, 00, 00, DateTimeKind.Utc), + new DateTime(2012, 12, 18, 16, 00, 01, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsNewSession( + new DateTime(2012, 12, 18, 16, 00, 01, DateTimeKind.Utc), + new DateTime(2012, 12, 18, 16, 00, 02, DateTimeKind.Utc)), Is.False); + + // ========== + // Time zone during Daylight savings + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "05:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "12:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-4 during dst + sched = new SessionSchedule(settings); + + Assert.That(sched.IsNewSession( + new DateTime(2012, 06, 18, 15, 59, 58, DateTimeKind.Utc), + new DateTime(2012, 06, 18, 15, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsNewSession( + new DateTime(2012, 06, 18, 15, 59, 59, DateTimeKind.Utc), + new DateTime(2012, 06, 18, 16, 00, 00, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsNewSession( + new DateTime(2012, 06, 18, 16, 00, 00, DateTimeKind.Utc), + new DateTime(2012, 06, 18, 16, 00, 01, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsNewSession( + new DateTime(2012, 06, 18, 16, 00, 01, DateTimeKind.Utc), + new DateTime(2012, 06, 18, 16, 00, 02, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestAdjustDateTime() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "09:30:00"); - settings.SetString(SessionSettings.END_TIME, "16:00:00"); - SessionSchedule sched = new SessionSchedule(settings); - - // 1) reject if param is not utc - Assert.Throws( - delegate { sched.AdjustUtcDateTime(new DateTime(2012, 10, 18, 12, 00, 00, DateTimeKind.Local)); }); - Assert.Throws( - delegate { sched.AdjustUtcDateTime(new DateTime(2012, 10, 18, 12, 00, 00, DateTimeKind.Unspecified)); }); - - // 2) if settings is UTC, don't convert - DateTime d2 = new DateTime(2013, 01, 15, 12, 00, 00, DateTimeKind.Utc); - Assert.That(sched.AdjustUtcDateTime(d2), Is.EqualTo(d2)); - - // 3) if settings has a TimeZone, convert to TimeZone - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-5 - sched = new SessionSchedule(settings); - - DateTime d3 = new DateTime(2013, 01, 15, 03, 00, 00, DateTimeKind.Utc); - DateTime d3expected = new DateTime(2013, 01, 14, 22, 00, 00, DateTimeKind.Unspecified); - DateTime d3actual = sched.AdjustUtcDateTime(d3); - Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d3expected, d3actual); - - // now with Pacific Standard Time - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, PacificStandardTimeZoneId); //-5 - sched = new SessionSchedule(settings); - - d3 = new DateTime(2013, 01, 15, 03, 00, 00, DateTimeKind.Utc); - d3expected = new DateTime(2013, 01, 14, 19, 00, 00, DateTimeKind.Unspecified); - d3actual = sched.AdjustUtcDateTime(d3); - Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d3expected, d3actual); - - // 4) TimeZone with daylight savings - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-4 in June - sched = new SessionSchedule(settings); - - DateTime d4 = new DateTime(2013, 06, 15, 03, 00, 00, DateTimeKind.Utc); - DateTime d4expected = new DateTime(2013, 06, 14, 23, 00, 00, DateTimeKind.Unspecified); - DateTime d4actual = sched.AdjustUtcDateTime(d4); - Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d4expected, d4actual); - - // 5) if settings has UseLocalTime, convert to local time - settings = new SettingsDictionary(); - settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc - settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc - settings.SetString(SessionSettings.USE_LOCAL_TIME, "Y"); - sched = new SessionSchedule(settings); - - DateTime d5 = new DateTime(2013, 01, 15, 16, 00, 00, DateTimeKind.Utc); - DateTime d5expected = d5.ToLocalTime(); - DateTime d5actual = sched.AdjustUtcDateTime(d5); - Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d5expected, d5actual); - Assert.That(d5actual.Kind, Is.EqualTo(DateTimeKind.Local)); - } + [Test] + public void TestAdjustDateTime() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "09:30:00"); + settings.SetString(SessionSettings.END_TIME, "16:00:00"); + SessionSchedule sched = new SessionSchedule(settings); + + // 1) reject if param is not utc + Assert.Throws( + delegate { sched.AdjustUtcDateTime(new DateTime(2012, 10, 18, 12, 00, 00, DateTimeKind.Local)); }); + Assert.Throws( + delegate { sched.AdjustUtcDateTime(new DateTime(2012, 10, 18, 12, 00, 00, DateTimeKind.Unspecified)); }); + + // 2) if settings is UTC, don't convert + DateTime d2 = new DateTime(2013, 01, 15, 12, 00, 00, DateTimeKind.Utc); + Assert.That(sched.AdjustUtcDateTime(d2), Is.EqualTo(d2)); + + // 3) if settings has a TimeZone, convert to TimeZone + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-5 + sched = new SessionSchedule(settings); + + DateTime d3 = new DateTime(2013, 01, 15, 03, 00, 00, DateTimeKind.Utc); + DateTime d3expected = new DateTime(2013, 01, 14, 22, 00, 00, DateTimeKind.Unspecified); + DateTime d3actual = sched.AdjustUtcDateTime(d3); + Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d3expected, d3actual); + + // now with Pacific Standard Time + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, PacificStandardTimeZoneId); //-5 + sched = new SessionSchedule(settings); + + d3 = new DateTime(2013, 01, 15, 03, 00, 00, DateTimeKind.Utc); + d3expected = new DateTime(2013, 01, 14, 19, 00, 00, DateTimeKind.Unspecified); + d3actual = sched.AdjustUtcDateTime(d3); + Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d3expected, d3actual); + + // 4) TimeZone with daylight savings + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.TIME_ZONE, EasternStandardTimeZoneId); //-4 in June + sched = new SessionSchedule(settings); + + DateTime d4 = new DateTime(2013, 06, 15, 03, 00, 00, DateTimeKind.Utc); + DateTime d4expected = new DateTime(2013, 06, 14, 23, 00, 00, DateTimeKind.Unspecified); + DateTime d4actual = sched.AdjustUtcDateTime(d4); + Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d4expected, d4actual); + + // 5) if settings has UseLocalTime, convert to local time + settings = new SettingsDictionary(); + settings.SetString(SessionSettings.START_TIME, "04:30:00"); // 09:30:00 utc + settings.SetString(SessionSettings.END_TIME, "11:00:00"); // 16:00:00 utc + settings.SetString(SessionSettings.USE_LOCAL_TIME, "Y"); + sched = new SessionSchedule(settings); + + DateTime d5 = new DateTime(2013, 01, 15, 16, 00, 00, DateTimeKind.Utc); + DateTime d5expected = d5.ToLocalTime(); + DateTime d5actual = sched.AdjustUtcDateTime(d5); + Util.UtcDateTimeSerializerTests.AssertHackyDateTimeEquality(d5expected, d5actual); + Assert.That(d5actual.Kind, Is.EqualTo(DateTimeKind.Local)); + } - [Test] - public void TestWeekdaysSession() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.WEEKDAYS, "Tue,Th"); - settings.SetString(SessionSettings.START_TIME, "08:00:00"); - settings.SetString(SessionSettings.END_TIME, "17:00:00"); - - SessionSchedule sched = new SessionSchedule(settings); - - // bounds of Tuesday - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 07, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 08, 00, 00, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 08, 00, 10, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 16, 59, 59, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 17, 00, 00, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 17, 00, 10, DateTimeKind.Utc)), Is.False); - - // bounds of Thursday - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 07, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 08, 00, 00, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 08, 00, 10, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 16, 59, 59, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 17, 00, 00, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 17, 00, 10, DateTimeKind.Utc)), Is.False); - } + [Test] + public void TestWeekdaysSession() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.WEEKDAYS, "Tue,Th"); + settings.SetString(SessionSettings.START_TIME, "08:00:00"); + settings.SetString(SessionSettings.END_TIME, "17:00:00"); + + SessionSchedule sched = new SessionSchedule(settings); + + // bounds of Tuesday + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 07, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 08, 00, 00, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 08, 00, 10, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 16, 59, 59, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 17, 00, 00, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 17, 00, 10, DateTimeKind.Utc)), Is.False); + + // bounds of Thursday + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 07, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 08, 00, 00, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 08, 00, 10, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 16, 59, 59, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 17, 00, 00, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 17, 00, 10, DateTimeKind.Utc)), Is.False); + } - [Test] - public void TestWeekdaysSession_ThatCrossesMidnight() - { - SettingsDictionary settings = new SettingsDictionary(); - settings.SetString(SessionSettings.WEEKDAYS, "Tue,Th"); - settings.SetString(SessionSettings.START_TIME, "17:00:00"); - settings.SetString(SessionSettings.END_TIME, "11:00:00"); - - SessionSchedule sched = new SessionSchedule(settings); - - // bounds of Tuesday-Wednesday - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 16, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 17, 00, 00, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 17, 00, 10, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 22, 10, 59, 59, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 22, 11, 00, 00, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 22, 11, 00, 10, DateTimeKind.Utc)), Is.False); - - // bounds of Thursday-Friday - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 16, 59, 59, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 17, 00, 00, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 17, 00, 10, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 24, 10, 59, 59, DateTimeKind.Utc)), Is.True); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 24, 11, 00, 00, DateTimeKind.Utc)), Is.False); - Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 24, 11, 00, 10, DateTimeKind.Utc)), Is.False); - } + [Test] + public void TestWeekdaysSession_ThatCrossesMidnight() + { + SettingsDictionary settings = new SettingsDictionary(); + settings.SetString(SessionSettings.WEEKDAYS, "Tue,Th"); + settings.SetString(SessionSettings.START_TIME, "17:00:00"); + settings.SetString(SessionSettings.END_TIME, "11:00:00"); + + SessionSchedule sched = new SessionSchedule(settings); + + // bounds of Tuesday-Wednesday + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 16, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 17, 00, 00, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 21, 17, 00, 10, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 22, 10, 59, 59, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 22, 11, 00, 00, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 22, 11, 00, 10, DateTimeKind.Utc)), Is.False); + + // bounds of Thursday-Friday + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 16, 59, 59, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 17, 00, 00, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 23, 17, 00, 10, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 24, 10, 59, 59, DateTimeKind.Utc)), Is.True); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 24, 11, 00, 00, DateTimeKind.Utc)), Is.False); + Assert.That(sched.IsSessionTime(new DateTime(2024, 05, 24, 11, 00, 10, DateTimeKind.Utc)), Is.False); } } diff --git a/UnitTests/SessionSettingsTest.cs b/UnitTests/SessionSettingsTest.cs index a35c4db0a..d20c08a52 100755 --- a/UnitTests/SessionSettingsTest.cs +++ b/UnitTests/SessionSettingsTest.cs @@ -3,317 +3,316 @@ using NUnit.Framework; using QuickFix; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class SessionSettingsTest { - [TestFixture] - public class SessionSettingsTest + private System.Text.StringBuilder _partialConfiguration = new(); + + [SetUp] + public void Init() + { + _partialConfiguration = new System.Text.StringBuilder() + .AppendLine("[SESSION]") + .AppendLine("BeginString=FIX.4.2") + .AppendLine("SenderCompID=ISLD") + .AppendLine("TargetCompID=TW") + .AppendLine("Value=1") + .AppendLine("# this is a comment") + .AppendLine("[SESSION]") + .AppendLine("BeginString=FIX.4.1") + .AppendLine("SenderCompID=ISLD") + .AppendLine("TargetCompID=WT") + .AppendLine("Value=2") + .AppendLine("[SESSION]") + .AppendLine("SenderCompID=ARCA") + .AppendLine("TargetCompID=TW") + .AppendLine("Value=3") + .AppendLine("[SESSION]") + .AppendLine("SenderCompID=ARCA") + .AppendLine("TargetCompID=WT") + .AppendLine("[SESSION]") + .AppendLine("SenderCompID=NYSE") + .AppendLine("TargetCompID=TW") + .AppendLine("SessionQualifier=QUAL1") + .AppendLine("Value=5") + .AppendLine("[SESSION]") + .AppendLine("SenderCompID=NYSE") + .AppendLine("TargetCompID=TW") + .AppendLine("SessionQualifier=QUAL2") + .AppendLine("Value=6") + .AppendLine("[SESSION]") + .AppendLine("BeginString=FIXT.1.1") + .AppendLine("SenderCompID=NYSE") + .AppendLine("TargetCompID=TW"); + } + + [Test] + public void Load() + { + string configuration = new System.Text.StringBuilder() + .AppendLine("[DEFAULT]") + .AppendLine("ConnectionType=initiator") + .AppendLine("BeginString=FIX.4.0") + .AppendLine("Value=4") + .AppendLine("Empty=") + .AppendLine(_partialConfiguration.ToString()) + .ToString(); + SessionSettings settings = new SessionSettings(new StringReader(configuration)); + + SessionID session1 = new SessionID("FIX.4.2", "ISLD", "TW"); + SessionID session2 = new SessionID("FIX.4.1", "ISLD", "WT"); + SessionID session3 = new SessionID("FIX.4.0", "ARCA", "TW"); + SessionID session4 = new SessionID("FIX.4.0", "ARCA", "WT"); + SessionID session5 = new SessionID("FIX.4.0", "NYSE", "TW", "QUAL1"); + SessionID session6 = new SessionID("FIX.4.0", "NYSE", "TW", "QUAL2"); + + Assert.That(settings.Get().GetString( "Empty" ), Is.EqualTo("") ); + + Assert.That(settings.Get().GetLong( "Value" ), Is.EqualTo(4) ); + Assert.That(settings.Get(session1).GetLong("Value"), Is.EqualTo(1)); + Assert.That(settings.Get(session2).GetLong("Value"), Is.EqualTo(2)); + Assert.That(settings.Get(session3).GetLong("Value"), Is.EqualTo(3)); + Assert.That(settings.Get(session4).GetLong("Value"), Is.EqualTo(4)); + Assert.That(settings.Get(session5).GetLong("Value"), Is.EqualTo(5)); + Assert.That(settings.Get(session6).GetLong("Value"), Is.EqualTo(6)); + + // case insensitivity + Assert.That(settings.Get().GetLong("value"), Is.EqualTo(4)); + Assert.That(settings.Get(session1).GetLong("value"), Is.EqualTo(1)); + Assert.That(settings.Get(session2).GetLong("value"), Is.EqualTo(2)); + Assert.That(settings.Get(session3).GetLong("value"), Is.EqualTo(3)); + Assert.That(settings.Get(session4).GetLong("value"), Is.EqualTo(4)); + Assert.That(settings.Get(session5).GetLong("value"), Is.EqualTo(5)); + Assert.That(settings.Get(session6).GetLong("value"), Is.EqualTo(6)); + + Assert.That(settings.Get().GetLong("VALUE"), Is.EqualTo(4)); + Assert.That(settings.Get(session1).GetLong("VALUE"), Is.EqualTo(1)); + Assert.That(settings.Get(session2).GetLong("VALUE"), Is.EqualTo(2)); + Assert.That(settings.Get(session3).GetLong("VALUE"), Is.EqualTo(3)); + Assert.That(settings.Get(session4).GetLong("VALUE"), Is.EqualTo(4)); + Assert.That(settings.Get(session5).GetLong("VALUE"), Is.EqualTo(5)); + Assert.That(settings.Get(session6).GetLong("VALUE"), Is.EqualTo(6)); + } + + [Test] + public void LoadSettingsWithDefaultSectionLast() { - private System.Text.StringBuilder _partialConfiguration = new(); + string configuration = new System.Text.StringBuilder() + .AppendLine(_partialConfiguration.ToString()) + .AppendLine("[DEFAULT]") + .AppendLine("ConnectionType=initiator") + .AppendLine("BeginString=FIX.4.0") + .AppendLine("Value=4") + .AppendLine("Empty=") + .ToString(); + SessionSettings settings = new SessionSettings(new StringReader(configuration)); + + SessionID session1 = new SessionID("FIX.4.2", "ISLD", "TW"); + SessionID session2 = new SessionID("FIX.4.1", "ISLD", "WT"); + SessionID session3 = new SessionID("FIX.4.0", "ARCA", "TW"); + SessionID session4 = new SessionID("FIX.4.0", "ARCA", "WT"); + SessionID session5 = new SessionID("FIX.4.0", "NYSE", "TW", "QUAL1"); + SessionID session6 = new SessionID("FIX.4.0", "NYSE", "TW", "QUAL2"); - [SetUp] - public void Init() - { - _partialConfiguration = new System.Text.StringBuilder() + Assert.That(settings.Get().GetString("Empty"), Is.EqualTo("")); + + Assert.That(settings.Get().GetLong("Value"), Is.EqualTo(4)); + Assert.That(settings.Get(session1).GetLong("Value"), Is.EqualTo(1)); + Assert.That(settings.Get(session2).GetLong("Value"), Is.EqualTo(2)); + Assert.That(settings.Get(session3).GetLong("Value"), Is.EqualTo(3)); + Assert.That(settings.Get(session4).GetLong("Value"), Is.EqualTo(4)); + Assert.That(settings.Get(session5).GetLong("Value"), Is.EqualTo(5)); + Assert.That(settings.Get(session6).GetLong("Value"), Is.EqualTo(6)); + + // case insensitivity + Assert.That(settings.Get().GetLong("value"), Is.EqualTo(4)); + Assert.That(settings.Get(session1).GetLong("value"), Is.EqualTo(1)); + Assert.That(settings.Get(session2).GetLong("value"), Is.EqualTo(2)); + Assert.That(settings.Get(session3).GetLong("value"), Is.EqualTo(3)); + Assert.That(settings.Get(session4).GetLong("value"), Is.EqualTo(4)); + Assert.That(settings.Get(session5).GetLong("value"), Is.EqualTo(5)); + Assert.That(settings.Get(session6).GetLong("value"), Is.EqualTo(6)); + + Assert.That(settings.Get().GetLong("VALUE"), Is.EqualTo(4)); + Assert.That(settings.Get(session1).GetLong("VALUE"), Is.EqualTo(1)); + Assert.That(settings.Get(session2).GetLong("VALUE"), Is.EqualTo(2)); + Assert.That(settings.Get(session3).GetLong("VALUE"), Is.EqualTo(3)); + Assert.That(settings.Get(session4).GetLong("VALUE"), Is.EqualTo(4)); + Assert.That(settings.Get(session5).GetLong("VALUE"), Is.EqualTo(5)); + Assert.That(settings.Get(session6).GetLong("VALUE"), Is.EqualTo(6)); + } + + [Test] + public void DuplicateSession() + { + string configuration = new System.Text.StringBuilder() + .AppendLine("[DEFAULT]") + .AppendLine("ConnectionType=initiator") .AppendLine("[SESSION]") .AppendLine("BeginString=FIX.4.2") .AppendLine("SenderCompID=ISLD") .AppendLine("TargetCompID=TW") - .AppendLine("Value=1") - .AppendLine("# this is a comment") .AppendLine("[SESSION]") - .AppendLine("BeginString=FIX.4.1") + .AppendLine("BeginString=FIX.4.2") .AppendLine("SenderCompID=ISLD") - .AppendLine("TargetCompID=WT") - .AppendLine("Value=2") - .AppendLine("[SESSION]") - .AppendLine("SenderCompID=ARCA") - .AppendLine("TargetCompID=TW") - .AppendLine("Value=3") - .AppendLine("[SESSION]") - .AppendLine("SenderCompID=ARCA") - .AppendLine("TargetCompID=WT") - .AppendLine("[SESSION]") - .AppendLine("SenderCompID=NYSE") .AppendLine("TargetCompID=TW") - .AppendLine("SessionQualifier=QUAL1") - .AppendLine("Value=5") - .AppendLine("[SESSION]") - .AppendLine("SenderCompID=NYSE") - .AppendLine("TargetCompID=TW") - .AppendLine("SessionQualifier=QUAL2") - .AppendLine("Value=6") - .AppendLine("[SESSION]") - .AppendLine("BeginString=FIXT.1.1") - .AppendLine("SenderCompID=NYSE") - .AppendLine("TargetCompID=TW"); - } - - [Test] - public void Load() - { - string configuration = new System.Text.StringBuilder() - .AppendLine("[DEFAULT]") - .AppendLine("ConnectionType=initiator") - .AppendLine("BeginString=FIX.4.0") - .AppendLine("Value=4") - .AppendLine("Empty=") - .AppendLine(_partialConfiguration.ToString()) - .ToString(); - SessionSettings settings = new SessionSettings(new StringReader(configuration)); - - SessionID session1 = new SessionID("FIX.4.2", "ISLD", "TW"); - SessionID session2 = new SessionID("FIX.4.1", "ISLD", "WT"); - SessionID session3 = new SessionID("FIX.4.0", "ARCA", "TW"); - SessionID session4 = new SessionID("FIX.4.0", "ARCA", "WT"); - SessionID session5 = new SessionID("FIX.4.0", "NYSE", "TW", "QUAL1"); - SessionID session6 = new SessionID("FIX.4.0", "NYSE", "TW", "QUAL2"); - - Assert.That(settings.Get().GetString( "Empty" ), Is.EqualTo("") ); - - Assert.That(settings.Get().GetLong( "Value" ), Is.EqualTo(4) ); - Assert.That(settings.Get(session1).GetLong("Value"), Is.EqualTo(1)); - Assert.That(settings.Get(session2).GetLong("Value"), Is.EqualTo(2)); - Assert.That(settings.Get(session3).GetLong("Value"), Is.EqualTo(3)); - Assert.That(settings.Get(session4).GetLong("Value"), Is.EqualTo(4)); - Assert.That(settings.Get(session5).GetLong("Value"), Is.EqualTo(5)); - Assert.That(settings.Get(session6).GetLong("Value"), Is.EqualTo(6)); - - // case insensitivity - Assert.That(settings.Get().GetLong("value"), Is.EqualTo(4)); - Assert.That(settings.Get(session1).GetLong("value"), Is.EqualTo(1)); - Assert.That(settings.Get(session2).GetLong("value"), Is.EqualTo(2)); - Assert.That(settings.Get(session3).GetLong("value"), Is.EqualTo(3)); - Assert.That(settings.Get(session4).GetLong("value"), Is.EqualTo(4)); - Assert.That(settings.Get(session5).GetLong("value"), Is.EqualTo(5)); - Assert.That(settings.Get(session6).GetLong("value"), Is.EqualTo(6)); - - Assert.That(settings.Get().GetLong("VALUE"), Is.EqualTo(4)); - Assert.That(settings.Get(session1).GetLong("VALUE"), Is.EqualTo(1)); - Assert.That(settings.Get(session2).GetLong("VALUE"), Is.EqualTo(2)); - Assert.That(settings.Get(session3).GetLong("VALUE"), Is.EqualTo(3)); - Assert.That(settings.Get(session4).GetLong("VALUE"), Is.EqualTo(4)); - Assert.That(settings.Get(session5).GetLong("VALUE"), Is.EqualTo(5)); - Assert.That(settings.Get(session6).GetLong("VALUE"), Is.EqualTo(6)); - } - - [Test] - public void LoadSettingsWithDefaultSectionLast() - { - string configuration = new System.Text.StringBuilder() - .AppendLine(_partialConfiguration.ToString()) - .AppendLine("[DEFAULT]") - .AppendLine("ConnectionType=initiator") - .AppendLine("BeginString=FIX.4.0") - .AppendLine("Value=4") - .AppendLine("Empty=") .ToString(); - SessionSettings settings = new SessionSettings(new StringReader(configuration)); - - SessionID session1 = new SessionID("FIX.4.2", "ISLD", "TW"); - SessionID session2 = new SessionID("FIX.4.1", "ISLD", "WT"); - SessionID session3 = new SessionID("FIX.4.0", "ARCA", "TW"); - SessionID session4 = new SessionID("FIX.4.0", "ARCA", "WT"); - SessionID session5 = new SessionID("FIX.4.0", "NYSE", "TW", "QUAL1"); - SessionID session6 = new SessionID("FIX.4.0", "NYSE", "TW", "QUAL2"); - - Assert.That(settings.Get().GetString("Empty"), Is.EqualTo("")); - - Assert.That(settings.Get().GetLong("Value"), Is.EqualTo(4)); - Assert.That(settings.Get(session1).GetLong("Value"), Is.EqualTo(1)); - Assert.That(settings.Get(session2).GetLong("Value"), Is.EqualTo(2)); - Assert.That(settings.Get(session3).GetLong("Value"), Is.EqualTo(3)); - Assert.That(settings.Get(session4).GetLong("Value"), Is.EqualTo(4)); - Assert.That(settings.Get(session5).GetLong("Value"), Is.EqualTo(5)); - Assert.That(settings.Get(session6).GetLong("Value"), Is.EqualTo(6)); - - // case insensitivity - Assert.That(settings.Get().GetLong("value"), Is.EqualTo(4)); - Assert.That(settings.Get(session1).GetLong("value"), Is.EqualTo(1)); - Assert.That(settings.Get(session2).GetLong("value"), Is.EqualTo(2)); - Assert.That(settings.Get(session3).GetLong("value"), Is.EqualTo(3)); - Assert.That(settings.Get(session4).GetLong("value"), Is.EqualTo(4)); - Assert.That(settings.Get(session5).GetLong("value"), Is.EqualTo(5)); - Assert.That(settings.Get(session6).GetLong("value"), Is.EqualTo(6)); - - Assert.That(settings.Get().GetLong("VALUE"), Is.EqualTo(4)); - Assert.That(settings.Get(session1).GetLong("VALUE"), Is.EqualTo(1)); - Assert.That(settings.Get(session2).GetLong("VALUE"), Is.EqualTo(2)); - Assert.That(settings.Get(session3).GetLong("VALUE"), Is.EqualTo(3)); - Assert.That(settings.Get(session4).GetLong("VALUE"), Is.EqualTo(4)); - Assert.That(settings.Get(session5).GetLong("VALUE"), Is.EqualTo(5)); - Assert.That(settings.Get(session6).GetLong("VALUE"), Is.EqualTo(6)); - } - - [Test] - public void DuplicateSession() - { - string configuration = new System.Text.StringBuilder() - .AppendLine("[DEFAULT]") - .AppendLine("ConnectionType=initiator") - .AppendLine("[SESSION]") - .AppendLine("BeginString=FIX.4.2") - .AppendLine("SenderCompID=ISLD") - .AppendLine("TargetCompID=TW") - .AppendLine("[SESSION]") - .AppendLine("BeginString=FIX.4.2") - .AppendLine("SenderCompID=ISLD") - .AppendLine("TargetCompID=TW") - .ToString(); - Assert.Throws(delegate { new SessionSettings(new StringReader(configuration)); }); - } - - [Test] - public void StripSpaces() - { - string configuration = new System.Text.StringBuilder() - .AppendLine("[ DEFAULT ]") - .AppendLine(" ConnectionType = initiator") - .AppendLine(" [ SESSION ] ") - .AppendLine("BeginString=FIX.4.2 ") - .AppendLine(" SenderCompID =ISLD") - .AppendLine(" TargetCompID = TW ") - .AppendLine(" Long = 123 ") - .AppendLine(" Double = 1.23 ") - .AppendLine(" Bool = N ") - .ToString(); - SessionSettings settings = new SessionSettings(new StringReader(configuration)); - - Assert.That(settings.Get().GetString("ConnectionType"), Is.EqualTo("initiator")); - - SessionID session = new SessionID("FIX.4.2", "ISLD", "TW"); - Assert.That(settings.Get(session).GetString("ConnectionType"), Is.EqualTo("initiator")); - Assert.That(settings.Get(session).GetString("BeginString"), Is.EqualTo("FIX.4.2")); - Assert.That(settings.Get(session).GetString("SenderCompID"), Is.EqualTo("ISLD")); - Assert.That(settings.Get(session).GetString("TargetCompID"), Is.EqualTo("TW")); - Assert.That(settings.Get(session).GetLong("Long"), Is.EqualTo(123)); - Assert.That(settings.Get(session).GetDouble("Double"), Is.EqualTo(1.23)); - Assert.That(settings.Get(session).GetBool("Bool"), Is.False); - } - - [Test] - public void Validate() - { - SessionSettings settings = new SessionSettings(); - SessionID sessionID = new SessionID("FIX.4.2", "SenderCompID", "TargetCompID"); - - // ConnectionType not set - QuickFix.SettingsDictionary settingsDictionary = new QuickFix.SettingsDictionary(); - Assert.Throws(delegate { settings.Set(sessionID, settingsDictionary); }); - - // ConnectionType set to invalid value - settingsDictionary.SetString(SessionSettings.CONNECTION_TYPE, "badvalue"); - Assert.Throws(delegate { settings.Set(sessionID, settingsDictionary); }); - - // ConnectionType set to valid value - settingsDictionary.SetString(SessionSettings.CONNECTION_TYPE, "initiator"); - Assert.DoesNotThrow(delegate { settings.Set(sessionID, settingsDictionary); }); - - // Invalid BeginString - sessionID = new SessionID("FIX4.2", "SenderCompID", "TargetCompID"); - Assert.Throws(delegate { settings.Set(sessionID, settingsDictionary); }); - } - - [Test] - public void SettingsToString() - { - string configuration = new System.Text.StringBuilder() - .AppendLine("[DEFAULT]") - .AppendLine("CONNECTIONTYPE=initiator") - .AppendLine("BEGINSTRING=FIX.4.0") - .AppendLine() - .AppendLine("[SESSION]") - .AppendLine("BEGINSTRING=FIX.4.2") - .AppendLine("SENDERCOMPID=ISLD") - .AppendLine("TARGETCOMPID=TW") - .AppendLine("VALUE=1") - .AppendLine() - .AppendLine("[SESSION]") - .AppendLine("BEGINSTRING=FIX.4.1") - .AppendLine("SENDERCOMPID=ISLD") - .AppendLine("TARGETCOMPID=WT") - .AppendLine("VALUE=2") + Assert.Throws(delegate { new SessionSettings(new StringReader(configuration)); }); + } + + [Test] + public void StripSpaces() + { + string configuration = new System.Text.StringBuilder() + .AppendLine("[ DEFAULT ]") + .AppendLine(" ConnectionType = initiator") + .AppendLine(" [ SESSION ] ") + .AppendLine("BeginString=FIX.4.2 ") + .AppendLine(" SenderCompID =ISLD") + .AppendLine(" TargetCompID = TW ") + .AppendLine(" Long = 123 ") + .AppendLine(" Double = 1.23 ") + .AppendLine(" Bool = N ") .ToString(); - SessionSettings settings = new SessionSettings(new StringReader(configuration)); + SessionSettings settings = new SessionSettings(new StringReader(configuration)); - Assert.That(settings.ToString(), Is.EqualTo(configuration)); - } + Assert.That(settings.Get().GetString("ConnectionType"), Is.EqualTo("initiator")); - [Test] - public void TestExtendedSettings() - { - string settingsString = new System.Text.StringBuilder() - .AppendLine("[DEFAULT]") - .AppendLine("ConnectionType=initiator") - .AppendLine("HeartBtInt=60") - .AppendLine("[SESSION]") - .AppendLine("BeginString=FIX.4.2") - .AppendLine("SenderCompID=Company") - .AppendLine("SenderSubID=FixedIncome") - .AppendLine("SenderLocationID=HongKong") - .AppendLine("TargetCompID=CLIENT1") - .AppendLine("TargetSubID=HedgeFund") - .AppendLine("TargetLocationID=NYC") - .AppendLine("SendRedundantResendRequests=Y") - .AppendLine("EnableLastMsgSeqNumProcessed=Y") - .AppendLine("MaxMessagesInResendRequest=2500") - .AppendLine("StartTime=06:00:00") - .AppendLine("EndTime=05:59:00") - .ToString(); + SessionID session = new SessionID("FIX.4.2", "ISLD", "TW"); + Assert.That(settings.Get(session).GetString("ConnectionType"), Is.EqualTo("initiator")); + Assert.That(settings.Get(session).GetString("BeginString"), Is.EqualTo("FIX.4.2")); + Assert.That(settings.Get(session).GetString("SenderCompID"), Is.EqualTo("ISLD")); + Assert.That(settings.Get(session).GetString("TargetCompID"), Is.EqualTo("TW")); + Assert.That(settings.Get(session).GetLong("Long"), Is.EqualTo(123)); + Assert.That(settings.Get(session).GetDouble("Double"), Is.EqualTo(1.23)); + Assert.That(settings.Get(session).GetBool("Bool"), Is.False); + } + + [Test] + public void Validate() + { + SessionSettings settings = new SessionSettings(); + SessionID sessionID = new SessionID("FIX.4.2", "SenderCompID", "TargetCompID"); + + // ConnectionType not set + QuickFix.SettingsDictionary settingsDictionary = new QuickFix.SettingsDictionary(); + Assert.Throws(delegate { settings.Set(sessionID, settingsDictionary); }); + + // ConnectionType set to invalid value + settingsDictionary.SetString(SessionSettings.CONNECTION_TYPE, "badvalue"); + Assert.Throws(delegate { settings.Set(sessionID, settingsDictionary); }); + + // ConnectionType set to valid value + settingsDictionary.SetString(SessionSettings.CONNECTION_TYPE, "initiator"); + Assert.DoesNotThrow(delegate { settings.Set(sessionID, settingsDictionary); }); - SessionSettings settings = new SessionSettings(new StringReader(settingsString)); - - SessionID id = new SessionID("FIX.4.2", "Company", "FixedIncome", "HongKong", "CLIENT1", "HedgeFund", "NYC"); - Assert.That(settings.Get(id).GetString("HeartBtInt"), Is.EqualTo("60")); - Assert.That(settings.Get(id).GetString("BeginString"), Is.EqualTo("FIX.4.2")); - Assert.That(settings.Get(id).GetString("SenderCompID"), Is.EqualTo("Company")); - Assert.That(settings.Get(id).GetString("SenderSubID"), Is.EqualTo("FixedIncome")); - Assert.That(settings.Get(id).GetString("SenderLocationID"), Is.EqualTo("HongKong")); - Assert.That(settings.Get(id).GetString("TargetCompID"), Is.EqualTo("CLIENT1")); - Assert.That(settings.Get(id).GetString("TargetSubID"), Is.EqualTo("HedgeFund")); - Assert.That(settings.Get(id).GetString("TargetLocationID"), Is.EqualTo("NYC")); - Assert.That(settings.Get(id).GetString("SendRedundantResendRequests"), Is.EqualTo("Y")); - Assert.That(settings.Get(id).GetString("EnableLastMsgSeqNumProcessed"), Is.EqualTo("Y")); - Assert.That(settings.Get(id).GetString("MaxMessagesInResendRequest"), Is.EqualTo("2500")); - Assert.That(settings.Get(id).GetString("StartTime"), Is.EqualTo("06:00:00")); - Assert.That(settings.Get(id).GetString("EndTime"), Is.EqualTo("05:59:00")); - - id = settings.GetSessions().First(); - Assert.That(id, Is.Not.Null); - Assert.That(id.BeginString, Is.EqualTo("FIX.4.2")); - Assert.That(id.SenderCompID, Is.EqualTo("Company")); - Assert.That(id.SenderSubID, Is.EqualTo("FixedIncome")); - Assert.That(id.SenderLocationID, Is.EqualTo("HongKong")); - Assert.That(id.TargetCompID, Is.EqualTo("CLIENT1")); - Assert.That(id.TargetSubID, Is.EqualTo("HedgeFund")); - Assert.That(id.TargetLocationID, Is.EqualTo("NYC")); - } - - [Test] - public void SettingsFileRelease() - { - string f = Path.Combine(TestContext.CurrentContext.TestDirectory, "foo_config.cfg"); - new SessionSettings(f); - - // if the file is still locked, this will throw an exception - new SessionSettings(f); - } - - [Test] - public void CaseInsensitiveSectionName() - { - string configuration = @"[dEfAuLt] + // Invalid BeginString + sessionID = new SessionID("FIX4.2", "SenderCompID", "TargetCompID"); + Assert.Throws(delegate { settings.Set(sessionID, settingsDictionary); }); + } + + [Test] + public void SettingsToString() + { + string configuration = new System.Text.StringBuilder() + .AppendLine("[DEFAULT]") + .AppendLine("CONNECTIONTYPE=initiator") + .AppendLine("BEGINSTRING=FIX.4.0") + .AppendLine() + .AppendLine("[SESSION]") + .AppendLine("BEGINSTRING=FIX.4.2") + .AppendLine("SENDERCOMPID=ISLD") + .AppendLine("TARGETCOMPID=TW") + .AppendLine("VALUE=1") + .AppendLine() + .AppendLine("[SESSION]") + .AppendLine("BEGINSTRING=FIX.4.1") + .AppendLine("SENDERCOMPID=ISLD") + .AppendLine("TARGETCOMPID=WT") + .AppendLine("VALUE=2") + .ToString(); + SessionSettings settings = new SessionSettings(new StringReader(configuration)); + + Assert.That(settings.ToString(), Is.EqualTo(configuration)); + } + + [Test] + public void TestExtendedSettings() + { + string settingsString = new System.Text.StringBuilder() + .AppendLine("[DEFAULT]") + .AppendLine("ConnectionType=initiator") + .AppendLine("HeartBtInt=60") + .AppendLine("[SESSION]") + .AppendLine("BeginString=FIX.4.2") + .AppendLine("SenderCompID=Company") + .AppendLine("SenderSubID=FixedIncome") + .AppendLine("SenderLocationID=HongKong") + .AppendLine("TargetCompID=CLIENT1") + .AppendLine("TargetSubID=HedgeFund") + .AppendLine("TargetLocationID=NYC") + .AppendLine("SendRedundantResendRequests=Y") + .AppendLine("EnableLastMsgSeqNumProcessed=Y") + .AppendLine("MaxMessagesInResendRequest=2500") + .AppendLine("StartTime=06:00:00") + .AppendLine("EndTime=05:59:00") + .ToString(); + + SessionSettings settings = new SessionSettings(new StringReader(settingsString)); + + SessionID id = new SessionID("FIX.4.2", "Company", "FixedIncome", "HongKong", "CLIENT1", "HedgeFund", "NYC"); + Assert.That(settings.Get(id).GetString("HeartBtInt"), Is.EqualTo("60")); + Assert.That(settings.Get(id).GetString("BeginString"), Is.EqualTo("FIX.4.2")); + Assert.That(settings.Get(id).GetString("SenderCompID"), Is.EqualTo("Company")); + Assert.That(settings.Get(id).GetString("SenderSubID"), Is.EqualTo("FixedIncome")); + Assert.That(settings.Get(id).GetString("SenderLocationID"), Is.EqualTo("HongKong")); + Assert.That(settings.Get(id).GetString("TargetCompID"), Is.EqualTo("CLIENT1")); + Assert.That(settings.Get(id).GetString("TargetSubID"), Is.EqualTo("HedgeFund")); + Assert.That(settings.Get(id).GetString("TargetLocationID"), Is.EqualTo("NYC")); + Assert.That(settings.Get(id).GetString("SendRedundantResendRequests"), Is.EqualTo("Y")); + Assert.That(settings.Get(id).GetString("EnableLastMsgSeqNumProcessed"), Is.EqualTo("Y")); + Assert.That(settings.Get(id).GetString("MaxMessagesInResendRequest"), Is.EqualTo("2500")); + Assert.That(settings.Get(id).GetString("StartTime"), Is.EqualTo("06:00:00")); + Assert.That(settings.Get(id).GetString("EndTime"), Is.EqualTo("05:59:00")); + + id = settings.GetSessions().First(); + Assert.That(id, Is.Not.Null); + Assert.That(id.BeginString, Is.EqualTo("FIX.4.2")); + Assert.That(id.SenderCompID, Is.EqualTo("Company")); + Assert.That(id.SenderSubID, Is.EqualTo("FixedIncome")); + Assert.That(id.SenderLocationID, Is.EqualTo("HongKong")); + Assert.That(id.TargetCompID, Is.EqualTo("CLIENT1")); + Assert.That(id.TargetSubID, Is.EqualTo("HedgeFund")); + Assert.That(id.TargetLocationID, Is.EqualTo("NYC")); + } + + [Test] + public void SettingsFileRelease() + { + string f = Path.Combine(TestContext.CurrentContext.TestDirectory, "foo_config.cfg"); + new SessionSettings(f); + + // if the file is still locked, this will throw an exception + new SessionSettings(f); + } + + [Test] + public void CaseInsensitiveSectionName() + { + string configuration = @"[dEfAuLt] ConnectionType=initiator [sEsSiOn] BeginString=FIX.4.2 SenderCompID=ISLD TargetCompID=TW"; - SessionSettings settings = new SessionSettings(new StringReader(configuration)); + SessionSettings settings = new SessionSettings(new StringReader(configuration)); - Assert.That(settings.Get().GetString("ConnectionType"), Is.EqualTo("initiator")); + Assert.That(settings.Get().GetString("ConnectionType"), Is.EqualTo("initiator")); - SessionID session = new SessionID("FIX.4.2", "ISLD", "TW"); - Assert.That(settings.Get(session).GetString("ConnectionType"), Is.EqualTo("initiator")); - Assert.That(settings.Get(session).GetString("BeginString"), Is.EqualTo("FIX.4.2")); - } + SessionID session = new SessionID("FIX.4.2", "ISLD", "TW"); + Assert.That(settings.Get(session).GetString("ConnectionType"), Is.EqualTo("initiator")); + Assert.That(settings.Get(session).GetString("BeginString"), Is.EqualTo("FIX.4.2")); } } diff --git a/UnitTests/SessionStateTest.cs b/UnitTests/SessionStateTest.cs index 83e713470..6e222ab56 100755 --- a/UnitTests/SessionStateTest.cs +++ b/UnitTests/SessionStateTest.cs @@ -7,217 +7,216 @@ using Microsoft.Extensions.Logging.Abstractions; using QuickFix.Store; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class SessionStateTest { - [TestFixture] - public class SessionStateTest + [SetUp] + public void Init() { - [SetUp] - public void Init() - { - } + } - [Test] - public void TimedOut() - { - int heartBtIntMillis = 60 * 1000; - System.DateTime now = System.DateTime.UtcNow; - System.DateTime lastReceivedTime = now; - - now = now.AddMilliseconds(heartBtIntMillis); - Assert.That(SessionState.TimedOut(now, heartBtIntMillis, lastReceivedTime), Is.False); - now = now.AddMilliseconds(heartBtIntMillis); - Assert.That(SessionState.TimedOut(now, heartBtIntMillis, lastReceivedTime), Is.False); - now = now.AddMilliseconds(heartBtIntMillis); - Assert.That(SessionState.TimedOut(now, heartBtIntMillis, lastReceivedTime), Is.True); - } - - [Test] - public void LogonTimedOut() - { - int logonTimeout = 5 * 1000; - - System.DateTime now = System.DateTime.UtcNow; - System.DateTime lastRecvTime = now; - - now = now.AddMilliseconds(4000); - Assert.That(SessionState.LogonTimedOut(now, logonTimeout, lastRecvTime), Is.False); - now = now.AddMilliseconds(1000); - Assert.That(SessionState.LogonTimedOut(now, logonTimeout, lastRecvTime), Is.True); - now = now.AddMilliseconds(1); - Assert.That(SessionState.LogonTimedOut(now, logonTimeout, lastRecvTime), Is.True); - } + [Test] + public void TimedOut() + { + int heartBtIntMillis = 60 * 1000; + System.DateTime now = System.DateTime.UtcNow; + System.DateTime lastReceivedTime = now; + + now = now.AddMilliseconds(heartBtIntMillis); + Assert.That(SessionState.TimedOut(now, heartBtIntMillis, lastReceivedTime), Is.False); + now = now.AddMilliseconds(heartBtIntMillis); + Assert.That(SessionState.TimedOut(now, heartBtIntMillis, lastReceivedTime), Is.False); + now = now.AddMilliseconds(heartBtIntMillis); + Assert.That(SessionState.TimedOut(now, heartBtIntMillis, lastReceivedTime), Is.True); + } - [Test] - public void LogoutTimedOut() - { - bool sentLogout = true; - int logoutTimeout = 2 * 1000; - - System.DateTime now = System.DateTime.UtcNow; - System.DateTime lastSentTime = now; - - now = now.AddMilliseconds(1000); - Assert.That(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime), Is.False); - now = now.AddMilliseconds(1000); - Assert.That(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime), Is.True); - - sentLogout = false; - Assert.That(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime), Is.False); - } + [Test] + public void LogonTimedOut() + { + int logonTimeout = 5 * 1000; - [Test] - public void NeedTestRequest() - { - int heartBtIntMillis = 30 * 1000; - int testRequestCounter = 0; + System.DateTime now = System.DateTime.UtcNow; + System.DateTime lastRecvTime = now; - System.DateTime now = System.DateTime.UtcNow; - System.DateTime lastReceivedTime = now; + now = now.AddMilliseconds(4000); + Assert.That(SessionState.LogonTimedOut(now, logonTimeout, lastRecvTime), Is.False); + now = now.AddMilliseconds(1000); + Assert.That(SessionState.LogonTimedOut(now, logonTimeout, lastRecvTime), Is.True); + now = now.AddMilliseconds(1); + Assert.That(SessionState.LogonTimedOut(now, logonTimeout, lastRecvTime), Is.True); + } - now = now.AddMilliseconds(heartBtIntMillis); - Assert.That(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter), Is.False); - now = now.AddMilliseconds(heartBtIntMillis); - Assert.That(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter), Is.True); + [Test] + public void LogoutTimedOut() + { + bool sentLogout = true; + int logoutTimeout = 2 * 1000; - testRequestCounter += 1; - Assert.That(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter), Is.False); - now = now.AddMilliseconds(heartBtIntMillis); - Assert.That(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter), Is.True); + System.DateTime now = System.DateTime.UtcNow; + System.DateTime lastSentTime = now; - } + now = now.AddMilliseconds(1000); + Assert.That(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime), Is.False); + now = now.AddMilliseconds(1000); + Assert.That(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime), Is.True); - [Test] - public void NeedHeartbeat() - { - int heartBtIntMillis = 60 * 1000; - int testRequestCounter = 0; - - System.DateTime now = System.DateTime.UtcNow; - System.DateTime lastSentTime = now; - - now = now.AddMilliseconds(heartBtIntMillis / 3); - Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.False); - now = now.AddMilliseconds(heartBtIntMillis / 3); - Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.False); - now = now.AddMilliseconds(heartBtIntMillis / 2); - Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.True); - - testRequestCounter = 1; - Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.False); - now = now.AddMilliseconds(2 * heartBtIntMillis); - Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.False); - testRequestCounter = 0; - Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.True); - } + sentLogout = false; + Assert.That(SessionState.LogoutTimedOut(now, sentLogout, logoutTimeout, lastSentTime), Is.False); + } - [Test] - public void WithinHeartbeat() - { - int heartBtIntMillis = 60 * 1000; + [Test] + public void NeedTestRequest() + { + int heartBtIntMillis = 30 * 1000; + int testRequestCounter = 0; - System.DateTime now = System.DateTime.UtcNow; - System.DateTime lastSentTime = now; - System.DateTime lastReceivedTime = now; + System.DateTime now = System.DateTime.UtcNow; + System.DateTime lastReceivedTime = now; - now = now.AddMilliseconds(heartBtIntMillis - 1); - Assert.That(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime), Is.True); - now = now.AddMilliseconds(1); - Assert.That(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime), Is.False); + now = now.AddMilliseconds(heartBtIntMillis); + Assert.That(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter), Is.False); + now = now.AddMilliseconds(heartBtIntMillis); + Assert.That(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter), Is.True); - lastSentTime = lastSentTime.AddMilliseconds(1); - lastReceivedTime = lastReceivedTime.AddMilliseconds(1); - Assert.That(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime), Is.True); - } + testRequestCounter += 1; + Assert.That(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter), Is.False); + now = now.AddMilliseconds(heartBtIntMillis); + Assert.That(SessionState.NeedTestRequest(now, heartBtIntMillis, lastReceivedTime, testRequestCounter), Is.True); - [Test] - public void ThreadSafeSetAndGet() { - //Set up store - var storeDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "store"); + } - if (System.IO.Directory.Exists(storeDirectory)) - System.IO.Directory.Delete(storeDirectory, true); + [Test] + public void NeedHeartbeat() + { + int heartBtIntMillis = 60 * 1000; + int testRequestCounter = 0; + + System.DateTime now = System.DateTime.UtcNow; + System.DateTime lastSentTime = now; + + now = now.AddMilliseconds(heartBtIntMillis / 3); + Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.False); + now = now.AddMilliseconds(heartBtIntMillis / 3); + Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.False); + now = now.AddMilliseconds(heartBtIntMillis / 2); + Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.True); + + testRequestCounter = 1; + Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.False); + now = now.AddMilliseconds(2 * heartBtIntMillis); + Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.False); + testRequestCounter = 0; + Assert.That(SessionState.NeedHeartbeat(now, heartBtIntMillis, lastSentTime, testRequestCounter), Is.True); + } - SessionID sessionId = new SessionID("FIX.4.2", "SENDERCOMP", "TARGETCOMP"); + [Test] + public void WithinHeartbeat() + { + int heartBtIntMillis = 60 * 1000; - SettingsDictionary config = new SettingsDictionary(); - config.SetString(SessionSettings.CONNECTION_TYPE, "initiator"); - config.SetString(SessionSettings.FILE_STORE_PATH, storeDirectory); + System.DateTime now = System.DateTime.UtcNow; + System.DateTime lastSentTime = now; + System.DateTime lastReceivedTime = now; - SessionSettings settings = new SessionSettings(); - settings.Set(sessionId, config); - FileStoreFactory factory = new FileStoreFactory(settings); + now = now.AddMilliseconds(heartBtIntMillis - 1); + Assert.That(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime), Is.True); + now = now.AddMilliseconds(1); + Assert.That(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime), Is.False); - FileStore store = (FileStore)factory.Create(sessionId); + lastSentTime = lastSentTime.AddMilliseconds(1); + lastReceivedTime = lastReceivedTime.AddMilliseconds(1); + Assert.That(SessionState.WithinHeartbeat(now, heartBtIntMillis, lastSentTime, lastReceivedTime), Is.True); + } - //Set up sessionstate - SessionState state = new SessionState(true, NullLogger.Instance, 1, store); + [Test] + public void ThreadSafeSetAndGet() { + //Set up store + var storeDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "store"); - Hashtable errorsTable = Hashtable.Synchronized(new Hashtable());//used in more than 1 thread at a time - Hashtable setTable = new Hashtable(1000);//only used in 1 thread at a time - Hashtable getTable = new Hashtable(1000);//only used in 1 thread at a time + if (System.IO.Directory.Exists(storeDirectory)) + System.IO.Directory.Delete(storeDirectory, true); - //Synchronously populate 1000 messages - for (SeqNumType i = 1; i < 1000; i++) { - string msg = "msg" + i; - state.Set(i, msg); - setTable[i] = msg; - } + SessionID sessionId = new SessionID("FIX.4.2", "SENDERCOMP", "TARGETCOMP"); - //Simulate background sending of messages that populate into the store - AutoResetEvent setEvent = new AutoResetEvent(false); - ThreadPool.QueueUserWorkItem(delegate(object? stateObject) { - AutoResetEvent internalSetEvent = (AutoResetEvent)((object[])stateObject!)[0]; - SessionState internalState = (SessionState)((object[])stateObject)[1]; - for (SeqNumType i = 1001; i < 2000; i++) { - try { - internalState.Set(i, "msg" + i); - } - catch (System.IO.IOException ex) { - errorsTable[ex.Message] = ex; - } - } + SettingsDictionary config = new SettingsDictionary(); + config.SetString(SessionSettings.CONNECTION_TYPE, "initiator"); + config.SetString(SessionSettings.FILE_STORE_PATH, storeDirectory); + + SessionSettings settings = new SessionSettings(); + settings.Set(sessionId, config); + FileStoreFactory factory = new FileStoreFactory(settings); + + FileStore store = (FileStore)factory.Create(sessionId); - internalSetEvent.Set(); + //Set up sessionstate + SessionState state = new SessionState(true, NullLogger.Instance, 1, store); + + Hashtable errorsTable = Hashtable.Synchronized(new Hashtable());//used in more than 1 thread at a time + Hashtable setTable = new Hashtable(1000);//only used in 1 thread at a time + Hashtable getTable = new Hashtable(1000);//only used in 1 thread at a time + + //Synchronously populate 1000 messages + for (SeqNumType i = 1; i < 1000; i++) { + string msg = "msg" + i; + state.Set(i, msg); + setTable[i] = msg; + } + + //Simulate background sending of messages that populate into the store + AutoResetEvent setEvent = new AutoResetEvent(false); + ThreadPool.QueueUserWorkItem(delegate(object? stateObject) { + AutoResetEvent internalSetEvent = (AutoResetEvent)((object[])stateObject!)[0]; + SessionState internalState = (SessionState)((object[])stateObject)[1]; + for (SeqNumType i = 1001; i < 2000; i++) { + try { + internalState.Set(i, "msg" + i); + } + catch (System.IO.IOException ex) { + errorsTable[ex.Message] = ex; + } } - , new object[] { setEvent, state }); - - //Simulate background reading of messages from the store - like is done in a resend request answer - AutoResetEvent getEvent = new AutoResetEvent(false); - ThreadPool.QueueUserWorkItem(delegate(object? stateObject){ - AutoResetEvent internalGetEvent = (AutoResetEvent)((object[])stateObject!)[0]; - SessionState internalState = (SessionState)((object[])stateObject)[1]; - for (SeqNumType i = 1; i < 1000; i++) { - try { - List lst = new List(1); - internalState.Get(i, i, lst); - if (lst.Count == 0) { - getTable[i] = "nothing read"; - } - else { - getTable[i] = lst[0]; - } + + internalSetEvent.Set(); + } + , new object[] { setEvent, state }); + + //Simulate background reading of messages from the store - like is done in a resend request answer + AutoResetEvent getEvent = new AutoResetEvent(false); + ThreadPool.QueueUserWorkItem(delegate(object? stateObject){ + AutoResetEvent internalGetEvent = (AutoResetEvent)((object[])stateObject!)[0]; + SessionState internalState = (SessionState)((object[])stateObject)[1]; + for (SeqNumType i = 1; i < 1000; i++) { + try { + List lst = new List(1); + internalState.Get(i, i, lst); + if (lst.Count == 0) { + getTable[i] = "nothing read"; } - catch (System.IO.IOException ex) { - errorsTable[ex.Message] = ex; + else { + getTable[i] = lst[0]; } } - - internalGetEvent.Set(); + catch (System.IO.IOException ex) { + errorsTable[ex.Message] = ex; + } } - , new object[]{getEvent, state}); - //wait till done and assert results - Assert.That(setEvent.WaitOne(10000), Is.True, "Get or Set hung/timed out during concurrent usage"); - Assert.That(getEvent.WaitOne(10000), Is.True, "Get or Set hung/timed out during concurrent usage"); - Assert.That(getTable, Is.EqualTo(setTable), "Garbled data read in concurrent set and get (like between resendrequest and send)"); - Assert.That(0, Is.EqualTo(errorsTable.Count), "IOException occured in concurrent set and get (like between resendrequest and send)"); + internalGetEvent.Set(); + } + , new object[]{getEvent, state}); - //Tear down filestore - state.Dispose(); - store.Dispose(); + //wait till done and assert results + Assert.That(setEvent.WaitOne(10000), Is.True, "Get or Set hung/timed out during concurrent usage"); + Assert.That(getEvent.WaitOne(10000), Is.True, "Get or Set hung/timed out during concurrent usage"); + Assert.That(getTable, Is.EqualTo(setTable), "Garbled data read in concurrent set and get (like between resendrequest and send)"); + Assert.That(0, Is.EqualTo(errorsTable.Count), "IOException occured in concurrent set and get (like between resendrequest and send)"); - Directory.Delete(storeDirectory, true); - } + //Tear down filestore + state.Dispose(); + store.Dispose(); + + Directory.Delete(storeDirectory, true); } } diff --git a/UnitTests/SettingsTest.cs b/UnitTests/SettingsTest.cs index bf646c672..674c93814 100644 --- a/UnitTests/SettingsTest.cs +++ b/UnitTests/SettingsTest.cs @@ -2,15 +2,15 @@ using NUnit.Framework; using QuickFix; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class SettingsTest { - [TestFixture] - public class SettingsTest + [Test] + public void Load() { - [Test] - public void Load() - { - string configuration = @"[FOO] + string configuration = @"[FOO] bar=24 baz=moo [OREN] @@ -30,56 +30,55 @@ public void Load() #Nero=IGNOREME EqualsInValue=We can have '=' in the value "; - Settings settings = new Settings(new System.IO.StringReader(configuration)); + Settings settings = new Settings(new System.IO.StringReader(configuration)); - LinkedList foo = settings.Get("FOO"); - Assert.That(foo.Count, Is.EqualTo(1)); - Assert.That(foo.First!.Value.GetLong("bar"), Is.EqualTo(24)); - Assert.That(foo.First.Value.GetString("baz"), Is.EqualTo("moo")); - Assert.That(foo.First.Value.GetString("baz"), Is.EqualTo("moo")); - Assert.That(foo.First.Value.Count, Is.EqualTo(2)); + LinkedList foo = settings.Get("FOO"); + Assert.That(foo.Count, Is.EqualTo(1)); + Assert.That(foo.First!.Value.GetLong("bar"), Is.EqualTo(24)); + Assert.That(foo.First.Value.GetString("baz"), Is.EqualTo("moo")); + Assert.That(foo.First.Value.GetString("baz"), Is.EqualTo("moo")); + Assert.That(foo.First.Value.Count, Is.EqualTo(2)); - LinkedList oren = settings.Get("OREN"); - Assert.That(oren.Count, Is.EqualTo(2)); - Assert.That(oren.First!.Value.Count, Is.EqualTo(1)); - Assert.That(oren.First.Value.GetString("Nero"), Is.EqualTo("TW")); - oren.RemoveFirst(); - Assert.That(oren.First.Value.Count, Is.EqualTo(2)); - Assert.That(oren.First.Value.GetString("ISLD"), Is.EqualTo("Nero")); - Assert.That(oren.First.Value.GetString("STUFF"), Is.EqualTo("./\\:")); + LinkedList oren = settings.Get("OREN"); + Assert.That(oren.Count, Is.EqualTo(2)); + Assert.That(oren.First!.Value.Count, Is.EqualTo(1)); + Assert.That(oren.First.Value.GetString("Nero"), Is.EqualTo("TW")); + oren.RemoveFirst(); + Assert.That(oren.First.Value.Count, Is.EqualTo(2)); + Assert.That(oren.First.Value.GetString("ISLD"), Is.EqualTo("Nero")); + Assert.That(oren.First.Value.GetString("STUFF"), Is.EqualTo("./\\:")); - LinkedList nero = settings.Get("NERO"); - Assert.That(nero.Count, Is.EqualTo(1)); - Assert.That(nero.First!.Value.Count, Is.EqualTo(5)); - Assert.That(nero.First.Value.GetString("WINDIR"), Is.EqualTo("D:\\This Is\\A-Directory\\Connamara\\")); - Assert.That(nero.First.Value.GetString("UNIXDIR"), Is.EqualTo("/home/mgatny/This Is/A Directory/ok/")); - Assert.That(nero.First.Value.GetString("WINFILE"), Is.EqualTo("D:\\Program Files\\Tomcat 4.1\\webapps\\mgatny\\WEB-INF\\connamara.cfg")); - Assert.That(nero.First.Value.GetString("stripspace"), Is.EqualTo("last spaces stripped")); - Assert.That(nero.First.Value.GetString("EqualsInValue"), Is.EqualTo("We can have '=' in the value")); - } + LinkedList nero = settings.Get("NERO"); + Assert.That(nero.Count, Is.EqualTo(1)); + Assert.That(nero.First!.Value.Count, Is.EqualTo(5)); + Assert.That(nero.First.Value.GetString("WINDIR"), Is.EqualTo("D:\\This Is\\A-Directory\\Connamara\\")); + Assert.That(nero.First.Value.GetString("UNIXDIR"), Is.EqualTo("/home/mgatny/This Is/A Directory/ok/")); + Assert.That(nero.First.Value.GetString("WINFILE"), Is.EqualTo("D:\\Program Files\\Tomcat 4.1\\webapps\\mgatny\\WEB-INF\\connamara.cfg")); + Assert.That(nero.First.Value.GetString("stripspace"), Is.EqualTo("last spaces stripped")); + Assert.That(nero.First.Value.GetString("EqualsInValue"), Is.EqualTo("We can have '=' in the value")); + } - [Test] - public void CaseInsensitiveSectionName() - { - string configuration = @"[foo] + [Test] + public void CaseInsensitiveSectionName() + { + string configuration = @"[foo] one=uno two=dos [bar] what=huh"; - Settings settings = new Settings(new System.IO.StringReader(configuration)); + Settings settings = new Settings(new System.IO.StringReader(configuration)); - LinkedList byLower = settings.Get("foo"); - Assert.That(byLower.Count, Is.EqualTo(1)); - Assert.That(byLower.First!.Value.Count, Is.EqualTo(2)); - Assert.That(byLower.First.Value.GetString("one"), Is.EqualTo("uno")); - Assert.That(byLower.First.Value.GetString("two"), Is.EqualTo("dos")); + LinkedList byLower = settings.Get("foo"); + Assert.That(byLower.Count, Is.EqualTo(1)); + Assert.That(byLower.First!.Value.Count, Is.EqualTo(2)); + Assert.That(byLower.First.Value.GetString("one"), Is.EqualTo("uno")); + Assert.That(byLower.First.Value.GetString("two"), Is.EqualTo("dos")); - // too lazy to write a QuickFix.Dictionary#Equals method (which would only be used by this test) - LinkedList byUpper = settings.Get("FOO"); - Assert.That(byUpper.Count, Is.EqualTo(byLower.Count)); - Assert.That(byUpper.First!.Value.Count, Is.EqualTo(byLower.First!.Value.Count)); - Assert.That(byUpper.First.Value.GetString("one"), Is.EqualTo(byUpper.First.Value.GetString("one"))); - Assert.That(byUpper.First.Value.GetString("two"), Is.EqualTo(byUpper.First.Value.GetString("two"))); - } + // too lazy to write a QuickFix.Dictionary#Equals method (which would only be used by this test) + LinkedList byUpper = settings.Get("FOO"); + Assert.That(byUpper.Count, Is.EqualTo(byLower.Count)); + Assert.That(byUpper.First!.Value.Count, Is.EqualTo(byLower.First!.Value.Count)); + Assert.That(byUpper.First.Value.GetString("one"), Is.EqualTo(byUpper.First.Value.GetString("one"))); + Assert.That(byUpper.First.Value.GetString("two"), Is.EqualTo(byUpper.First.Value.GetString("two"))); } } diff --git a/UnitTests/SocketSettingsTest.cs b/UnitTests/SocketSettingsTest.cs index 5e126b9ba..277e5e2b0 100644 --- a/UnitTests/SocketSettingsTest.cs +++ b/UnitTests/SocketSettingsTest.cs @@ -2,107 +2,106 @@ using NUnit.Framework; using QuickFix; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class SocketSettingsTest { - [TestFixture] - public class SocketSettingsTest + [Test] + public void DefaultValues() { - [Test] - public void DefaultValues() - { - SocketSettings socketSettings = new SocketSettings(); + SocketSettings socketSettings = new SocketSettings(); - Assert.That(socketSettings.SocketIgnoreProxy, Is.False); - Assert.That(socketSettings.SocketNodelay, Is.True); - Assert.That(socketSettings.SocketReceiveBufferSize, Is.Null); - Assert.That(socketSettings.SocketSendBufferSize, Is.Null); - Assert.That(socketSettings.SocketReceiveTimeout, Is.Null); - Assert.That(socketSettings.SocketSendTimeout, Is.Null); - Assert.That(socketSettings.ServerCommonName, Is.Null); - Assert.That(socketSettings.ValidateCertificates, Is.True); - Assert.That(socketSettings.CertificatePath, Is.Null); - Assert.That(socketSettings.CertificatePassword, Is.Null); - Assert.That(socketSettings.SslProtocol, Is.EqualTo(SslProtocols.None)); - Assert.That(socketSettings.CheckCertificateRevocation, Is.True); - Assert.That(socketSettings.UseSSL, Is.False); - Assert.That(socketSettings.CACertificatePath, Is.Null); - Assert.That(socketSettings.RequireClientCertificate, Is.True); - } + Assert.That(socketSettings.SocketIgnoreProxy, Is.False); + Assert.That(socketSettings.SocketNodelay, Is.True); + Assert.That(socketSettings.SocketReceiveBufferSize, Is.Null); + Assert.That(socketSettings.SocketSendBufferSize, Is.Null); + Assert.That(socketSettings.SocketReceiveTimeout, Is.Null); + Assert.That(socketSettings.SocketSendTimeout, Is.Null); + Assert.That(socketSettings.ServerCommonName, Is.Null); + Assert.That(socketSettings.ValidateCertificates, Is.True); + Assert.That(socketSettings.CertificatePath, Is.Null); + Assert.That(socketSettings.CertificatePassword, Is.Null); + Assert.That(socketSettings.SslProtocol, Is.EqualTo(SslProtocols.None)); + Assert.That(socketSettings.CheckCertificateRevocation, Is.True); + Assert.That(socketSettings.UseSSL, Is.False); + Assert.That(socketSettings.CACertificatePath, Is.Null); + Assert.That(socketSettings.RequireClientCertificate, Is.True); + } - private SettingsDictionary BaseTestDict() - { - SettingsDictionary dict = new SettingsDictionary(); - dict.SetBool(SessionSettings.SOCKET_IGNORE_PROXY, false); - dict.SetBool(SessionSettings.SOCKET_NODELAY, false); - dict.SetLong(SessionSettings.SOCKET_RECEIVE_BUFFER_SIZE, 1); - dict.SetLong(SessionSettings.SOCKET_SEND_BUFFER_SIZE, 2); - dict.SetLong(SessionSettings.SOCKET_RECEIVE_TIMEOUT, 3); - dict.SetLong(SessionSettings.SOCKET_SEND_TIMEOUT, 4); - dict.SetString(SessionSettings.SSL_SERVERNAME, "SSL_SERVERNAME"); - dict.SetBool(SessionSettings.SSL_VALIDATE_CERTIFICATES, false); - dict.SetString(SessionSettings.SSL_CERTIFICATE, "SSL_CERTIFICATE"); - dict.SetString(SessionSettings.SSL_CA_CERTIFICATE, "SSL_CA_CERTIFICATE"); - dict.SetString(SessionSettings.SSL_CERTIFICATE_PASSWORD, "SSL_CERTIFICATE_PASSWORD"); - dict.SetString(SessionSettings.SSL_PROTOCOLS, "Tls12"); - dict.SetBool(SessionSettings.SSL_CHECK_CERTIFICATE_REVOCATION, false); - dict.SetBool(SessionSettings.SSL_ENABLE, true); - dict.SetBool(SessionSettings.SSL_REQUIRE_CLIENT_CERTIFICATE, false); - return dict; - } + private SettingsDictionary BaseTestDict() + { + SettingsDictionary dict = new SettingsDictionary(); + dict.SetBool(SessionSettings.SOCKET_IGNORE_PROXY, false); + dict.SetBool(SessionSettings.SOCKET_NODELAY, false); + dict.SetLong(SessionSettings.SOCKET_RECEIVE_BUFFER_SIZE, 1); + dict.SetLong(SessionSettings.SOCKET_SEND_BUFFER_SIZE, 2); + dict.SetLong(SessionSettings.SOCKET_RECEIVE_TIMEOUT, 3); + dict.SetLong(SessionSettings.SOCKET_SEND_TIMEOUT, 4); + dict.SetString(SessionSettings.SSL_SERVERNAME, "SSL_SERVERNAME"); + dict.SetBool(SessionSettings.SSL_VALIDATE_CERTIFICATES, false); + dict.SetString(SessionSettings.SSL_CERTIFICATE, "SSL_CERTIFICATE"); + dict.SetString(SessionSettings.SSL_CA_CERTIFICATE, "SSL_CA_CERTIFICATE"); + dict.SetString(SessionSettings.SSL_CERTIFICATE_PASSWORD, "SSL_CERTIFICATE_PASSWORD"); + dict.SetString(SessionSettings.SSL_PROTOCOLS, "Tls12"); + dict.SetBool(SessionSettings.SSL_CHECK_CERTIFICATE_REVOCATION, false); + dict.SetBool(SessionSettings.SSL_ENABLE, true); + dict.SetBool(SessionSettings.SSL_REQUIRE_CLIENT_CERTIFICATE, false); + return dict; + } - [Test] - public void Configure() - { - SocketSettings socketSettings = new SocketSettings(); - socketSettings.Configure(BaseTestDict()); + [Test] + public void Configure() + { + SocketSettings socketSettings = new SocketSettings(); + socketSettings.Configure(BaseTestDict()); - Assert.That(socketSettings.SocketIgnoreProxy, Is.False); - Assert.That(socketSettings.SocketNodelay, Is.False); - Assert.That(socketSettings.SocketReceiveBufferSize, Is.EqualTo(1)); - Assert.That(socketSettings.SocketSendBufferSize, Is.EqualTo(2)); - Assert.That(socketSettings.SocketReceiveTimeout, Is.EqualTo(3)); - Assert.That(socketSettings.SocketSendTimeout, Is.EqualTo(4)); - Assert.That(socketSettings.ServerCommonName, Is.EqualTo("SSL_SERVERNAME")); - Assert.That(socketSettings.ValidateCertificates, Is.False); - Assert.That(socketSettings.CertificatePath, Is.EqualTo("SSL_CERTIFICATE")); - Assert.That(socketSettings.CACertificatePath, Is.EqualTo("SSL_CA_CERTIFICATE")); - Assert.That(socketSettings.CertificatePassword, Is.EqualTo("SSL_CERTIFICATE_PASSWORD")); - Assert.That(socketSettings.SslProtocol, Is.EqualTo(SslProtocols.Tls12)); - Assert.That(socketSettings.CheckCertificateRevocation, Is.False); - Assert.That(socketSettings.UseSSL, Is.True); - Assert.That(socketSettings.RequireClientCertificate, Is.False); - } + Assert.That(socketSettings.SocketIgnoreProxy, Is.False); + Assert.That(socketSettings.SocketNodelay, Is.False); + Assert.That(socketSettings.SocketReceiveBufferSize, Is.EqualTo(1)); + Assert.That(socketSettings.SocketSendBufferSize, Is.EqualTo(2)); + Assert.That(socketSettings.SocketReceiveTimeout, Is.EqualTo(3)); + Assert.That(socketSettings.SocketSendTimeout, Is.EqualTo(4)); + Assert.That(socketSettings.ServerCommonName, Is.EqualTo("SSL_SERVERNAME")); + Assert.That(socketSettings.ValidateCertificates, Is.False); + Assert.That(socketSettings.CertificatePath, Is.EqualTo("SSL_CERTIFICATE")); + Assert.That(socketSettings.CACertificatePath, Is.EqualTo("SSL_CA_CERTIFICATE")); + Assert.That(socketSettings.CertificatePassword, Is.EqualTo("SSL_CERTIFICATE_PASSWORD")); + Assert.That(socketSettings.SslProtocol, Is.EqualTo(SslProtocols.Tls12)); + Assert.That(socketSettings.CheckCertificateRevocation, Is.False); + Assert.That(socketSettings.UseSSL, Is.True); + Assert.That(socketSettings.RequireClientCertificate, Is.False); + } - private SocketSettings CreateWithSslConfig(bool sslValidateCertificates, bool sslCheckCertificateRevocation) - { - var dict = BaseTestDict(); - dict.SetBool(SessionSettings.SSL_VALIDATE_CERTIFICATES, sslValidateCertificates); - dict.SetBool(SessionSettings.SSL_CHECK_CERTIFICATE_REVOCATION, sslCheckCertificateRevocation); - SocketSettings socketSettings = new SocketSettings(); - socketSettings.Configure(dict); - return socketSettings; - } + private SocketSettings CreateWithSslConfig(bool sslValidateCertificates, bool sslCheckCertificateRevocation) + { + var dict = BaseTestDict(); + dict.SetBool(SessionSettings.SSL_VALIDATE_CERTIFICATES, sslValidateCertificates); + dict.SetBool(SessionSettings.SSL_CHECK_CERTIFICATE_REVOCATION, sslCheckCertificateRevocation); + SocketSettings socketSettings = new SocketSettings(); + socketSettings.Configure(dict); + return socketSettings; + } - [Test] - public void Configure_SslOverride() - { - // SSLValidateCertificates=true does not affect SSLCheckCertificateRevocation - var socketSettings = CreateWithSslConfig(true, false); - Assert.That(socketSettings.ValidateCertificates, Is.True); - Assert.That(socketSettings.CheckCertificateRevocation, Is.False); + [Test] + public void Configure_SslOverride() + { + // SSLValidateCertificates=true does not affect SSLCheckCertificateRevocation + var socketSettings = CreateWithSslConfig(true, false); + Assert.That(socketSettings.ValidateCertificates, Is.True); + Assert.That(socketSettings.CheckCertificateRevocation, Is.False); - socketSettings = CreateWithSslConfig(true, true); - Assert.That(socketSettings.ValidateCertificates, Is.True); - Assert.That(socketSettings.CheckCertificateRevocation, Is.True); + socketSettings = CreateWithSslConfig(true, true); + Assert.That(socketSettings.ValidateCertificates, Is.True); + Assert.That(socketSettings.CheckCertificateRevocation, Is.True); - // SSLValidateCertificates=false means SSLCheckCertificateRevocation must be false - socketSettings = CreateWithSslConfig(false, true); - Assert.That(socketSettings.ValidateCertificates, Is.False); - Assert.That(socketSettings.CheckCertificateRevocation, Is.False); + // SSLValidateCertificates=false means SSLCheckCertificateRevocation must be false + socketSettings = CreateWithSslConfig(false, true); + Assert.That(socketSettings.ValidateCertificates, Is.False); + Assert.That(socketSettings.CheckCertificateRevocation, Is.False); - socketSettings = CreateWithSslConfig(false, false); - Assert.That(socketSettings.ValidateCertificates, Is.False); - Assert.That(socketSettings.CheckCertificateRevocation, Is.False); - } + socketSettings = CreateWithSslConfig(false, false); + Assert.That(socketSettings.ValidateCertificates, Is.False); + Assert.That(socketSettings.CheckCertificateRevocation, Is.False); } } diff --git a/UnitTests/TestHelpers/DataDictionaryLoadExtensions.cs b/UnitTests/TestHelpers/DataDictionaryLoadExtensions.cs index 8cc1ae13a..ac2534b30 100644 --- a/UnitTests/TestHelpers/DataDictionaryLoadExtensions.cs +++ b/UnitTests/TestHelpers/DataDictionaryLoadExtensions.cs @@ -2,18 +2,17 @@ using NUnit.Framework; using QuickFix.DataDictionary; -namespace UnitTests.TestHelpers +namespace UnitTests.TestHelpers; + +internal static class DataDictionaryLoadExtensions { - internal static class DataDictionaryLoadExtensions + public static void LoadFIXSpec(this DataDictionary self, string name) { - public static void LoadFIXSpec(this DataDictionary self, string name) - { - self.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "fix", $"{name}.xml")); - } + self.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "fix", $"{name}.xml")); + } - public static void LoadTestFIXSpec(this DataDictionary self, string name) - { - self.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "test", $"{name}.xml")); - } + public static void LoadTestFIXSpec(this DataDictionary self, string name) + { + self.Load(Path.Combine(TestContext.CurrentContext.TestDirectory, "spec", "test", $"{name}.xml")); } } diff --git a/UnitTests/ThreadedSocketAcceptorTests.cs b/UnitTests/ThreadedSocketAcceptorTests.cs index 0361f3d1c..b9cc16892 100644 --- a/UnitTests/ThreadedSocketAcceptorTests.cs +++ b/UnitTests/ThreadedSocketAcceptorTests.cs @@ -1,16 +1,15 @@ using System.IO; -using Microsoft.Extensions.Logging; using NUnit.Framework; using QuickFix; using QuickFix.Logger; using QuickFix.Store; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class ThreadedSocketAcceptorTests { - [TestFixture] - public class ThreadedSocketAcceptorTests - { - private static string Config = $@" + private static string Config = $@" [DEFAULT] StartTime = 00:00:00 EndTime = 23:59:59 @@ -27,31 +26,30 @@ public class ThreadedSocketAcceptorTests BeginString = FIX.4.4 "; - private static SessionSettings CreateSettings() - { - return new SessionSettings(new StringReader(Config)); - } + private static SessionSettings CreateSettings() + { + return new SessionSettings(new StringReader(Config)); + } - [Test] - public void TestRecreation() - { - StartStopAcceptor(); - StartStopAcceptor(); - StartStopAcceptor(); - } + [Test] + public void TestRecreation() + { + StartStopAcceptor(); + StartStopAcceptor(); + StartStopAcceptor(); + } - private static void StartStopAcceptor() - { - var settings = CreateSettings(); - var lf = new FileLogFactory(settings); + private static void StartStopAcceptor() + { + var settings = CreateSettings(); + var lf = new FileLogFactory(settings); - var acceptor = new ThreadedSocketAcceptor( - new NullApplication(), - new FileStoreFactory(settings), - settings, - lf); - acceptor.Start(); - acceptor.Dispose(); - } + var acceptor = new ThreadedSocketAcceptor( + new NullApplication(), + new FileStoreFactory(settings), + settings, + lf); + acceptor.Start(); + acceptor.Dispose(); } } diff --git a/UnitTests/ThreadedSocketReactorTests.cs b/UnitTests/ThreadedSocketReactorTests.cs index ae33dbb84..735f60898 100644 --- a/UnitTests/ThreadedSocketReactorTests.cs +++ b/UnitTests/ThreadedSocketReactorTests.cs @@ -6,61 +6,60 @@ using System.Net.Sockets; using QuickFix.Logger; -namespace UnitTests +namespace UnitTests; + +[TestFixture] +public class ThreadedSocketReactorTests { - [TestFixture] - public class ThreadedSocketReactorTests - { - static TcpListener? _tcpListener; + static TcpListener? _tcpListener; - private int OccupyAPort() + private int OccupyAPort() + { + Random random = new(); + for (int i = 0; i < 10; i++) { - Random random = new(); - for (int i = 0; i < 10; i++) + try { - try - { - int randomPort = random.Next(5000, 6000); - _tcpListener = new TcpListener(IPAddress.Loopback, randomPort); - _tcpListener.Start(); - - return randomPort; - } - catch { } - } + int randomPort = random.Next(5000, 6000); + _tcpListener = new TcpListener(IPAddress.Loopback, randomPort); + _tcpListener.Start(); - throw new Exception("Could not occupy a port in 10 attempts"); + return randomPort; + } + catch { } } - static StringWriter GetStdOut() - { - var stringWriter = new StringWriter(); - Console.SetOut(stringWriter); - return stringWriter; - } + throw new Exception("Could not occupy a port in 10 attempts"); + } - [Test] - public void TestStartOnBusyPort() - { - var port = OccupyAPort(); + static StringWriter GetStdOut() + { + var stringWriter = new StringWriter(); + Console.SetOut(stringWriter); + return stringWriter; + } + + [Test] + public void TestStartOnBusyPort() + { + var port = OccupyAPort(); - var settings = new SocketSettings(); - var testingObject = new ThreadedSocketReactor( - new IPEndPoint(IPAddress.Loopback, port), - settings, - acceptorSocketDescriptor: null, - new LogFactoryAdapter(new ScreenLogFactory(true, true, true))); + var settings = new SocketSettings(); + var testingObject = new ThreadedSocketReactor( + new IPEndPoint(IPAddress.Loopback, port), + settings, + acceptorSocketDescriptor: null, + new LogFactoryAdapter(new ScreenLogFactory(true, true, true))); - var stdOut = GetStdOut(); - var ex = Assert.Throws(delegate { testingObject.Start(); })!; + var stdOut = GetStdOut(); + var ex = Assert.Throws(delegate { testingObject.Start(); })!; - Assert.That(stdOut.ToString(), Does.StartWith(" Error starting listener")); - Assert.That(ex.SocketErrorCode, Is.EqualTo(SocketError.AddressAlreadyInUse)); - } + Assert.That(stdOut.ToString(), Does.StartWith(" Error starting listener")); + Assert.That(ex.SocketErrorCode, Is.EqualTo(SocketError.AddressAlreadyInUse)); + } - [TearDown] - public void TearDown() { - _tcpListener?.Stop(); - } + [TearDown] + public void TearDown() { + _tcpListener?.Stop(); } } diff --git a/UnitTests/Util/ExceptionExtensionsTests.cs b/UnitTests/Util/ExceptionExtensionsTests.cs index a968f1045..192769f9c 100644 --- a/UnitTests/Util/ExceptionExtensionsTests.cs +++ b/UnitTests/Util/ExceptionExtensionsTests.cs @@ -2,28 +2,27 @@ using NUnit.Framework; using QuickFix.Util; -namespace UnitTests.Util +namespace UnitTests.Util; + +public sealed class ExceptionExtensionsTests { - public sealed class ExceptionExtensionsTests + [Test] + public void WhenInnerExceptionShouldReturnJoinedInnerExceptionMessages() { - [Test] - public void WhenInnerExceptionShouldReturnJoinedInnerExceptionMessages() - { - var exception = new Exception( - "Outer exception, see inner exception", - new Exception("My inner exception message")); + var exception = new Exception( + "Outer exception, see inner exception", + new Exception("My inner exception message")); - Assert.That( - "Outer exception, see inner exception --> My inner exception message", - Is.EqualTo(exception.GetFullMessage())); - } + Assert.That( + "Outer exception, see inner exception --> My inner exception message", + Is.EqualTo(exception.GetFullMessage())); + } - [Test] - public void WhenNoInnerExceptionShouldReturnExceptionMessageUnmodified() - { - var exception = new Exception("My exception message"); + [Test] + public void WhenNoInnerExceptionShouldReturnExceptionMessageUnmodified() + { + var exception = new Exception("My exception message"); - Assert.That("My exception message", Is.EqualTo(exception.GetFullMessage())); - } + Assert.That("My exception message", Is.EqualTo(exception.GetFullMessage())); } } diff --git a/UnitTests/Util/UtcDateTimeSerializerTests.cs b/UnitTests/Util/UtcDateTimeSerializerTests.cs index c83a2a364..d8d4bbb30 100644 --- a/UnitTests/Util/UtcDateTimeSerializerTests.cs +++ b/UnitTests/Util/UtcDateTimeSerializerTests.cs @@ -2,51 +2,49 @@ using NUnit.Framework; using QuickFix.Util; +namespace UnitTests.Util; -namespace UnitTests.Util +[TestFixture] +public class UtcDateTimeSerializerTests { - [TestFixture] - public class UtcDateTimeSerializerTests + /// + /// A little precision is lost in the serialization, so exact equality doesn't happen. + /// This is an adequate test kludge. + /// + /// + /// + public static void AssertHackyDateTimeEquality(DateTime d1, DateTime d2) { - /// - /// A little precision is lost in the serialization, so exact equality doesn't happen. - /// This is an adequate test kludge. - /// - /// - /// - static public void AssertHackyDateTimeEquality(DateTime d1, DateTime d2) - { - Assert.That(d2.Kind, Is.EqualTo(d1.Kind), "kind"); - Assert.That(d2.Date, Is.EqualTo(d1.Date), "date"); - Assert.That(d2.Hour, Is.EqualTo(d1.Hour), "hours"); - Assert.That(d2.Minute, Is.EqualTo(d1.Minute), "minutes"); - Assert.That(d2.Second, Is.EqualTo(d1.Second), "seconds"); - Assert.That(d2.Millisecond, Is.EqualTo(d1.Millisecond), "milliseconds"); - } + Assert.That(d2.Kind, Is.EqualTo(d1.Kind), "kind"); + Assert.That(d2.Date, Is.EqualTo(d1.Date), "date"); + Assert.That(d2.Hour, Is.EqualTo(d1.Hour), "hours"); + Assert.That(d2.Minute, Is.EqualTo(d1.Minute), "minutes"); + Assert.That(d2.Second, Is.EqualTo(d1.Second), "seconds"); + Assert.That(d2.Millisecond, Is.EqualTo(d1.Millisecond), "milliseconds"); + } - [Test] - public void BackAndForth() - { - DateTime d1 = DateTime.UtcNow; - DateTime d2 = UtcDateTimeSerializer.FromString( - UtcDateTimeSerializer.ToString(d1)); + [Test] + public void BackAndForth() + { + DateTime d1 = DateTime.UtcNow; + DateTime d2 = UtcDateTimeSerializer.FromString( + UtcDateTimeSerializer.ToString(d1)); - AssertHackyDateTimeEquality(d1, d2); - } + AssertHackyDateTimeEquality(d1, d2); + } - [Test] - public void SomeDates() - { - DateTime d1 = new DateTime(2013, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); - DateTime d6 = new DateTime(2013, 6, 6, 6, 6, 6, 6, DateTimeKind.Utc); + [Test] + public void SomeDates() + { + DateTime d1 = new DateTime(2013, 1, 1, 1, 1, 1, 1, DateTimeKind.Utc); + DateTime d6 = new DateTime(2013, 6, 6, 6, 6, 6, 6, DateTimeKind.Utc); - DateTime d1b = UtcDateTimeSerializer.FromString( - UtcDateTimeSerializer.ToString(d1)); - DateTime d6b = UtcDateTimeSerializer.FromString( - UtcDateTimeSerializer.ToString(d6)); + DateTime d1b = UtcDateTimeSerializer.FromString( + UtcDateTimeSerializer.ToString(d1)); + DateTime d6b = UtcDateTimeSerializer.FromString( + UtcDateTimeSerializer.ToString(d6)); - AssertHackyDateTimeEquality(d1b, d1b); - AssertHackyDateTimeEquality(d6b, d6b); - } + AssertHackyDateTimeEquality(d1b, d1b); + AssertHackyDateTimeEquality(d6b, d6b); } } From 9ed4171372b1a79ffbe206932e6378b22eb8aa19 Mon Sep 17 00:00:00 2001 From: Grant Birchmeier Date: Tue, 14 Apr 2026 10:59:22 -0500 Subject: [PATCH 3/4] use file-scoped namespace - ATApp --- AcceptanceTest/ATApplication.cs | 329 ++++++++++++++++---------------- 1 file changed, 164 insertions(+), 165 deletions(-) diff --git a/AcceptanceTest/ATApplication.cs b/AcceptanceTest/ATApplication.cs index ace78032f..5e2ef3a54 100755 --- a/AcceptanceTest/ATApplication.cs +++ b/AcceptanceTest/ATApplication.cs @@ -1,217 +1,216 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.Extensions.Logging; using QuickFix; using QuickFix.Fields; -namespace AcceptanceTest +namespace AcceptanceTest; + +public class ATApplication : MessageCracker, IApplication { - public class ATApplication : MessageCracker, IApplication - { - public event System.Action? StopMeEvent; + public event System.Action? StopMeEvent; - private readonly HashSet> _clOrdIDs = new(); + private readonly HashSet> _clOrdIDs = new(); - public ATApplication() - { - } + public ATApplication() + { + } - public void OnMessage(QuickFix.FIX40.NewOrderSingle nos, SessionID sessionId) - { - ProcessNOS(nos, sessionId); - } + public void OnMessage(QuickFix.FIX40.NewOrderSingle nos, SessionID sessionId) + { + ProcessNOS(nos, sessionId); + } - public void OnMessage(QuickFix.FIX41.NewOrderSingle nos, SessionID sessionId) - { - ProcessNOS(nos, sessionId); - } + public void OnMessage(QuickFix.FIX41.NewOrderSingle nos, SessionID sessionId) + { + ProcessNOS(nos, sessionId); + } - public void OnMessage(QuickFix.FIX42.NewOrderSingle nos, SessionID sessionId) - { - ProcessNOS(nos, sessionId); - } + public void OnMessage(QuickFix.FIX42.NewOrderSingle nos, SessionID sessionId) + { + ProcessNOS(nos, sessionId); + } - public void OnMessage(QuickFix.FIX42.SecurityDefinition message, SessionID sessionId) - { - Echo(message, sessionId); - } + public void OnMessage(QuickFix.FIX42.SecurityDefinition message, SessionID sessionId) + { + Echo(message, sessionId); + } - public void OnMessage(QuickFix.FIX43.NewOrderSingle nos, SessionID sessionId) - { - ProcessNOS(nos, sessionId); - } + public void OnMessage(QuickFix.FIX43.NewOrderSingle nos, SessionID sessionId) + { + ProcessNOS(nos, sessionId); + } - public void OnMessage(QuickFix.FIX43.SecurityDefinition message, SessionID sessionId) - { - Echo(message, sessionId); - } + public void OnMessage(QuickFix.FIX43.SecurityDefinition message, SessionID sessionId) + { + Echo(message, sessionId); + } - public void OnMessage(QuickFix.FIX44.NewOrderSingle nos, SessionID sessionId) - { - ProcessNOS(nos, sessionId); - } + public void OnMessage(QuickFix.FIX44.NewOrderSingle nos, SessionID sessionId) + { + ProcessNOS(nos, sessionId); + } - public void OnMessage(QuickFix.FIX44.SecurityDefinition message, SessionID sessionId) - { - Echo(message, sessionId); - } + public void OnMessage(QuickFix.FIX44.SecurityDefinition message, SessionID sessionId) + { + Echo(message, sessionId); + } - public void OnMessage(QuickFix.FIX44.QuoteRequest message, SessionID sessionId) - { - Echo(message, sessionId); - } + public void OnMessage(QuickFix.FIX44.QuoteRequest message, SessionID sessionId) + { + Echo(message, sessionId); + } - public void OnMessage(QuickFix.FIX50.NewOrderSingle nos, SessionID sessionId) - { - ProcessNOS(nos, sessionId); - } + public void OnMessage(QuickFix.FIX50.NewOrderSingle nos, SessionID sessionId) + { + ProcessNOS(nos, sessionId); + } - public void OnMessage(QuickFix.FIX50.SecurityDefinition message, SessionID sessionId) - { - Echo(message, sessionId); - } + public void OnMessage(QuickFix.FIX50.SecurityDefinition message, SessionID sessionId) + { + Echo(message, sessionId); + } - public void OnMessage(QuickFix.FIX50SP1.NewOrderSingle nos, SessionID sessionId) - { - ProcessNOS(nos, sessionId); - } + public void OnMessage(QuickFix.FIX50SP1.NewOrderSingle nos, SessionID sessionId) + { + ProcessNOS(nos, sessionId); + } - public void OnMessage(QuickFix.FIX50SP1.SecurityDefinition message, SessionID sessionId) - { - Echo(message, sessionId); - } + public void OnMessage(QuickFix.FIX50SP1.SecurityDefinition message, SessionID sessionId) + { + Echo(message, sessionId); + } - public void OnMessage(QuickFix.FIX50SP2.NewOrderSingle nos, SessionID sessionId) - { - ProcessNOS(nos, sessionId); - } + public void OnMessage(QuickFix.FIX50SP2.NewOrderSingle nos, SessionID sessionId) + { + ProcessNOS(nos, sessionId); + } - public void OnMessage(QuickFix.FIX50SP2.SecurityDefinition message, SessionID sessionId) - { - Echo(message, sessionId); - } + public void OnMessage(QuickFix.FIX50SP2.SecurityDefinition message, SessionID sessionId) + { + Echo(message, sessionId); + } - private static void Echo(Message message, SessionID sessionId) - { - Message echo = new(message); - Session.SendToTarget(echo, sessionId); - } + private static void Echo(Message message, SessionID sessionId) + { + Message echo = new(message); + Session.SendToTarget(echo, sessionId); + } - private void ProcessNOS(Message message, SessionID sessionId) - { - Message echo = new(message); + private void ProcessNOS(Message message, SessionID sessionId) + { + Message echo = new(message); - bool possResend = false; - if (message.Header.IsSetField(Tags.PossResend)) - possResend = message.Header.GetBoolean(Tags.PossResend); + bool possResend = false; + if (message.Header.IsSetField(Tags.PossResend)) + possResend = message.Header.GetBoolean(Tags.PossResend); - KeyValuePair pair = new(message.GetString(Tags.ClOrdID), sessionId); - if (possResend && _clOrdIDs.Contains(pair)) - return; - _clOrdIDs.Add(pair); + KeyValuePair pair = new(message.GetString(Tags.ClOrdID), sessionId); + if (possResend && _clOrdIDs.Contains(pair)) + return; + _clOrdIDs.Add(pair); - Session.SendToTarget(echo, sessionId); - } + Session.SendToTarget(echo, sessionId); + } - private static Message CreateNewsReply(Message source, string headlineString) { - string beginString = Message.ExtractBeginString(source.ToString()); + private static Message CreateNewsReply(Message source, string headlineString) { + string beginString = Message.ExtractBeginString(source.ToString()); - Message response = new(); - response.Header.SetField(new BeginString(beginString)); - response.Header.SetField(new MsgType("B")); - response.SetField(new Headline(headlineString)); + Message response = new(); + response.Header.SetField(new BeginString(beginString)); + response.Header.SetField(new MsgType("B")); + response.SetField(new Headline(headlineString)); - return response; - } + return response; + } - public void OnMessage(QuickFix.FIX41.News news, SessionID sessionId) { ProcessNews(news, sessionId); } - public void OnMessage(QuickFix.FIX42.News news, SessionID sessionId) { ProcessNews(news, sessionId); } - public void OnMessage(QuickFix.FIX43.News news, SessionID sessionId) { ProcessNews(news, sessionId); } - public void OnMessage(QuickFix.FIX44.News news, SessionID sessionId) { ProcessNews(news, sessionId); } - public void OnMessage(QuickFix.FIX50.News news, SessionID sessionId) { ProcessNews(news, sessionId); } - public void OnMessage(QuickFix.FIX50SP1.News news, SessionID sessionId) { ProcessNews(news, sessionId); } - public void OnMessage(QuickFix.FIX50SP2.News news, SessionID sessionId) { ProcessNews(news, sessionId); } + public void OnMessage(QuickFix.FIX41.News news, SessionID sessionId) { ProcessNews(news, sessionId); } + public void OnMessage(QuickFix.FIX42.News news, SessionID sessionId) { ProcessNews(news, sessionId); } + public void OnMessage(QuickFix.FIX43.News news, SessionID sessionId) { ProcessNews(news, sessionId); } + public void OnMessage(QuickFix.FIX44.News news, SessionID sessionId) { ProcessNews(news, sessionId); } + public void OnMessage(QuickFix.FIX50.News news, SessionID sessionId) { ProcessNews(news, sessionId); } + public void OnMessage(QuickFix.FIX50SP1.News news, SessionID sessionId) { ProcessNews(news, sessionId); } + public void OnMessage(QuickFix.FIX50SP2.News news, SessionID sessionId) { ProcessNews(news, sessionId); } - private void ProcessNews(Message msg, SessionID sessionId) + private void ProcessNews(Message msg, SessionID sessionId) + { + if (msg.IsSetField(Tags.Headline)) { - if (msg.IsSetField(Tags.Headline)) + string headline = msg.GetString(Tags.Headline); + if (headline == "STOPME" && StopMeEvent is not null) { - string headline = msg.GetString(Tags.Headline); - if (headline == "STOPME" && StopMeEvent is not null) - { - StopMeEvent(); - } - else if (headline.StartsWith("echo:")) - { - Match match = Regex.Match(headline, "echo: *(.*)"); - Message reply = CreateNewsReply(msg, match.Groups[1].Value); - - if (msg.Header.IsSetField(Tags.MessageEncoding)) - reply.Header.SetField(new MessageEncoding(msg.Header.GetString(Tags.MessageEncoding))); - if (msg.IsSetField(Tags.EncodedHeadline)) - reply.SetField(new EncodedHeadline(msg.GetString(Tags.EncodedHeadline))); - - Session.SendToTarget(reply, sessionId); - } + StopMeEvent(); } - } + else if (headline.StartsWith("echo:")) + { + Match match = Regex.Match(headline, "echo: *(.*)"); + Message reply = CreateNewsReply(msg, match.Groups[1].Value); - public void OnMessage(QuickFix.FIX44.TradeCaptureReportRequest msg, SessionID sessionId) - { - // do nothing, just swallow it. + if (msg.Header.IsSetField(Tags.MessageEncoding)) + reply.Header.SetField(new MessageEncoding(msg.Header.GetString(Tags.MessageEncoding))); + if (msg.IsSetField(Tags.EncodedHeadline)) + reply.SetField(new EncodedHeadline(msg.GetString(Tags.EncodedHeadline))); + + Session.SendToTarget(reply, sessionId); + } } + } - #region Application Methods + public void OnMessage(QuickFix.FIX44.TradeCaptureReportRequest msg, SessionID sessionId) + { + // do nothing, just swallow it. + } - public void OnCreate(SessionID sessionId) - { - Session? session = Session.LookupSession(sessionId); + #region Application Methods - // Hey QF/N users, don't do this in a real app. - session?.Reset("AT Session Reset"); - } + public void OnCreate(SessionID sessionId) + { + Session? session = Session.LookupSession(sessionId); - public void OnLogout(SessionID sessionId) - { - _clOrdIDs.Clear(); - } + // Hey QF/N users, don't do this in a real app. + session?.Reset("AT Session Reset"); + } - public void OnLogon(SessionID sessionId) - { } + public void OnLogout(SessionID sessionId) + { + _clOrdIDs.Clear(); + } - public void FromApp(Message message, SessionID sessionId) + public void OnLogon(SessionID sessionId) + { } + + public void FromApp(Message message, SessionID sessionId) + { + try { - try - { - //string msgType = message.Header.GetString(QuickFix.Fields.Tags.MsgType); - // log_.OnEvent("Got message " + msgType); - // System.Console.WriteLine("===got message " + msgType); + //string msgType = message.Header.GetString(QuickFix.Fields.Tags.MsgType); + // log_.OnEvent("Got message " + msgType); + // System.Console.WriteLine("===got message " + msgType); - Crack(message, sessionId); - } - catch (UnsupportedMessageType) - { - throw; - } - catch (System.Exception e) - { - Session.LookupSession(sessionId)?.Log.Log(LogLevel.Error, e, - "Exception during FromApp: {Error}\n while processing msg ({Message})", e, message); - } + Crack(message, sessionId); + } + catch (UnsupportedMessageType) + { + throw; } + catch (System.Exception e) + { + Session.LookupSession(sessionId)?.Log.Log(LogLevel.Error, e, + "Exception during FromApp: {Error}\n while processing msg ({Message})", e, message); + } + } - public void FromAdmin(Message msg, SessionID sessionId) { - if (msg.Header.GetString(35) == "n") { - string seqNo = msg.Header.GetString(34); - Session.SendToTarget( - CreateNewsReply(msg, $"Successfully received 'n' message with seqNo={seqNo}"), - sessionId); - } + public void FromAdmin(Message msg, SessionID sessionId) { + if (msg.Header.GetString(35) == "n") { + string seqNo = msg.Header.GetString(34); + Session.SendToTarget( + CreateNewsReply(msg, $"Successfully received 'n' message with seqNo={seqNo}"), + sessionId); } + } - public void ToAdmin(Message message, SessionID sessionId) { } - public void ToApp(Message message, SessionID sessionId) { } + public void ToAdmin(Message message, SessionID sessionId) { } + public void ToApp(Message message, SessionID sessionId) { } - #endregion - } + #endregion } From 3b077c5125223dab3947cbf0a03f7bf2ccd81caa Mon Sep 17 00:00:00 2001 From: Grant Birchmeier Date: Tue, 14 Apr 2026 10:59:40 -0500 Subject: [PATCH 4/4] use file-scoped namespaces - Examples --- Examples/Executor/Executor.cs | 1137 +++++++++--------- Examples/Executor/Program.cs | 96 +- Examples/FixToJson/Program.cs | 175 ++- Examples/JsonToFix/Program.cs | 107 +- Examples/SimpleAcceptor/Program.cs | 86 +- Examples/SimpleAcceptor/SimpleAcceptorApp.cs | 57 +- Examples/TradeClient/Program.cs | 98 +- Examples/TradeClient/TradeClientApp.cs | 667 +++++----- 8 files changed, 1206 insertions(+), 1217 deletions(-) diff --git a/Examples/Executor/Executor.cs b/Examples/Executor/Executor.cs index 6e4ec5c27..f49229d1f 100644 --- a/Examples/Executor/Executor.cs +++ b/Examples/Executor/Executor.cs @@ -3,599 +3,598 @@ using QuickFix; using QuickFix.Fields; -namespace Executor +namespace Executor; + +public class Executor : QuickFix.MessageCracker, QuickFix.IApplication { - public class Executor : QuickFix.MessageCracker, QuickFix.IApplication + static readonly decimal DEFAULT_MARKET_PRICE = 10; + + int orderID = 0; + int execID = 0; + + private string GenOrderID() { return (++orderID).ToString(); } + private string GenExecID() { return (++execID).ToString(); } + + #region QuickFix.Application Methods + + public void FromApp(Message message, SessionID sessionID) { - static readonly decimal DEFAULT_MARKET_PRICE = 10; - - int orderID = 0; - int execID = 0; - - private string GenOrderID() { return (++orderID).ToString(); } - private string GenExecID() { return (++execID).ToString(); } - - #region QuickFix.Application Methods - - public void FromApp(Message message, SessionID sessionID) - { - Console.WriteLine("IN: " + message); - Crack(message, sessionID); - } - - public void ToApp(Message message, SessionID sessionID) - { - Console.WriteLine("OUT: " + message); - } - - public void FromAdmin(Message message, SessionID sessionID) { } - public void OnCreate(SessionID sessionID) { } - public void OnLogout(SessionID sessionID) { } - public void OnLogon(SessionID sessionID) { } - public void ToAdmin(Message message, SessionID sessionID) { } - #endregion - - #region MessageCracker overloads - public void OnMessage(QuickFix.FIX40.NewOrderSingle n, SessionID s) - { - Symbol symbol = n.Symbol; - Side side = n.Side; - OrdType ordType = n.OrdType; - OrderQty orderQty = n.OrderQty; - Price price = new Price(DEFAULT_MARKET_PRICE); - ClOrdID clOrdID = n.ClOrdID; - - switch (ordType.Value) - { - case OrdType.LIMIT: - price = n.Price; - if (price.Value == 0) - throw new IncorrectTagValue(price.Tag); - break; - case OrdType.MARKET: break; - default: throw new IncorrectTagValue(ordType.Tag); - } - - QuickFix.FIX40.ExecutionReport exReport = new QuickFix.FIX40.ExecutionReport( - new OrderID(GenOrderID()), - new ExecID(GenExecID()), - new ExecTransType(ExecTransType.NEW), - new OrdStatus(OrdStatus.FILLED), - symbol, - side, - orderQty, - new LastShares(orderQty.Value), - new LastPx(price.Value), - new CumQty(orderQty.Value), - new AvgPx(price.Value)); - - exReport.Set(clOrdID); - - if (n.IsSetAccount()) - exReport.SetField(n.Account); - - try - { - Session.SendToTarget(exReport, s); - } - catch (SessionNotFound ex) - { - Console.WriteLine("==session not found exception!=="); - Console.WriteLine(ex.ToString()); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX41.NewOrderSingle n, SessionID s) - { - Symbol symbol = n.Symbol; - Side side = n.Side; - OrdType ordType = n.OrdType; - OrderQty orderQty = n.OrderQty; - Price price = new Price(DEFAULT_MARKET_PRICE); - ClOrdID clOrdID = n.ClOrdID; - - switch (ordType.Value) - { - case OrdType.LIMIT: - price = n.Price; - if (price.Value == 0) - throw new IncorrectTagValue(price.Tag); - break; - case OrdType.MARKET: break; - default: throw new IncorrectTagValue(ordType.Tag); - } - - QuickFix.FIX41.ExecutionReport exReport = new QuickFix.FIX41.ExecutionReport( - new OrderID(GenOrderID()), - new ExecID(GenExecID()), - new ExecTransType(ExecTransType.NEW), - new ExecType(ExecType.FILL), - new OrdStatus(OrdStatus.FILLED), - symbol, - side, - orderQty, - new LastShares(orderQty.Value), - new LastPx(price.Value), - new LeavesQty(0), - new CumQty(orderQty.Value), - new AvgPx(price.Value)); - - exReport.Set(clOrdID); - - if (n.IsSetAccount()) - exReport.SetField(n.Account); - - try - { - Session.SendToTarget(exReport, s); - } - catch (SessionNotFound ex) - { - Console.WriteLine("==session not found exception!=="); - Console.WriteLine(ex.ToString()); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX42.NewOrderSingle n, SessionID s) - { - Symbol symbol = n.Symbol; - Side side = n.Side; - OrdType ordType = n.OrdType; - OrderQty orderQty = n.OrderQty; - ClOrdID clOrdID = n.ClOrdID; - Price price = new Price(DEFAULT_MARKET_PRICE); - - switch (ordType.Value) - { - case OrdType.LIMIT: - price = n.Price; - if (price.Value == 0) - throw new IncorrectTagValue(price.Tag); - break; - case OrdType.MARKET: break; - default: throw new IncorrectTagValue(ordType.Tag); - } - - QuickFix.FIX42.ExecutionReport exReport = new QuickFix.FIX42.ExecutionReport( - new OrderID(GenOrderID()), - new ExecID(GenExecID()), - new ExecTransType(ExecTransType.NEW), - new ExecType(ExecType.FILL), - new OrdStatus(OrdStatus.FILLED), - symbol, - side, - new LeavesQty(0), - new CumQty(orderQty.Value), - new AvgPx(price.Value)); - - exReport.Set(clOrdID); - exReport.Set(orderQty); - exReport.Set(new LastShares(orderQty.Value)); - exReport.Set(new LastPx(price.Value)); - - if (n.IsSetAccount()) - exReport.SetField(n.Account); - - try - { - Session.SendToTarget(exReport, s); - } - catch (SessionNotFound ex) - { - Console.WriteLine("==session not found exception!=="); - Console.WriteLine(ex.ToString()); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX43.NewOrderSingle n, SessionID s) - { - Symbol symbol = n.Symbol; - Side side = n.Side; - OrdType ordType = n.OrdType; - OrderQty orderQty = n.OrderQty; - Price price = new Price(DEFAULT_MARKET_PRICE); - ClOrdID clOrdID = n.ClOrdID; - - switch (ordType.Value) - { - case OrdType.LIMIT: - price = n.Price; - if (price.Value == 0) - throw new IncorrectTagValue(price.Tag); - break; - case OrdType.MARKET: break; - default: throw new IncorrectTagValue(ordType.Tag); - } - - QuickFix.FIX43.ExecutionReport exReport = new QuickFix.FIX43.ExecutionReport( - new OrderID(GenOrderID()), - new ExecID(GenExecID()), - new ExecType(ExecType.FILL), - new OrdStatus(OrdStatus.FILLED), - symbol, // Shouldn't be here? - side, - new LeavesQty(0), - new CumQty(orderQty.Value), - new AvgPx(price.Value)); - - exReport.Set(clOrdID); - exReport.Set(symbol); - exReport.Set(orderQty); - exReport.Set(new LastQty(orderQty.Value)); - exReport.Set(new LastPx(price.Value)); - - if (n.IsSetAccount()) - exReport.SetField(n.Account); - - try - { - Session.SendToTarget(exReport, s); - } - catch (SessionNotFound ex) - { - Console.WriteLine("==session not found exception!=="); - Console.WriteLine(ex.ToString()); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX44.NewOrderSingle n, SessionID s) - { - Symbol symbol = n.Symbol; - Side side = n.Side; - OrdType ordType = n.OrdType; - OrderQty orderQty = n.OrderQty; - Price price = new Price(DEFAULT_MARKET_PRICE); - ClOrdID clOrdID = n.ClOrdID; - - switch (ordType.Value) - { - case OrdType.LIMIT: - price = n.Price; - if (price.Value == 0) - throw new IncorrectTagValue(price.Tag); - break; - case OrdType.MARKET: break; - default: throw new IncorrectTagValue(ordType.Tag); - } - - QuickFix.FIX44.ExecutionReport exReport = new QuickFix.FIX44.ExecutionReport( - new OrderID(GenOrderID()), - new ExecID(GenExecID()), - new ExecType(ExecType.FILL), - new OrdStatus(OrdStatus.FILLED), - symbol, //shouldn't be here? - side, - new LeavesQty(0), - new CumQty(orderQty.Value), - new AvgPx(price.Value)); - - exReport.Set(clOrdID); - exReport.Set(symbol); - exReport.Set(orderQty); - exReport.Set(new LastQty(orderQty.Value)); - exReport.Set(new LastPx(price.Value)); - - if (n.IsSetAccount()) - exReport.SetField(n.Account); - - try - { - Session.SendToTarget(exReport, s); - } - catch (SessionNotFound ex) - { - Console.WriteLine("==session not found exception!=="); - Console.WriteLine(ex.ToString()); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX50.NewOrderSingle n, SessionID s) - { - Symbol symbol = n.Symbol; - Side side = n.Side; - OrdType ordType = n.OrdType; - OrderQty orderQty = n.OrderQty; - Price price = new Price(DEFAULT_MARKET_PRICE); - ClOrdID clOrdID = n.ClOrdID; - - switch (ordType.Value) - { - case OrdType.LIMIT: - price = n.Price; - if (price.Value == 0) - throw new IncorrectTagValue(price.Tag); - break; - case OrdType.MARKET: break; - default: throw new IncorrectTagValue(ordType.Tag); - } - - QuickFix.FIX50.ExecutionReport exReport = new QuickFix.FIX50.ExecutionReport( - new OrderID(GenOrderID()), - new ExecID(GenExecID()), - new ExecType(ExecType.FILL), - new OrdStatus(OrdStatus.FILLED), - side, - new LeavesQty(0), - new CumQty(orderQty.Value)); - - exReport.Set(clOrdID); - exReport.Set(symbol); - exReport.Set(orderQty); - exReport.Set(new LastQty(orderQty.Value)); - exReport.Set(new LastPx(price.Value)); - exReport.Set(new AvgPx(price.Value)); - - if (n.IsSetAccount()) - exReport.SetField(n.Account); - - try - { - Session.SendToTarget(exReport, s); - } - catch (SessionNotFound ex) - { - Console.WriteLine("==session not found exception!=="); - Console.WriteLine(ex.ToString()); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX40.News n, SessionID s) { } - public void OnMessage(QuickFix.FIX41.News n, SessionID s) { } - public void OnMessage(QuickFix.FIX42.News n, SessionID s) { } - public void OnMessage(QuickFix.FIX43.News n, SessionID s) { } - public void OnMessage(QuickFix.FIX44.News n, SessionID s) { } - public void OnMessage(QuickFix.FIX50.News n, SessionID s) { } - - public void OnMessage(QuickFix.FIX40.OrderCancelRequest msg, SessionID s) - { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX40.OrderCancelReject ocj = new QuickFix.FIX40.OrderCancelReject(new OrderID(orderid), msg.ClOrdID); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); - ocj.Text = new Text("Executor does not support order cancels"); - - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX41.OrderCancelRequest msg, SessionID s) - { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX41.OrderCancelReject ocj = new QuickFix.FIX41.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); - ocj.Text = new Text("Executor does not support order cancels"); - - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX42.OrderCancelRequest msg, SessionID s) - { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX42.OrderCancelReject ocj = new QuickFix.FIX42.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REQUEST)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); - ocj.Text = new Text("Executor does not support order cancels"); - - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX43.OrderCancelRequest msg, SessionID s) - { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX43.OrderCancelReject ocj = new QuickFix.FIX43.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REQUEST)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); - ocj.Text = new Text("Executor does not support order cancels"); - - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX44.OrderCancelRequest msg, SessionID s) - { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX44.OrderCancelReject ocj = new QuickFix.FIX44.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REQUEST)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.OTHER); - ocj.Text = new Text("Executor does not support order cancels"); - - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX50.OrderCancelRequest msg, SessionID s) - { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX50.OrderCancelReject ocj = new QuickFix.FIX50.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REQUEST)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.OTHER); - ocj.Text = new Text("Executor does not support order cancels"); - - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - - - public void OnMessage(QuickFix.FIX40.OrderCancelReplaceRequest msg, SessionID s) - { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX40.OrderCancelReject ocj = new QuickFix.FIX40.OrderCancelReject(new OrderID(orderid), msg.ClOrdID); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); - ocj.Text = new Text("Executor does not support order cancel/replaces"); - - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - public void OnMessage(QuickFix.FIX41.OrderCancelReplaceRequest msg, SessionID s) - { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX41.OrderCancelReject ocj = new QuickFix.FIX41.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); - ocj.Text = new Text("Executor does not support order cancel/replaces"); + Console.WriteLine("IN: " + message); + Crack(message, sessionID); + } - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } + public void ToApp(Message message, SessionID sessionID) + { + Console.WriteLine("OUT: " + message); + } + + public void FromAdmin(Message message, SessionID sessionID) { } + public void OnCreate(SessionID sessionID) { } + public void OnLogout(SessionID sessionID) { } + public void OnLogon(SessionID sessionID) { } + public void ToAdmin(Message message, SessionID sessionID) { } + #endregion + + #region MessageCracker overloads + public void OnMessage(QuickFix.FIX40.NewOrderSingle n, SessionID s) + { + Symbol symbol = n.Symbol; + Side side = n.Side; + OrdType ordType = n.OrdType; + OrderQty orderQty = n.OrderQty; + Price price = new Price(DEFAULT_MARKET_PRICE); + ClOrdID clOrdID = n.ClOrdID; + + switch (ordType.Value) + { + case OrdType.LIMIT: + price = n.Price; + if (price.Value == 0) + throw new IncorrectTagValue(price.Tag); + break; + case OrdType.MARKET: break; + default: throw new IncorrectTagValue(ordType.Tag); + } + + QuickFix.FIX40.ExecutionReport exReport = new QuickFix.FIX40.ExecutionReport( + new OrderID(GenOrderID()), + new ExecID(GenExecID()), + new ExecTransType(ExecTransType.NEW), + new OrdStatus(OrdStatus.FILLED), + symbol, + side, + orderQty, + new LastShares(orderQty.Value), + new LastPx(price.Value), + new CumQty(orderQty.Value), + new AvgPx(price.Value)); + + exReport.Set(clOrdID); + + if (n.IsSetAccount()) + exReport.SetField(n.Account); + + try + { + Session.SendToTarget(exReport, s); + } + catch (SessionNotFound ex) + { + Console.WriteLine("==session not found exception!=="); + Console.WriteLine(ex.ToString()); } - - public void OnMessage(QuickFix.FIX42.OrderCancelReplaceRequest msg, SessionID s) + catch (Exception ex) { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX42.OrderCancelReject ocj = new QuickFix.FIX42.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REPLACE_REQUEST)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); - ocj.Text = new Text("Executor does not support order cancel/replaces"); + Console.WriteLine(ex.ToString()); + } + } - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } + public void OnMessage(QuickFix.FIX41.NewOrderSingle n, SessionID s) + { + Symbol symbol = n.Symbol; + Side side = n.Side; + OrdType ordType = n.OrdType; + OrderQty orderQty = n.OrderQty; + Price price = new Price(DEFAULT_MARKET_PRICE); + ClOrdID clOrdID = n.ClOrdID; + + switch (ordType.Value) + { + case OrdType.LIMIT: + price = n.Price; + if (price.Value == 0) + throw new IncorrectTagValue(price.Tag); + break; + case OrdType.MARKET: break; + default: throw new IncorrectTagValue(ordType.Tag); } - public void OnMessage(QuickFix.FIX43.OrderCancelReplaceRequest msg, SessionID s) + QuickFix.FIX41.ExecutionReport exReport = new QuickFix.FIX41.ExecutionReport( + new OrderID(GenOrderID()), + new ExecID(GenExecID()), + new ExecTransType(ExecTransType.NEW), + new ExecType(ExecType.FILL), + new OrdStatus(OrdStatus.FILLED), + symbol, + side, + orderQty, + new LastShares(orderQty.Value), + new LastPx(price.Value), + new LeavesQty(0), + new CumQty(orderQty.Value), + new AvgPx(price.Value)); + + exReport.Set(clOrdID); + + if (n.IsSetAccount()) + exReport.SetField(n.Account); + + try { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX43.OrderCancelReject ocj = new QuickFix.FIX43.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REPLACE_REQUEST)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); - ocj.Text = new Text("Executor does not support order cancel/replaces"); + Session.SendToTarget(exReport, s); + } + catch (SessionNotFound ex) + { + Console.WriteLine("==session not found exception!=="); + Console.WriteLine(ex.ToString()); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX42.NewOrderSingle n, SessionID s) + { + Symbol symbol = n.Symbol; + Side side = n.Side; + OrdType ordType = n.OrdType; + OrderQty orderQty = n.OrderQty; + ClOrdID clOrdID = n.ClOrdID; + Price price = new Price(DEFAULT_MARKET_PRICE); + + switch (ordType.Value) + { + case OrdType.LIMIT: + price = n.Price; + if (price.Value == 0) + throw new IncorrectTagValue(price.Tag); + break; + case OrdType.MARKET: break; + default: throw new IncorrectTagValue(ordType.Tag); + } - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } + QuickFix.FIX42.ExecutionReport exReport = new QuickFix.FIX42.ExecutionReport( + new OrderID(GenOrderID()), + new ExecID(GenExecID()), + new ExecTransType(ExecTransType.NEW), + new ExecType(ExecType.FILL), + new OrdStatus(OrdStatus.FILLED), + symbol, + side, + new LeavesQty(0), + new CumQty(orderQty.Value), + new AvgPx(price.Value)); + + exReport.Set(clOrdID); + exReport.Set(orderQty); + exReport.Set(new LastShares(orderQty.Value)); + exReport.Set(new LastPx(price.Value)); + + if (n.IsSetAccount()) + exReport.SetField(n.Account); + + try + { + Session.SendToTarget(exReport, s); + } + catch (SessionNotFound ex) + { + Console.WriteLine("==session not found exception!=="); + Console.WriteLine(ex.ToString()); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX43.NewOrderSingle n, SessionID s) + { + Symbol symbol = n.Symbol; + Side side = n.Side; + OrdType ordType = n.OrdType; + OrderQty orderQty = n.OrderQty; + Price price = new Price(DEFAULT_MARKET_PRICE); + ClOrdID clOrdID = n.ClOrdID; + + switch (ordType.Value) + { + case OrdType.LIMIT: + price = n.Price; + if (price.Value == 0) + throw new IncorrectTagValue(price.Tag); + break; + case OrdType.MARKET: break; + default: throw new IncorrectTagValue(ordType.Tag); } - public void OnMessage(QuickFix.FIX44.OrderCancelReplaceRequest msg, SessionID s) + QuickFix.FIX43.ExecutionReport exReport = new QuickFix.FIX43.ExecutionReport( + new OrderID(GenOrderID()), + new ExecID(GenExecID()), + new ExecType(ExecType.FILL), + new OrdStatus(OrdStatus.FILLED), + symbol, // Shouldn't be here? + side, + new LeavesQty(0), + new CumQty(orderQty.Value), + new AvgPx(price.Value)); + + exReport.Set(clOrdID); + exReport.Set(symbol); + exReport.Set(orderQty); + exReport.Set(new LastQty(orderQty.Value)); + exReport.Set(new LastPx(price.Value)); + + if (n.IsSetAccount()) + exReport.SetField(n.Account); + + try { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX44.OrderCancelReject ocj = new QuickFix.FIX44.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REPLACE_REQUEST)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.OTHER); - ocj.Text = new Text("Executor does not support order cancel/replaces"); + Session.SendToTarget(exReport, s); + } + catch (SessionNotFound ex) + { + Console.WriteLine("==session not found exception!=="); + Console.WriteLine(ex.ToString()); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } + public void OnMessage(QuickFix.FIX44.NewOrderSingle n, SessionID s) + { + Symbol symbol = n.Symbol; + Side side = n.Side; + OrdType ordType = n.OrdType; + OrderQty orderQty = n.OrderQty; + Price price = new Price(DEFAULT_MARKET_PRICE); + ClOrdID clOrdID = n.ClOrdID; + + switch (ordType.Value) + { + case OrdType.LIMIT: + price = n.Price; + if (price.Value == 0) + throw new IncorrectTagValue(price.Tag); + break; + case OrdType.MARKET: break; + default: throw new IncorrectTagValue(ordType.Tag); } - public void OnMessage(QuickFix.FIX50.OrderCancelReplaceRequest msg, SessionID s) + QuickFix.FIX44.ExecutionReport exReport = new QuickFix.FIX44.ExecutionReport( + new OrderID(GenOrderID()), + new ExecID(GenExecID()), + new ExecType(ExecType.FILL), + new OrdStatus(OrdStatus.FILLED), + symbol, //shouldn't be here? + side, + new LeavesQty(0), + new CumQty(orderQty.Value), + new AvgPx(price.Value)); + + exReport.Set(clOrdID); + exReport.Set(symbol); + exReport.Set(orderQty); + exReport.Set(new LastQty(orderQty.Value)); + exReport.Set(new LastPx(price.Value)); + + if (n.IsSetAccount()) + exReport.SetField(n.Account); + + try { - string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; - QuickFix.FIX50.OrderCancelReject ocj = new QuickFix.FIX50.OrderCancelReject( - new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REPLACE_REQUEST)); - ocj.CxlRejReason = new CxlRejReason(CxlRejReason.OTHER); - ocj.Text = new Text("Executor does not support order cancel/replaces"); + Session.SendToTarget(exReport, s); + } + catch (SessionNotFound ex) + { + Console.WriteLine("==session not found exception!=="); + Console.WriteLine(ex.ToString()); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } - try - { - Session.SendToTarget(ocj, s); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } + public void OnMessage(QuickFix.FIX50.NewOrderSingle n, SessionID s) + { + Symbol symbol = n.Symbol; + Side side = n.Side; + OrdType ordType = n.OrdType; + OrderQty orderQty = n.OrderQty; + Price price = new Price(DEFAULT_MARKET_PRICE); + ClOrdID clOrdID = n.ClOrdID; + + switch (ordType.Value) + { + case OrdType.LIMIT: + price = n.Price; + if (price.Value == 0) + throw new IncorrectTagValue(price.Tag); + break; + case OrdType.MARKET: break; + default: throw new IncorrectTagValue(ordType.Tag); } + QuickFix.FIX50.ExecutionReport exReport = new QuickFix.FIX50.ExecutionReport( + new OrderID(GenOrderID()), + new ExecID(GenExecID()), + new ExecType(ExecType.FILL), + new OrdStatus(OrdStatus.FILLED), + side, + new LeavesQty(0), + new CumQty(orderQty.Value)); + + exReport.Set(clOrdID); + exReport.Set(symbol); + exReport.Set(orderQty); + exReport.Set(new LastQty(orderQty.Value)); + exReport.Set(new LastPx(price.Value)); + exReport.Set(new AvgPx(price.Value)); + + if (n.IsSetAccount()) + exReport.SetField(n.Account); + + try + { + Session.SendToTarget(exReport, s); + } + catch (SessionNotFound ex) + { + Console.WriteLine("==session not found exception!=="); + Console.WriteLine(ex.ToString()); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + public void OnMessage(QuickFix.FIX40.News n, SessionID s) { } + public void OnMessage(QuickFix.FIX41.News n, SessionID s) { } + public void OnMessage(QuickFix.FIX42.News n, SessionID s) { } + public void OnMessage(QuickFix.FIX43.News n, SessionID s) { } + public void OnMessage(QuickFix.FIX44.News n, SessionID s) { } + public void OnMessage(QuickFix.FIX50.News n, SessionID s) { } + public void OnMessage(QuickFix.FIX40.OrderCancelRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX40.OrderCancelReject ocj = new QuickFix.FIX40.OrderCancelReject(new OrderID(orderid), msg.ClOrdID); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); + ocj.Text = new Text("Executor does not support order cancels"); - // FIX40-41 don't have rejects - public void OnMessage(QuickFix.FIX42.BusinessMessageReject n, SessionID s) { } - public void OnMessage(QuickFix.FIX43.BusinessMessageReject n, SessionID s) { } - public void OnMessage(QuickFix.FIX44.BusinessMessageReject n, SessionID s) { } - public void OnMessage(QuickFix.FIX50.BusinessMessageReject n, SessionID s) { } + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + public void OnMessage(QuickFix.FIX41.OrderCancelRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX41.OrderCancelReject ocj = new QuickFix.FIX41.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); + ocj.Text = new Text("Executor does not support order cancels"); - #endregion //MessageCracker overloads + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } } + + public void OnMessage(QuickFix.FIX42.OrderCancelRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX42.OrderCancelReject ocj = new QuickFix.FIX42.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REQUEST)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); + ocj.Text = new Text("Executor does not support order cancels"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX43.OrderCancelRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX43.OrderCancelReject ocj = new QuickFix.FIX43.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REQUEST)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); + ocj.Text = new Text("Executor does not support order cancels"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX44.OrderCancelRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX44.OrderCancelReject ocj = new QuickFix.FIX44.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REQUEST)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.OTHER); + ocj.Text = new Text("Executor does not support order cancels"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX50.OrderCancelRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX50.OrderCancelReject ocj = new QuickFix.FIX50.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REQUEST)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.OTHER); + ocj.Text = new Text("Executor does not support order cancels"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + + + public void OnMessage(QuickFix.FIX40.OrderCancelReplaceRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX40.OrderCancelReject ocj = new QuickFix.FIX40.OrderCancelReject(new OrderID(orderid), msg.ClOrdID); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); + ocj.Text = new Text("Executor does not support order cancel/replaces"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX41.OrderCancelReplaceRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX41.OrderCancelReject ocj = new QuickFix.FIX41.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); + ocj.Text = new Text("Executor does not support order cancel/replaces"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX42.OrderCancelReplaceRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX42.OrderCancelReject ocj = new QuickFix.FIX42.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REPLACE_REQUEST)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); + ocj.Text = new Text("Executor does not support order cancel/replaces"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX43.OrderCancelReplaceRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX43.OrderCancelReject ocj = new QuickFix.FIX43.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REPLACE_REQUEST)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.UNKNOWN_ORDER); + ocj.Text = new Text("Executor does not support order cancel/replaces"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX44.OrderCancelReplaceRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX44.OrderCancelReject ocj = new QuickFix.FIX44.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REPLACE_REQUEST)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.OTHER); + ocj.Text = new Text("Executor does not support order cancel/replaces"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + public void OnMessage(QuickFix.FIX50.OrderCancelReplaceRequest msg, SessionID s) + { + string orderid = (msg.IsSetOrderID()) ? msg.OrderID.Value : "unknown orderID"; + QuickFix.FIX50.OrderCancelReject ocj = new QuickFix.FIX50.OrderCancelReject( + new OrderID(orderid), msg.ClOrdID, msg.OrigClOrdID, new OrdStatus(OrdStatus.REJECTED), new CxlRejResponseTo(CxlRejResponseTo.ORDER_CANCEL_REPLACE_REQUEST)); + ocj.CxlRejReason = new CxlRejReason(CxlRejReason.OTHER); + ocj.Text = new Text("Executor does not support order cancel/replaces"); + + try + { + Session.SendToTarget(ocj, s); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + + + + // FIX40-41 don't have rejects + public void OnMessage(QuickFix.FIX42.BusinessMessageReject n, SessionID s) { } + public void OnMessage(QuickFix.FIX43.BusinessMessageReject n, SessionID s) { } + public void OnMessage(QuickFix.FIX44.BusinessMessageReject n, SessionID s) { } + public void OnMessage(QuickFix.FIX50.BusinessMessageReject n, SessionID s) { } + + + #endregion //MessageCracker overloads } diff --git a/Examples/Executor/Program.cs b/Examples/Executor/Program.cs index b5eb480d2..a33f9ccfb 100644 --- a/Examples/Executor/Program.cs +++ b/Examples/Executor/Program.cs @@ -1,66 +1,64 @@ using System; using Microsoft.Extensions.Logging; using QuickFix; -using QuickFix.Logger; using QuickFix.Store; -namespace Executor +namespace Executor; + +class Program { - class Program + private const string HttpServerPrefix = "http://127.0.0.1:5080/"; + + [STAThread] + static void Main(string[] args) { - private const string HttpServerPrefix = "http://127.0.0.1:5080/"; - - [STAThread] - static void Main(string[] args) + Console.WriteLine("============="); + Console.WriteLine("This is only an example program, meant to be used with the TradeClient example."); + Console.WriteLine("============="); + + if (args.Length != 1) { - Console.WriteLine("============="); - Console.WriteLine("This is only an example program, meant to be used with the TradeClient example."); - Console.WriteLine("============="); + Console.WriteLine("usage: Executor CONFIG_FILENAME"); + System.Environment.Exit(2); + } - if (args.Length != 1) - { - Console.WriteLine("usage: Executor CONFIG_FILENAME"); - System.Environment.Exit(2); - } + try + { + SessionSettings settings = new SessionSettings(args[0]); + IApplication executorApp = new Executor(); + IMessageStoreFactory storeFactory = new FileStoreFactory(settings); - try + /* + // legacy logging interface + ILogFactory logFactory = new ScreenLogFactory(settings); + ThreadedSocketAcceptor acceptor = new ThreadedSocketAcceptor(executorApp, storeFactory, settings, logFactory); + */ + + // v1.14: you can use Microsoft.Extensions.Logging instead + using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => { - SessionSettings settings = new SessionSettings(args[0]); - IApplication executorApp = new Executor(); - IMessageStoreFactory storeFactory = new FileStoreFactory(settings); + builder.SetMinimumLevel(LogLevel.Trace); + builder.AddConsole(); + }); + ThreadedSocketAcceptor acceptor = + new ThreadedSocketAcceptor(executorApp, storeFactory, settings, loggerFactory); - /* - // legacy logging interface - ILogFactory logFactory = new ScreenLogFactory(settings); - ThreadedSocketAcceptor acceptor = new ThreadedSocketAcceptor(executorApp, storeFactory, settings, logFactory); - */ + HttpServer srv = new HttpServer(HttpServerPrefix, settings); - // v1.14: you can use Microsoft.Extensions.Logging instead - using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => - { - builder.SetMinimumLevel(LogLevel.Trace); - builder.AddConsole(); - }); - ThreadedSocketAcceptor acceptor = - new ThreadedSocketAcceptor(executorApp, storeFactory, settings, loggerFactory); + acceptor.Start(); + srv.Start(); - HttpServer srv = new HttpServer(HttpServerPrefix, settings); - - acceptor.Start(); - srv.Start(); - - Console.WriteLine("View Executor status: "+HttpServerPrefix); - Console.WriteLine("press to quit"); - Console.Read(); - - srv.Stop(); - acceptor.Stop(); - } - catch (System.Exception e) - { - Console.WriteLine("==FATAL ERROR=="); - Console.WriteLine(e.ToString()); - } + Console.WriteLine("View Executor status: "+HttpServerPrefix); + Console.WriteLine("press to quit"); + Console.Read(); + + srv.Stop(); + acceptor.Stop(); + } + catch (System.Exception e) + { + Console.WriteLine("==FATAL ERROR=="); + Console.WriteLine(e.ToString()); } } } diff --git a/Examples/FixToJson/Program.cs b/Examples/FixToJson/Program.cs index 476a3df9c..ca0e9cd97 100644 --- a/Examples/FixToJson/Program.cs +++ b/Examples/FixToJson/Program.cs @@ -3,109 +3,108 @@ using System.IO; using System.Linq; -namespace Examples.FixToJson +namespace Examples.FixToJson; + +internal static class Program { - internal static class Program + static void FixToJson( + string fname, + bool humanReadableValues, + QuickFix.DataDictionary.DataDictionary? sessionDataDictionary, + QuickFix.DataDictionary.DataDictionary? appDataDictionary, + List? tagsToMask, + string? maskText) { - static void FixToJson( - string fname, - bool humanReadableValues, - QuickFix.DataDictionary.DataDictionary? sessionDataDictionary, - QuickFix.DataDictionary.DataDictionary? appDataDictionary, - List? tagsToMask, - string? maskText) + try { - try + Console.WriteLine("{\n\"messages\": ["); + using (StreamReader streamReader = new StreamReader(fname)) { - Console.WriteLine("{\n\"messages\": ["); - using (StreamReader streamReader = new StreamReader(fname)) + QuickFix.IMessageFactory msgFactory = new QuickFix.DefaultMessageFactory(); + QuickFix.Message msg = new QuickFix.Message(); + string comma = ""; + while (streamReader.ReadLine() is { } line) { - QuickFix.IMessageFactory msgFactory = new QuickFix.DefaultMessageFactory(); - QuickFix.Message msg = new QuickFix.Message(); - string comma = ""; - while (streamReader.ReadLine() is { } line) - { - line = line.Trim(); - msg.FromString(line, false, sessionDataDictionary, appDataDictionary, msgFactory); - if(maskText is not null) { - Console.WriteLine(comma + msg.ToJSON(appDataDictionary, convertEnumsToDescriptions: humanReadableValues, tagsToMask, maskText)); - } - else { - Console.WriteLine(comma + msg.ToJSON(appDataDictionary, convertEnumsToDescriptions: humanReadableValues, tagsToMask)); - } - comma = ","; + line = line.Trim(); + msg.FromString(line, false, sessionDataDictionary, appDataDictionary, msgFactory); + if(maskText is not null) { + Console.WriteLine(comma + msg.ToJSON(appDataDictionary, convertEnumsToDescriptions: humanReadableValues, tagsToMask, maskText)); + } + else { + Console.WriteLine(comma + msg.ToJSON(appDataDictionary, convertEnumsToDescriptions: humanReadableValues, tagsToMask)); } + comma = ","; } - Console.WriteLine("]\n}"); - - } - catch (Exception e) - { - Console.WriteLine(e.Message); - Console.WriteLine(e.StackTrace); } + Console.WriteLine("]\n}"); + + } + catch (Exception e) + { + Console.WriteLine(e.Message); + Console.WriteLine(e.StackTrace); } + } - [STAThread] - static void Main(string[] args) + [STAThread] + static void Main(string[] args) + { + if (args.Length < 1) { - if (args.Length < 1) - { - Console.WriteLine("USAGE"); - Console.WriteLine(""); - Console.WriteLine(" FixToJson.exe FILE [-h | --human-readable] [-d ] [-m | --mask ] [--mask-text ]"); - Console.WriteLine(""); - Console.WriteLine("EXAMPLES"); - Console.WriteLine(""); - Console.WriteLine(" FixToJson.exe messages.log -h -d ../../spec/fix/FIX50SP2.xml"); - Console.WriteLine(" FixToJson.exe messages.log -h -d ../../spec/fix/FIX44.xml -m 52,448,560 --masktext [MASK]"); - Console.WriteLine(" FixToJson.exe messages.log -d ../../spec/fix/FIX42.xml"); - Console.WriteLine(" FixToJson.exe messages.log -m 15,236,448"); - Console.WriteLine(""); - Console.WriteLine("NOTE"); - Console.WriteLine(""); - Console.WriteLine(" Per the FIX JSON Encoding Specification, tags are converted to human-readable form, but values are not."); - Console.WriteLine(" Set the -h or --human-readable flag to override the standard behavior. If the --human-readable flag is set a data dictionary must also be provided."); - Console.WriteLine(" If desired use the -m or --mask flag followed by a comma delimited list of tags that should be masked in the FIX JSON output."); - Console.WriteLine(" To specify custom text for the mask use the --mask-text flag followed by the text to use for masking."); - Environment.Exit(2); - } + Console.WriteLine("USAGE"); + Console.WriteLine(""); + Console.WriteLine(" FixToJson.exe FILE [-h | --human-readable] [-d ] [-m | --mask ] [--mask-text ]"); + Console.WriteLine(""); + Console.WriteLine("EXAMPLES"); + Console.WriteLine(""); + Console.WriteLine(" FixToJson.exe messages.log -h -d ../../spec/fix/FIX50SP2.xml"); + Console.WriteLine(" FixToJson.exe messages.log -h -d ../../spec/fix/FIX44.xml -m 52,448,560 --masktext [MASK]"); + Console.WriteLine(" FixToJson.exe messages.log -d ../../spec/fix/FIX42.xml"); + Console.WriteLine(" FixToJson.exe messages.log -m 15,236,448"); + Console.WriteLine(""); + Console.WriteLine("NOTE"); + Console.WriteLine(""); + Console.WriteLine(" Per the FIX JSON Encoding Specification, tags are converted to human-readable form, but values are not."); + Console.WriteLine(" Set the -h or --human-readable flag to override the standard behavior. If the --human-readable flag is set a data dictionary must also be provided."); + Console.WriteLine(" If desired use the -m or --mask flag followed by a comma delimited list of tags that should be masked in the FIX JSON output."); + Console.WriteLine(" To specify custom text for the mask use the --mask-text flag followed by the text to use for masking."); + Environment.Exit(2); + } - string fname = args[0]; - bool humanReadableValues = false; - QuickFix.DataDictionary.DataDictionary? sessionDataDictionary = null; - QuickFix.DataDictionary.DataDictionary? appDataDictionary = null; - List? tagsToMask = null; - string? maskText = null; + string fname = args[0]; + bool humanReadableValues = false; + QuickFix.DataDictionary.DataDictionary? sessionDataDictionary = null; + QuickFix.DataDictionary.DataDictionary? appDataDictionary = null; + List? tagsToMask = null; + string? maskText = null; - for (int i = 1; i < args.Length; i++) + for (int i = 1; i < args.Length; i++) + { + switch(args[i].ToLower()) { - switch(args[i].ToLower()) - { - case "-h": - case "--human-readable": - humanReadableValues = true; - break; - case "-d": - sessionDataDictionary = new QuickFix.DataDictionary.DataDictionary(args[++i]); - appDataDictionary = sessionDataDictionary; - break; - case "-m": - case "--mask": - tagsToMask = args[++i].Split(',').Select(int.Parse).ToList(); - break; - case "--mask-text": - maskText = args[++i]; - break; - default: - Console.WriteLine($"Unknown argument: {args[i]}"); - Environment.Exit(2); - break; - } + case "-h": + case "--human-readable": + humanReadableValues = true; + break; + case "-d": + sessionDataDictionary = new QuickFix.DataDictionary.DataDictionary(args[++i]); + appDataDictionary = sessionDataDictionary; + break; + case "-m": + case "--mask": + tagsToMask = args[++i].Split(',').Select(int.Parse).ToList(); + break; + case "--mask-text": + maskText = args[++i]; + break; + default: + Console.WriteLine($"Unknown argument: {args[i]}"); + Environment.Exit(2); + break; } - - FixToJson(fname, humanReadableValues, sessionDataDictionary, appDataDictionary, tagsToMask, maskText); - Environment.Exit(1); } + + FixToJson(fname, humanReadableValues, sessionDataDictionary, appDataDictionary, tagsToMask, maskText); + Environment.Exit(1); } } diff --git a/Examples/JsonToFix/Program.cs b/Examples/JsonToFix/Program.cs index 11775be98..5a298b7c2 100644 --- a/Examples/JsonToFix/Program.cs +++ b/Examples/JsonToFix/Program.cs @@ -3,74 +3,73 @@ using System.Text.Json; using QuickFix; -namespace Examples.JsonToFix +namespace Examples.JsonToFix; + +internal static class Program { - internal static class Program + static void JsonMsgToFix(string json, QuickFix.DataDictionary.DataDictionary sessionDataDictionary, QuickFix.DataDictionary.DataDictionary appDataDictionary, QuickFix.IMessageFactory msgFactory) { - static void JsonMsgToFix(string json, QuickFix.DataDictionary.DataDictionary sessionDataDictionary, QuickFix.DataDictionary.DataDictionary appDataDictionary, QuickFix.IMessageFactory msgFactory) - { - var msg = new Message(); - msg.FromJson(json, true, sessionDataDictionary, appDataDictionary, msgFactory); - Console.WriteLine(msg.ConstructString()); - } + var msg = new Message(); + msg.FromJson(json, true, sessionDataDictionary, appDataDictionary, msgFactory); + Console.WriteLine(msg.ConstructString()); + } - static void JsonToFix(string fname, QuickFix.DataDictionary.DataDictionary sessionDataDictionary, QuickFix.DataDictionary.DataDictionary appDataDictionary) + static void JsonToFix(string fname, QuickFix.DataDictionary.DataDictionary sessionDataDictionary, QuickFix.DataDictionary.DataDictionary appDataDictionary) + { + try { - try + QuickFix.IMessageFactory msgFactory = new QuickFix.DefaultMessageFactory(); + string json = File.ReadAllText(fname); + using (JsonDocument document = JsonDocument.Parse(json)) { - QuickFix.IMessageFactory msgFactory = new QuickFix.DefaultMessageFactory(); - string json = File.ReadAllText(fname); - using (JsonDocument document = JsonDocument.Parse(json)) + if (document.RootElement.TryGetProperty("messages", out JsonElement messagesElement)) { - if (document.RootElement.TryGetProperty("messages", out JsonElement messagesElement)) + foreach (JsonElement jsonMsg in messagesElement.EnumerateArray()) { - foreach (JsonElement jsonMsg in messagesElement.EnumerateArray()) - { - JsonMsgToFix(jsonMsg.ToString(), sessionDataDictionary, appDataDictionary, msgFactory); - } - } - else // assume there is only one message instead of an array of messages - { - JsonMsgToFix(json, sessionDataDictionary, appDataDictionary, msgFactory); + JsonMsgToFix(jsonMsg.ToString(), sessionDataDictionary, appDataDictionary, msgFactory); } } + else // assume there is only one message instead of an array of messages + { + JsonMsgToFix(json, sessionDataDictionary, appDataDictionary, msgFactory); + } } - catch (Exception e) - { - Console.WriteLine(e.Message); - Console.WriteLine(e.StackTrace); - } } + catch (Exception e) + { + Console.WriteLine(e.Message); + Console.WriteLine(e.StackTrace); + } + } - [STAThread] - static void Main(string[] args) + [STAThread] + static void Main(string[] args) + { + if (args.Length < 1 || args.Length > 2) { - if (args.Length < 1 || args.Length > 2) - { - Console.WriteLine("USAGE"); - Console.WriteLine(""); - Console.WriteLine(" FixToJson.exe FILE DATA_DICTIONARY"); - Console.WriteLine(""); - Console.WriteLine(" The FILE may contain either a single message in FIX JSON Encoding, or an array of messages in a root-level \"messages\" element."); - Console.WriteLine(""); - Console.WriteLine("EXAMPLES"); - Console.WriteLine(""); - Console.WriteLine(" JsonToFix.exe messages.json ../../spec/fix/FIX50SP2.xml"); - Console.WriteLine(" JsonToFix.exe messages.json ../../spec/fix/FIX44.xml"); - Console.WriteLine(" JsonToFix.exe messages.json ../../spec/fix/FIX42.xml"); - Console.WriteLine(""); - Console.WriteLine("NOTE"); - Console.WriteLine(""); - Console.WriteLine(" Per the FIX JSON Encoding Specification, tags are converted to human-readable form, but values are not."); - Environment.Exit(2); - } + Console.WriteLine("USAGE"); + Console.WriteLine(""); + Console.WriteLine(" FixToJson.exe FILE DATA_DICTIONARY"); + Console.WriteLine(""); + Console.WriteLine(" The FILE may contain either a single message in FIX JSON Encoding, or an array of messages in a root-level \"messages\" element."); + Console.WriteLine(""); + Console.WriteLine("EXAMPLES"); + Console.WriteLine(""); + Console.WriteLine(" JsonToFix.exe messages.json ../../spec/fix/FIX50SP2.xml"); + Console.WriteLine(" JsonToFix.exe messages.json ../../spec/fix/FIX44.xml"); + Console.WriteLine(" JsonToFix.exe messages.json ../../spec/fix/FIX42.xml"); + Console.WriteLine(""); + Console.WriteLine("NOTE"); + Console.WriteLine(""); + Console.WriteLine(" Per the FIX JSON Encoding Specification, tags are converted to human-readable form, but values are not."); + Environment.Exit(2); + } - string fname = args[0]; - QuickFix.DataDictionary.DataDictionary sessionDataDictionary = new QuickFix.DataDictionary.DataDictionary(args[1]); - QuickFix.DataDictionary.DataDictionary appDataDictionary = sessionDataDictionary; + string fname = args[0]; + QuickFix.DataDictionary.DataDictionary sessionDataDictionary = new QuickFix.DataDictionary.DataDictionary(args[1]); + QuickFix.DataDictionary.DataDictionary appDataDictionary = sessionDataDictionary; - JsonToFix(fname, sessionDataDictionary, appDataDictionary); - Environment.Exit(1); - } + JsonToFix(fname, sessionDataDictionary, appDataDictionary); + Environment.Exit(1); } } diff --git a/Examples/SimpleAcceptor/Program.cs b/Examples/SimpleAcceptor/Program.cs index 9117ed135..85640b858 100644 --- a/Examples/SimpleAcceptor/Program.cs +++ b/Examples/SimpleAcceptor/Program.cs @@ -1,59 +1,57 @@ using System; -using Microsoft.Extensions.Logging; using QuickFix; using QuickFix.Logger; using QuickFix.Store; -namespace SimpleAcceptor +namespace SimpleAcceptor; + +class Program { - class Program + [STAThread] + static void Main(string[] args) { - [STAThread] - static void Main(string[] args) - { - Console.WriteLine("============="); - Console.WriteLine("This is only an example program."); - Console.WriteLine("It's a simple server (e.g. Acceptor) app that will let clients (e.g. Initiators)"); - Console.WriteLine("connect to it. It will accept and display any application-level messages that it receives."); - Console.WriteLine("Connecting clients should set TargetCompID to 'SIMPLE' and SenderCompID to 'CLIENT1' or 'CLIENT2'."); - Console.WriteLine("Port is 5001."); - Console.WriteLine("(see simpleacc.cfg for configuration details)"); - Console.WriteLine("============="); - - if (args.Length != 1) - { - Console.WriteLine("usage: SimpleAcceptor CONFIG_FILENAME"); - System.Environment.Exit(2); - } + Console.WriteLine("============="); + Console.WriteLine("This is only an example program."); + Console.WriteLine("It's a simple server (e.g. Acceptor) app that will let clients (e.g. Initiators)"); + Console.WriteLine("connect to it. It will accept and display any application-level messages that it receives."); + Console.WriteLine("Connecting clients should set TargetCompID to 'SIMPLE' and SenderCompID to 'CLIENT1' or 'CLIENT2'."); + Console.WriteLine("Port is 5001."); + Console.WriteLine("(see simpleacc.cfg for configuration details)"); + Console.WriteLine("============="); - try - { - SessionSettings settings = new SessionSettings(args[0]); - IApplication app = new SimpleAcceptorApp(); - IMessageStoreFactory storeFactory = new FileStoreFactory(settings); + if (args.Length != 1) + { + Console.WriteLine("usage: SimpleAcceptor CONFIG_FILENAME"); + System.Environment.Exit(2); + } - ILogFactory logFactory = new ScreenLogFactory(settings); - ThreadedSocketAcceptor acceptor = new ThreadedSocketAcceptor(app, storeFactory, settings, logFactory); + try + { + SessionSettings settings = new SessionSettings(args[0]); + IApplication app = new SimpleAcceptorApp(); + IMessageStoreFactory storeFactory = new FileStoreFactory(settings); - /* - // v1.14: you can use Microsoft.Extensions.Logging instead - using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => - { - builder.AddConsole(); - }); - IAcceptor acceptor = new ThreadedSocketAcceptor(app, storeFactory, settings, loggerFactory); - */ + ILogFactory logFactory = new ScreenLogFactory(settings); + ThreadedSocketAcceptor acceptor = new ThreadedSocketAcceptor(app, storeFactory, settings, logFactory); - acceptor.Start(); - Console.WriteLine("press to quit"); - Console.Read(); - acceptor.Stop(); - } - catch (System.Exception e) + /* + // v1.14: you can use Microsoft.Extensions.Logging instead + using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => { - Console.WriteLine("==FATAL ERROR=="); - Console.WriteLine(e.ToString()); - } + builder.AddConsole(); + }); + IAcceptor acceptor = new ThreadedSocketAcceptor(app, storeFactory, settings, loggerFactory); + */ + + acceptor.Start(); + Console.WriteLine("press to quit"); + Console.Read(); + acceptor.Stop(); + } + catch (System.Exception e) + { + Console.WriteLine("==FATAL ERROR=="); + Console.WriteLine(e.ToString()); } } } diff --git a/Examples/SimpleAcceptor/SimpleAcceptorApp.cs b/Examples/SimpleAcceptor/SimpleAcceptorApp.cs index a5249d98b..250aa2eef 100644 --- a/Examples/SimpleAcceptor/SimpleAcceptorApp.cs +++ b/Examples/SimpleAcceptor/SimpleAcceptorApp.cs @@ -1,39 +1,38 @@ using System; using QuickFix; -namespace SimpleAcceptor -{ - /// - /// Just a simple server that will let you connect to it and ignore any - /// application-level messages you send to it. - /// Note that this app is *NOT* a message cracker. - /// +namespace SimpleAcceptor; - public class SimpleAcceptorApp : /*QuickFix.MessageCracker,*/ QuickFix.IApplication - { - public void FromApp(Message message, SessionID sessionID) - { - Console.WriteLine("IN: " + message); - //Crack(message, sessionID); - } +/// +/// Just a simple server that will let you connect to it and ignore any +/// application-level messages you send to it. +/// Note that this app is *NOT* a message cracker. +/// - public void ToApp(Message message, SessionID sessionID) - { - Console.WriteLine("OUT: " + message); - } +public class SimpleAcceptorApp : /*QuickFix.MessageCracker,*/ QuickFix.IApplication +{ + public void FromApp(Message message, SessionID sessionID) + { + Console.WriteLine("IN: " + message); + //Crack(message, sessionID); + } - public void FromAdmin(Message message, SessionID sessionID) - { - Console.WriteLine("IN: " + message); - } + public void ToApp(Message message, SessionID sessionID) + { + Console.WriteLine("OUT: " + message); + } - public void ToAdmin(Message message, SessionID sessionID) - { - Console.WriteLine("OUT: " + message); - } + public void FromAdmin(Message message, SessionID sessionID) + { + Console.WriteLine("IN: " + message); + } - public void OnCreate(SessionID sessionID) { } - public void OnLogout(SessionID sessionID) { } - public void OnLogon(SessionID sessionID) { } + public void ToAdmin(Message message, SessionID sessionID) + { + Console.WriteLine("OUT: " + message); } + + public void OnCreate(SessionID sessionID) { } + public void OnLogout(SessionID sessionID) { } + public void OnLogon(SessionID sessionID) { } } diff --git a/Examples/TradeClient/Program.cs b/Examples/TradeClient/Program.cs index 288b9aa08..f8cede7af 100644 --- a/Examples/TradeClient/Program.cs +++ b/Examples/TradeClient/Program.cs @@ -1,63 +1,61 @@ using System; -using Microsoft.Extensions.Logging; using QuickFix.Logger; using QuickFix.Store; -namespace TradeClient +namespace TradeClient; + +class Program { - class Program + [STAThread] + static void Main(string[] args) { - [STAThread] - static void Main(string[] args) + Console.WriteLine("============="); + Console.WriteLine("This is only an example program, meant to run against the Executor or SimpleAcceptor example programs."); + Console.WriteLine(); + Console.WriteLine(" ! ! !"); + Console.WriteLine(" DO NOT USE THIS ON A COMMERCIAL FIX INTERFACE! It won't work and it's a bad idea!"); + Console.WriteLine(" ! ! !"); + Console.WriteLine(); + Console.WriteLine("============="); + + if (args.Length != 1) { - Console.WriteLine("============="); - Console.WriteLine("This is only an example program, meant to run against the Executor or SimpleAcceptor example programs."); - Console.WriteLine(); - Console.WriteLine(" ! ! !"); - Console.WriteLine(" DO NOT USE THIS ON A COMMERCIAL FIX INTERFACE! It won't work and it's a bad idea!"); - Console.WriteLine(" ! ! !"); - Console.WriteLine(); - Console.WriteLine("============="); - - if (args.Length != 1) - { - System.Console.WriteLine("usage: TradeClient.exe CONFIG_FILENAME"); - System.Environment.Exit(2); - } + System.Console.WriteLine("usage: TradeClient.exe CONFIG_FILENAME"); + System.Environment.Exit(2); + } - string file = args[0]; + string file = args[0]; - try - { - QuickFix.SessionSettings settings = new QuickFix.SessionSettings(file); - TradeClientApp application = new TradeClientApp(); - IMessageStoreFactory storeFactory = new FileStoreFactory(settings); - - ILogFactory logFactory = new ScreenLogFactory(settings); - QuickFix.Transport.SocketInitiator initiator = new QuickFix.Transport.SocketInitiator(application, storeFactory, settings, logFactory); - - /* - // v1.14: you can use Microsoft.Extensions.Logging instead - using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => - { - builder.AddConsole(); - }); - QuickFix.Transport.SocketInitiator initiator = new QuickFix.Transport.SocketInitiator(application, storeFactory, settings, loggerFactory); - */ - - // this is a developer-test kludge. do not emulate. - application.MyInitiator = initiator; - - initiator.Start(); - application.Run(); - initiator.Stop(); - } - catch (Exception e) + try + { + QuickFix.SessionSettings settings = new QuickFix.SessionSettings(file); + TradeClientApp application = new TradeClientApp(); + IMessageStoreFactory storeFactory = new FileStoreFactory(settings); + + ILogFactory logFactory = new ScreenLogFactory(settings); + QuickFix.Transport.SocketInitiator initiator = new QuickFix.Transport.SocketInitiator(application, storeFactory, settings, logFactory); + + /* + // v1.14: you can use Microsoft.Extensions.Logging instead + using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => { - Console.WriteLine(e.Message); - Console.WriteLine(e.StackTrace); - } - Environment.Exit(1); + builder.AddConsole(); + }); + QuickFix.Transport.SocketInitiator initiator = new QuickFix.Transport.SocketInitiator(application, storeFactory, settings, loggerFactory); + */ + + // this is a developer-test kludge. do not emulate. + application.MyInitiator = initiator; + + initiator.Start(); + application.Run(); + initiator.Stop(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + Console.WriteLine(e.StackTrace); } + Environment.Exit(1); } } diff --git a/Examples/TradeClient/TradeClientApp.cs b/Examples/TradeClient/TradeClientApp.cs index 5a41fff27..b8fecc7b1 100644 --- a/Examples/TradeClient/TradeClientApp.cs +++ b/Examples/TradeClient/TradeClientApp.cs @@ -5,412 +5,411 @@ using ApplicationException = System.ApplicationException; using Exception = System.Exception; -namespace TradeClient +namespace TradeClient; + +public class TradeClientApp : QuickFix.MessageCracker, QuickFix.IApplication { - public class TradeClientApp : QuickFix.MessageCracker, QuickFix.IApplication - { - private Session? _session = null; + private Session? _session = null; - // This variable is a kludge for developer test purposes. Don't do this on a production application. - public IInitiator? MyInitiator = null; + // This variable is a kludge for developer test purposes. Don't do this on a production application. + public IInitiator? MyInitiator = null; - #region IApplication interface overrides + #region IApplication interface overrides - public void OnCreate(SessionID sessionId) - { - _session = Session.LookupSession(sessionId); - if (_session is null) - throw new ApplicationException("Somehow session is not found"); - } + public void OnCreate(SessionID sessionId) + { + _session = Session.LookupSession(sessionId); + if (_session is null) + throw new ApplicationException("Somehow session is not found"); + } - public void OnLogon(SessionID sessionId) { Console.WriteLine("Logon - " + sessionId); } - public void OnLogout(SessionID sessionId) { Console.WriteLine("Logout - " + sessionId); } + public void OnLogon(SessionID sessionId) { Console.WriteLine("Logon - " + sessionId); } + public void OnLogout(SessionID sessionId) { Console.WriteLine("Logout - " + sessionId); } - public void FromAdmin(Message message, SessionID sessionId) { } - public void ToAdmin(Message message, SessionID sessionId) { } + public void FromAdmin(Message message, SessionID sessionId) { } + public void ToAdmin(Message message, SessionID sessionId) { } - public void FromApp(Message message, SessionID sessionId) + public void FromApp(Message message, SessionID sessionId) + { + Console.WriteLine("IN: " + message.ConstructString()); + try { - Console.WriteLine("IN: " + message.ConstructString()); - try - { - Crack(message, sessionId); - } - catch (Exception ex) - { - Console.WriteLine("==Cracker exception=="); - Console.WriteLine(ex.ToString()); - Console.WriteLine(ex.StackTrace); - } + Crack(message, sessionId); } + catch (Exception ex) + { + Console.WriteLine("==Cracker exception=="); + Console.WriteLine(ex.ToString()); + Console.WriteLine(ex.StackTrace); + } + } - public void ToApp(Message message, SessionID sessionId) + public void ToApp(Message message, SessionID sessionId) + { + try { - try + bool possDupFlag = false; + if (message.Header.IsSetField(Tags.PossDupFlag)) { - bool possDupFlag = false; - if (message.Header.IsSetField(Tags.PossDupFlag)) - { - possDupFlag = message.Header.GetBoolean(Tags.PossDupFlag); - } - if (possDupFlag) - throw new DoNotSend(); + possDupFlag = message.Header.GetBoolean(Tags.PossDupFlag); } - catch (FieldNotFoundException) - { } - - Console.WriteLine(); - Console.WriteLine("OUT: " + message.ConstructString()); + if (possDupFlag) + throw new DoNotSend(); } - #endregion + catch (FieldNotFoundException) + { } + Console.WriteLine(); + Console.WriteLine("OUT: " + message.ConstructString()); + } + #endregion - #region MessageCracker handlers - public void OnMessage(QuickFix.FIX44.ExecutionReport m, SessionID s) - { - Console.WriteLine("Received execution report"); - } - public void OnMessage(QuickFix.FIX44.OrderCancelReject m, SessionID s) - { - Console.WriteLine("Received order cancel reject"); - } - #endregion + #region MessageCracker handlers + public void OnMessage(QuickFix.FIX44.ExecutionReport m, SessionID s) + { + Console.WriteLine("Received execution report"); + } + public void OnMessage(QuickFix.FIX44.OrderCancelReject m, SessionID s) + { + Console.WriteLine("Received order cancel reject"); + } + #endregion - public void Run() - { - if (this.MyInitiator is null) - throw new ApplicationException("Somehow this.MyInitiator is not set"); - while (true) + public void Run() + { + if (this.MyInitiator is null) + throw new ApplicationException("Somehow this.MyInitiator is not set"); + + while (true) + { + try { - try + char action = QueryAction(); + if (action == '1') + QueryEnterOrder(); + else if (action == '2') + QueryCancelOrder(); + else if (action == '3') + QueryReplaceOrder(); + else if (action == '4') + QueryMarketDataRequest(); + else if (action == 'g') { - char action = QueryAction(); - if (action == '1') - QueryEnterOrder(); - else if (action == '2') - QueryCancelOrder(); - else if (action == '3') - QueryReplaceOrder(); - else if (action == '4') - QueryMarketDataRequest(); - else if (action == 'g') - { - if (this.MyInitiator.IsStopped) - { - Console.WriteLine("Restarting initiator..."); - this.MyInitiator.Start(); - } - else - Console.WriteLine("Already started."); - } - else if (action == 'x') + if (this.MyInitiator.IsStopped) { - if (this.MyInitiator.IsStopped) - Console.WriteLine("Already stopped."); - else - { - Console.WriteLine("Stopping initiator..."); - this.MyInitiator.Stop(); - } + Console.WriteLine("Restarting initiator..."); + this.MyInitiator.Start(); } - else if (action == 'q' || action == 'Q') - break; + else + Console.WriteLine("Already started."); } - catch (Exception e) + else if (action == 'x') { - Console.WriteLine("Message Not Sent: " + e.Message); - Console.WriteLine("StackTrace: " + e.StackTrace); + if (this.MyInitiator.IsStopped) + Console.WriteLine("Already stopped."); + else + { + Console.WriteLine("Stopping initiator..."); + this.MyInitiator.Stop(); + } } + else if (action == 'q' || action == 'Q') + break; } - Console.WriteLine("Program shutdown."); - } - - private void SendMessage(Message m) - { - if (_session is not null) - _session.Send(m); - else + catch (Exception e) { - // This probably won't ever happen. - Console.WriteLine("Can't send message: session not created."); + Console.WriteLine("Message Not Sent: " + e.Message); + Console.WriteLine("StackTrace: " + e.StackTrace); } } + Console.WriteLine("Program shutdown."); + } - private static string ReadCommand() { - string? inp = Console.ReadLine(); - if (inp is null) - throw new ApplicationException("Input no longer available"); - return inp.Trim(); - } - - private char QueryAction() + private void SendMessage(Message m) + { + if (_session is not null) + _session.Send(m); + else { - // Commands 'g' and 'x' are intentionally hidden. - Console.Write("\n" - + "1) Enter Order\n" - + "2) Cancel Order\n" - + "3) Replace Order\n" - + "4) Market data test\n" - + "Q) Quit\n" - + "Action: " - ); - - HashSet validActions = new HashSet("1,2,3,4,q,Q,g,x".Split(',')); - - string cmd = ReadCommand(); - if (cmd.Length != 1 || validActions.Contains(cmd) == false) - throw new System.Exception("Invalid action"); - - return cmd.ToCharArray()[0]; + // This probably won't ever happen. + Console.WriteLine("Can't send message: session not created."); } + } - private void QueryEnterOrder() - { - Console.WriteLine("\nNewOrderSingle"); + private static string ReadCommand() { + string? inp = Console.ReadLine(); + if (inp is null) + throw new ApplicationException("Input no longer available"); + return inp.Trim(); + } - QuickFix.FIX44.NewOrderSingle m = QueryNewOrderSingle44(); + private char QueryAction() + { + // Commands 'g' and 'x' are intentionally hidden. + Console.Write("\n" + + "1) Enter Order\n" + + "2) Cancel Order\n" + + "3) Replace Order\n" + + "4) Market data test\n" + + "Q) Quit\n" + + "Action: " + ); + + HashSet validActions = new HashSet("1,2,3,4,q,Q,g,x".Split(',')); + + string cmd = ReadCommand(); + if (cmd.Length != 1 || validActions.Contains(cmd) == false) + throw new System.Exception("Invalid action"); + + return cmd.ToCharArray()[0]; + } - if (m is not null && QueryConfirm("Send order")) - { - m.Header.GetString(Tags.BeginString); + private void QueryEnterOrder() + { + Console.WriteLine("\nNewOrderSingle"); - SendMessage(m); - } - } + QuickFix.FIX44.NewOrderSingle m = QueryNewOrderSingle44(); - private void QueryCancelOrder() + if (m is not null && QueryConfirm("Send order")) { - Console.WriteLine("\nOrderCancelRequest"); - - QuickFix.FIX44.OrderCancelRequest m = QueryOrderCancelRequest44(); + m.Header.GetString(Tags.BeginString); - if (m != null && QueryConfirm("Cancel order")) - SendMessage(m); + SendMessage(m); } + } - private void QueryReplaceOrder() - { - Console.WriteLine("\nCancelReplaceRequest"); + private void QueryCancelOrder() + { + Console.WriteLine("\nOrderCancelRequest"); - QuickFix.FIX44.OrderCancelReplaceRequest m = QueryCancelReplaceRequest44(); + QuickFix.FIX44.OrderCancelRequest m = QueryOrderCancelRequest44(); - if (m != null && QueryConfirm("Send replace")) - SendMessage(m); - } + if (m != null && QueryConfirm("Cancel order")) + SendMessage(m); + } - private void QueryMarketDataRequest() - { - Console.WriteLine("\nMarketDataRequest"); + private void QueryReplaceOrder() + { + Console.WriteLine("\nCancelReplaceRequest"); - QuickFix.FIX44.MarketDataRequest m = QueryMarketDataRequest44(); + QuickFix.FIX44.OrderCancelReplaceRequest m = QueryCancelReplaceRequest44(); - if (QueryConfirm("Send market data request")) - SendMessage(m); - } + if (m != null && QueryConfirm("Send replace")) + SendMessage(m); + } - private bool QueryConfirm(string query) - { - Console.WriteLine(); - Console.WriteLine(query + "?: "); - string line = ReadCommand(); - return (line[0].Equals('y') || line[0].Equals('Y')); - } + private void QueryMarketDataRequest() + { + Console.WriteLine("\nMarketDataRequest"); - #region Message creation functions - private QuickFix.FIX44.NewOrderSingle QueryNewOrderSingle44() - { - OrdType ordType = QueryOrdType(); - - QuickFix.FIX44.NewOrderSingle newOrderSingle = new QuickFix.FIX44.NewOrderSingle( - QueryClOrdId(), - QuerySymbol(), - QuerySide(), - new TransactTime(DateTime.Now), - ordType); - - newOrderSingle.Set(new HandlInst('1')); - newOrderSingle.Set(QueryOrderQty()); - newOrderSingle.Set(QueryTimeInForce()); - if (ordType.Value == OrdType.LIMIT || ordType.Value == OrdType.STOP_LIMIT) - newOrderSingle.Set(QueryPrice()); - if (ordType.Value == OrdType.STOP || ordType.Value == OrdType.STOP_LIMIT) - newOrderSingle.Set(QueryStopPx()); - - return newOrderSingle; - } + QuickFix.FIX44.MarketDataRequest m = QueryMarketDataRequest44(); - private QuickFix.FIX44.OrderCancelRequest QueryOrderCancelRequest44() - { - QuickFix.FIX44.OrderCancelRequest orderCancelRequest = new QuickFix.FIX44.OrderCancelRequest( - QueryOrigClOrdId(), - QueryClOrdId(), - QuerySymbol(), - QuerySide(), - new TransactTime(DateTime.Now)); - - orderCancelRequest.Set(QueryOrderQty()); - return orderCancelRequest; - } + if (QueryConfirm("Send market data request")) + SendMessage(m); + } - private QuickFix.FIX44.OrderCancelReplaceRequest QueryCancelReplaceRequest44() - { - QuickFix.FIX44.OrderCancelReplaceRequest ocrr = new QuickFix.FIX44.OrderCancelReplaceRequest( - QueryOrigClOrdId(), - QueryClOrdId(), - QuerySymbol(), - QuerySide(), - new TransactTime(DateTime.Now), - QueryOrdType()); - - ocrr.Set(new HandlInst('1')); - if (QueryConfirm("New price")) - ocrr.Set(QueryPrice()); - if (QueryConfirm("New quantity")) - ocrr.Set(QueryOrderQty()); - - return ocrr; - } + private bool QueryConfirm(string query) + { + Console.WriteLine(); + Console.WriteLine(query + "?: "); + string line = ReadCommand(); + return (line[0].Equals('y') || line[0].Equals('Y')); + } - private QuickFix.FIX44.MarketDataRequest QueryMarketDataRequest44() - { - MDReqID mdReqID = new MDReqID("MARKETDATAID"); - SubscriptionRequestType subType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT); - MarketDepth marketDepth = new MarketDepth(0); + #region Message creation functions + private QuickFix.FIX44.NewOrderSingle QueryNewOrderSingle44() + { + OrdType ordType = QueryOrdType(); + + QuickFix.FIX44.NewOrderSingle newOrderSingle = new QuickFix.FIX44.NewOrderSingle( + QueryClOrdId(), + QuerySymbol(), + QuerySide(), + new TransactTime(DateTime.Now), + ordType); + + newOrderSingle.Set(new HandlInst('1')); + newOrderSingle.Set(QueryOrderQty()); + newOrderSingle.Set(QueryTimeInForce()); + if (ordType.Value == OrdType.LIMIT || ordType.Value == OrdType.STOP_LIMIT) + newOrderSingle.Set(QueryPrice()); + if (ordType.Value == OrdType.STOP || ordType.Value == OrdType.STOP_LIMIT) + newOrderSingle.Set(QueryStopPx()); + + return newOrderSingle; + } - QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup marketDataEntryGroup = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); - marketDataEntryGroup.Set(new MDEntryType(MDEntryType.BID)); + private QuickFix.FIX44.OrderCancelRequest QueryOrderCancelRequest44() + { + QuickFix.FIX44.OrderCancelRequest orderCancelRequest = new QuickFix.FIX44.OrderCancelRequest( + QueryOrigClOrdId(), + QueryClOrdId(), + QuerySymbol(), + QuerySide(), + new TransactTime(DateTime.Now)); + + orderCancelRequest.Set(QueryOrderQty()); + return orderCancelRequest; + } - QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symbolGroup = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup(); - symbolGroup.Set(new Symbol("LNUX")); + private QuickFix.FIX44.OrderCancelReplaceRequest QueryCancelReplaceRequest44() + { + QuickFix.FIX44.OrderCancelReplaceRequest ocrr = new QuickFix.FIX44.OrderCancelReplaceRequest( + QueryOrigClOrdId(), + QueryClOrdId(), + QuerySymbol(), + QuerySide(), + new TransactTime(DateTime.Now), + QueryOrdType()); + + ocrr.Set(new HandlInst('1')); + if (QueryConfirm("New price")) + ocrr.Set(QueryPrice()); + if (QueryConfirm("New quantity")) + ocrr.Set(QueryOrderQty()); + + return ocrr; + } - QuickFix.FIX44.MarketDataRequest message = new QuickFix.FIX44.MarketDataRequest(mdReqID, subType, marketDepth); - message.AddGroup(marketDataEntryGroup); - message.AddGroup(symbolGroup); + private QuickFix.FIX44.MarketDataRequest QueryMarketDataRequest44() + { + MDReqID mdReqID = new MDReqID("MARKETDATAID"); + SubscriptionRequestType subType = new SubscriptionRequestType(SubscriptionRequestType.SNAPSHOT); + MarketDepth marketDepth = new MarketDepth(0); - return message; - } - #endregion + QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup marketDataEntryGroup = new QuickFix.FIX44.MarketDataRequest.NoMDEntryTypesGroup(); + marketDataEntryGroup.Set(new MDEntryType(MDEntryType.BID)); - #region field query private methods - private ClOrdID QueryClOrdId() - { - Console.WriteLine(); - Console.Write("ClOrdID? "); - return new ClOrdID(ReadCommand()); - } + QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup symbolGroup = new QuickFix.FIX44.MarketDataRequest.NoRelatedSymGroup(); + symbolGroup.Set(new Symbol("LNUX")); - private OrigClOrdID QueryOrigClOrdId() - { - Console.WriteLine(); - Console.Write("OrigClOrdID? "); - return new OrigClOrdID(ReadCommand()); - } + QuickFix.FIX44.MarketDataRequest message = new QuickFix.FIX44.MarketDataRequest(mdReqID, subType, marketDepth); + message.AddGroup(marketDataEntryGroup); + message.AddGroup(symbolGroup); - private Symbol QuerySymbol() - { - Console.WriteLine(); - Console.Write("Symbol? "); - return new Symbol(ReadCommand()); - } + return message; + } + #endregion - private Side QuerySide() - { - Console.WriteLine(); - Console.WriteLine("1) Buy"); - Console.WriteLine("2) Sell"); - Console.WriteLine("3) Sell Short"); - Console.WriteLine("4) Sell Short Exempt"); - Console.WriteLine("5) Cross"); - Console.WriteLine("6) Cross Short"); - Console.WriteLine("7) Cross Short Exempt"); - Console.Write("Side? "); - string s = ReadCommand(); - - char c = ' '; - switch (s) - { - case "1": c = Side.BUY; break; - case "2": c = Side.SELL; break; - case "3": c = Side.SELL_SHORT; break; - case "4": c = Side.SELL_SHORT_EXEMPT; break; - case "5": c = Side.CROSS; break; - case "6": c = Side.CROSS_SHORT; break; - case "7": c = 'A'; break; - default: throw new Exception("unsupported input"); - } - return new Side(c); - } + #region field query private methods + private ClOrdID QueryClOrdId() + { + Console.WriteLine(); + Console.Write("ClOrdID? "); + return new ClOrdID(ReadCommand()); + } - private OrdType QueryOrdType() - { - Console.WriteLine(); - Console.WriteLine("1) Market"); - Console.WriteLine("2) Limit"); - Console.WriteLine("3) Stop"); - Console.WriteLine("4) Stop Limit"); - Console.Write("OrdType? "); - string s = ReadCommand(); - - char c = ' '; - switch (s) - { - case "1": c = OrdType.MARKET; break; - case "2": c = OrdType.LIMIT; break; - case "3": c = OrdType.STOP; break; - case "4": c = OrdType.STOP_LIMIT; break; - default: throw new Exception("unsupported input"); - } - return new OrdType(c); - } + private OrigClOrdID QueryOrigClOrdId() + { + Console.WriteLine(); + Console.Write("OrigClOrdID? "); + return new OrigClOrdID(ReadCommand()); + } - private OrderQty QueryOrderQty() - { - Console.WriteLine(); - Console.Write("OrderQty? "); - return new OrderQty(Convert.ToDecimal(ReadCommand())); - } + private Symbol QuerySymbol() + { + Console.WriteLine(); + Console.Write("Symbol? "); + return new Symbol(ReadCommand()); + } - private TimeInForce QueryTimeInForce() + private Side QuerySide() + { + Console.WriteLine(); + Console.WriteLine("1) Buy"); + Console.WriteLine("2) Sell"); + Console.WriteLine("3) Sell Short"); + Console.WriteLine("4) Sell Short Exempt"); + Console.WriteLine("5) Cross"); + Console.WriteLine("6) Cross Short"); + Console.WriteLine("7) Cross Short Exempt"); + Console.Write("Side? "); + string s = ReadCommand(); + + char c = ' '; + switch (s) { - Console.WriteLine(); - Console.WriteLine("1) Day"); - Console.WriteLine("2) IOC"); - Console.WriteLine("3) OPG"); - Console.WriteLine("4) GTC"); - Console.WriteLine("5) GTX"); - Console.Write("TimeInForce? "); - string s = ReadCommand(); - - char c = ' '; - switch (s) - { - case "1": c = TimeInForce.DAY; break; - case "2": c = TimeInForce.IMMEDIATE_OR_CANCEL; break; - case "3": c = TimeInForce.AT_THE_OPENING; break; - case "4": c = TimeInForce.GOOD_TILL_CANCEL; break; - case "5": c = TimeInForce.GOOD_TILL_CROSSING; break; - default: throw new Exception("unsupported input"); - } - return new TimeInForce(c); + case "1": c = Side.BUY; break; + case "2": c = Side.SELL; break; + case "3": c = Side.SELL_SHORT; break; + case "4": c = Side.SELL_SHORT_EXEMPT; break; + case "5": c = Side.CROSS; break; + case "6": c = Side.CROSS_SHORT; break; + case "7": c = 'A'; break; + default: throw new Exception("unsupported input"); } + return new Side(c); + } - private Price QueryPrice() + private OrdType QueryOrdType() + { + Console.WriteLine(); + Console.WriteLine("1) Market"); + Console.WriteLine("2) Limit"); + Console.WriteLine("3) Stop"); + Console.WriteLine("4) Stop Limit"); + Console.Write("OrdType? "); + string s = ReadCommand(); + + char c = ' '; + switch (s) { - Console.WriteLine(); - Console.Write("Price? "); - return new Price(Convert.ToDecimal(ReadCommand())); + case "1": c = OrdType.MARKET; break; + case "2": c = OrdType.LIMIT; break; + case "3": c = OrdType.STOP; break; + case "4": c = OrdType.STOP_LIMIT; break; + default: throw new Exception("unsupported input"); } + return new OrdType(c); + } + + private OrderQty QueryOrderQty() + { + Console.WriteLine(); + Console.Write("OrderQty? "); + return new OrderQty(Convert.ToDecimal(ReadCommand())); + } - private StopPx QueryStopPx() + private TimeInForce QueryTimeInForce() + { + Console.WriteLine(); + Console.WriteLine("1) Day"); + Console.WriteLine("2) IOC"); + Console.WriteLine("3) OPG"); + Console.WriteLine("4) GTC"); + Console.WriteLine("5) GTX"); + Console.Write("TimeInForce? "); + string s = ReadCommand(); + + char c = ' '; + switch (s) { - Console.WriteLine(); - Console.Write("StopPx? "); - return new StopPx(Convert.ToDecimal(ReadCommand())); + case "1": c = TimeInForce.DAY; break; + case "2": c = TimeInForce.IMMEDIATE_OR_CANCEL; break; + case "3": c = TimeInForce.AT_THE_OPENING; break; + case "4": c = TimeInForce.GOOD_TILL_CANCEL; break; + case "5": c = TimeInForce.GOOD_TILL_CROSSING; break; + default: throw new Exception("unsupported input"); } + return new TimeInForce(c); + } - #endregion + private Price QueryPrice() + { + Console.WriteLine(); + Console.Write("Price? "); + return new Price(Convert.ToDecimal(ReadCommand())); } + + private StopPx QueryStopPx() + { + Console.WriteLine(); + Console.Write("StopPx? "); + return new StopPx(Convert.ToDecimal(ReadCommand())); + } + + #endregion }