Beispiel #1
0
        public Session(Connection connection, SessionProtocol protocol, TemplateRegistry inboundRegistry, TemplateRegistry outboundRegistry)
        {
            var inContext = new Context();

            inContext.TemplateRegistry.RegisterAll(inboundRegistry);
            var outContext = new Context();

            outContext.TemplateRegistry.RegisterAll(outboundRegistry);
            inContext.ErrorHandler = this;

            this.connection = connection;
            this.protocol   = protocol;
            try
            {
                in_stream  = new MessageInputStream(connection.InputStream.BaseStream, inContext);
                out_stream = new MessageOutputStream(connection.OutputStream.BaseStream, outContext);
            }
            catch (System.IO.IOException e)
            {
                errorHandler.Error(null, "Error occurred in connection.", e);
                throw new IllegalStateException(e);
            }

            protocol.ConfigureSession(this);
        }
Beispiel #2
0
        public Session(IConnection connection, ISessionProtocol protocol, ITemplateRegistry inboundRegistry,
                       ITemplateRegistry outboundRegistry)
        {
            var inContext = new Context();

            inContext.TemplateRegistry.RegisterAll(inboundRegistry);
            var outContext = new Context();

            outContext.TemplateRegistry.RegisterAll(outboundRegistry);
            inContext.ErrorHandler = this;

            _connection = connection;
            _protocol   = protocol;
            try
            {
                _inStream  = new MessageInputStream(connection.InputStream.BaseStream, inContext);
                _outStream = new MessageOutputStream(connection.OutputStream.BaseStream, outContext);
            }
            catch (IOException e)
            {
                _errorHandler.OnError(e, DynError.Undefined, "Error occurred in connection.");
                throw new IllegalStateException(e);
            }

            protocol.ConfigureSession(this);
        }
 public void TestReadMessage()
 {
     var input = new MessageInputStream(BitStream("11000000 10000100"));
     try
     {
         input.ReadMessage();
         Assert.Fail();
     }
     catch (DynErrorException e)
     {
         Assert.AreEqual(DynError.TemplateNotRegistered, e.Error);
     }
 }
Beispiel #4
0
        public void TestMultipleMessages()
        {
            var outStream = new MemoryStream();
            var output    = new MessageOutputStream(outStream);

            output.RegisterTemplate(ObjectMother.AllocInstrctnTemplateId,
                                    ObjectMother.AllocationInstruction);

            var allocations = new SequenceValue(ObjectMother.AllocationInstruction
                                                .GetSequence("Allocations"));

            allocations.Add(ObjectMother.NewAllocation("fortyFiveFund", 22.5, 75.0));
            allocations.Add(ObjectMother.NewAllocation("fortyFund", 24.6, 25.0));

            Message ai1 = ObjectMother.NewAllocInstrctn(
                "ltg0001", 1, 100.0, 23.4, ObjectMother.NewInstrument("CTYA", "200910"), allocations);

            allocations = new SequenceValue(
                ObjectMother.AllocationInstruction.GetSequence("Allocations"));

            allocations.Add(ObjectMother.NewAllocation("fortyFiveFund", 22.5, 75.0));
            allocations.Add(ObjectMother.NewAllocation("fortyFund", 24.6, 25.0));

            Message ai2 = ObjectMother.NewAllocInstrctn(
                "ltg0001", 1, 100.0, 23.4, ObjectMother.NewInstrument("CTYA", "200910"), allocations);

            allocations = new SequenceValue(
                ObjectMother.AllocationInstruction.GetSequence("Allocations"));
            allocations.Add(ObjectMother.NewAllocation("fortyFiveFund", 22.5, 75.0));
            allocations.Add(ObjectMother.NewAllocation("fortyFund", 24.6, 25.0));

            Message ai3 = ObjectMother.NewAllocInstrctn(
                "ltg0001", 1, 100.0, 23.4, ObjectMother.NewInstrument("CTYA", "200910"), allocations);

            output.WriteMessage(ai1);
            output.WriteMessage(ai2);
            output.WriteMessage(ai3);

            byte[] bytes = outStream.ToArray();
            var    input = new MessageInputStream(new MemoryStream(bytes));

            input.RegisterTemplate(ObjectMother.AllocInstrctnTemplateId,
                                   ObjectMother.AllocationInstruction);

            Message message = input.ReadMessage();

            Assert.AreEqual(ai1, message);
            message = input.ReadMessage();
            Assert.AreEqual(ai2, message);
            Assert.AreEqual(ai3, input.ReadMessage());
        }
Beispiel #5
0
        public void TestReadMessage()
        {
            var input = new MessageInputStream(BitStream("11000000 10000100"));

            try
            {
                input.ReadMessage();
                Assert.Fail();
            }
            catch (DynErrorException e)
            {
                Assert.AreEqual(DynError.TemplateNotRegistered, e.Error);
            }
        }
        public void TestReadMessage()
        {
            var input = new MessageInputStream(BitStream("11000000 10000100"));

            try
            {
                input.ReadMessage();
                Assert.Fail();
            }
            catch (FastException e)
            {
                Assert.AreEqual(FastConstants.D9_TEMPLATE_NOT_REGISTERED, e.Code);
            }
        }
        public void TestDeltas()
        {
            var templateLoader = new XmlMessageTemplateLoader { LoadTemplateIdFromAuxId = true };

            using (var stream = File.OpenRead("CME/templates.xml"))
            {
                templateLoader.Load(stream);
            }

            using (var stream = File.OpenRead("CME/messages.fast"))
            {
                var mis = new MessageInputStream(stream, templateLoader.TemplateRegistry);
                Message md = mis.ReadMessage();
                Assert.AreEqual(-5025.0, md.GetSequence("MDEntries")[0].GetDouble("NetChgPrevDay"), .1);
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            string myString = string.Empty;

            byte[] data = new byte[] {
                215, 255, 148, 50, 48, 49, 56, 48, 50, 49, 50, 45, 48, 54, 58, 51, 56, 58, 51, 55, 46, 54, 53, 185, 177, 49, 27, 154, 128, 128, 128, 129, 95, 127, 127, 192, 128, 243, 83, 89, 66, 69, 65, 78, 73, 68, 82, 50, 48, 70, 69, 66, 50, 48, 49, 184, 50, 56, 53, 54, 183, 248, 11, 25, 38, 62, 14, 253, 128, 128, 128, 128, 128, 128, 128, 2, 29, 156, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128
            };



            string s = Encoding.ASCII.GetString(data);


            //TemplateTest objTempTest = new TemplateTest();
            //objTempTest.SetUp();
            //objTempTest.TestTemplates();


            //EncodeDecodeTest objEncodeDecodeTest = new EncodeDecodeTest();
            //objEncodeDecodeTest.TestComplexMessage();


            MessageTemplate[] objMessageTemplate = null;
            _loader = new XmlMessageTemplateLoader();

            using (FileStream stream = File.OpenRead("NCEDX.xml"))
                objMessageTemplate = _loader.Load(stream);


            var outStream = new MemoryStream();

            MessageTemplate template = _loader.TemplateRegistry[new QName("IncRefreshMDEntries")];



            var input = new MessageInputStream(new MemoryStream(data));

            input.RegisterTemplate(7, template);

            Message message = input.ReadMessage();



            Console.WriteLine(myString);
            Console.ReadLine();
        }
Beispiel #9
0
        public void TestDeltas()
        {
            var templateLoader = new XmlMessageTemplateLoader {
                LoadTemplateIdFromAuxId = true
            };

            using (var stream = File.OpenRead("CME/templates.xml"))
            {
                templateLoader.Load(stream);
            }

            using (var stream = File.OpenRead("CME/messages.fast"))
            {
                var     mis = new MessageInputStream(stream, templateLoader.TemplateRegistry);
                Message md  = mis.ReadMessage();
                Assert.AreEqual(-5025.0, md.GetSequence("MDEntries")[0].GetDouble("NetChgPrevDay"), .1);
            }
        }
Beispiel #10
0
        public void TestDeltas()
        {
            var templateSource = new StreamReader("CME/templates.xml");
            var templateLoader = new XMLMessageTemplateLoader {
                LoadTemplateIdFromAuxId = true
            };

            templateLoader.Load(templateSource.BaseStream);



            var is1 = new StreamReader("CME/messages.fast");
            var mis = new MessageInputStream(is1.BaseStream);

            mis.SetTemplateRegistry(templateLoader.TemplateRegistry);
            Message md = mis.ReadMessage();

            Assert.AreEqual(-5025.0, md.GetSequence("MDEntries")[0].GetDouble("NetChgPrevDay"), .1);
        }
Beispiel #11
0
        public void TestDeltas()
        {
            var templateLoader = new XmlMessageTemplateLoader {
                LoadTemplateIdFromAuxId = true
            };

            if (!Directory.Exists("Files") && Directory.Exists("../../../../Files"))
            {
                Utility.Util.DirectoryCopy("../../../../Files", "Files", true);
            }

            using (var stream = File.OpenRead("Files/CME/templates.xml"))
            {
                templateLoader.Load(stream);
            }

            using (var stream = File.OpenRead("Files/CME/messages.fast"))
            {
                var     mis = new MessageInputStream(stream, templateLoader.TemplateRegistry);
                Message md  = mis.ReadMessage();
                Assert.AreEqual(-5025.0, md.GetSequence("MDEntries")[0].GetDouble("NetChgPrevDay"), .1);
            }
        }
Beispiel #12
0
        public Session(Connection connection, SessionProtocol protocol, TemplateRegistry inboundRegistry, TemplateRegistry outboundRegistry)
        {
            var inContext = new Context();
            inContext.TemplateRegistry.RegisterAll(inboundRegistry);
            var outContext = new Context();
            outContext.TemplateRegistry.RegisterAll(outboundRegistry);
            inContext.ErrorHandler = this;

            this.connection = connection;
            this.protocol = protocol;
            try
            {
                in_stream = new MessageInputStream(connection.InputStream.BaseStream, inContext);
                out_stream = new MessageOutputStream(connection.OutputStream.BaseStream, outContext);
            }
            catch (System.IO.IOException e)
            {
                errorHandler.Error(null, "Error occurred in connection.", e);
                throw new IllegalStateException(e);
            }

            protocol.ConfigureSession(this);
        }
Beispiel #13
0
        public Session(IConnection connection, ISessionProtocol protocol, ITemplateRegistry inboundRegistry,
                       ITemplateRegistry outboundRegistry)
        {
            var inContext = new Context();
            inContext.TemplateRegistry.RegisterAll(inboundRegistry);
            var outContext = new Context();
            outContext.TemplateRegistry.RegisterAll(outboundRegistry);
            inContext.ErrorHandler = this;

            _connection = connection;
            _protocol = protocol;
            try
            {
                _inStream = new MessageInputStream(connection.InputStream.BaseStream, inContext);
                _outStream = new MessageOutputStream(connection.OutputStream.BaseStream, outContext);
            }
            catch (IOException e)
            {
                _errorHandler.OnError(e, DynError.Undefined, "Error occurred in connection.");
                throw new IllegalStateException(e);
            }

            protocol.ConfigureSession(this);
        }
Beispiel #14
0
        public void RunAllTests()
        {
            Console.WriteLine("Initializing...");

            // throw args.Exception;
            ValidationEventHandler errorHandler =
                (sender, args) => Console.WriteLine("Error {0}\n{1}", args.Message, args.Exception);

            Type   thisType = MethodBase.GetCurrentMethod().DeclaringType;
            Stream schema   = thisType.Assembly.GetManifestResourceStream(thisType, "TestSchema.xsd");

            Assert.IsNotNull(schema, "Unable to load XSD from the resources");

            var settings = new XmlReaderSettings();

            settings.Schemas.Add(XmlSchema.Read(schema, errorHandler));

            //
            // BUG!  TODO! change to schema-validated input
            //
            settings.ValidationType          = ValidationType.None; // ValidationType.Schema;
            settings.ValidationEventHandler += errorHandler;

            foreach (string xmlFile in Directory.GetFiles(XmlTestFilesDir, "*.xml"))
            {
                Console.WriteLine("Processing {0}...", xmlFile);

                XmlReader reader = XmlReader.Create(xmlFile, settings);
                try
                {
                    var xml = new XmlDocument();
                    xml.Load(reader);

                    foreach (XmlElement test in xml.GetElementsByTagName("test"))
                    {
                        XmlElement desc = test.GetElement("desc");

                        string actionStr = test.GetAttribute("action");
                        if (string.IsNullOrEmpty(actionStr))
                        {
                            actionStr = "all";
                        }
                        var action = (Actions)Enum.Parse(typeof(Actions), actionStr, true);

                        Console.WriteLine("  Test {0}{1}{2}", test.GetAttribute("name"),
                                          desc == null || string.IsNullOrEmpty(desc.Value) ? "" : " - " + desc.Value,
                                          action == Actions.All ? "" : " (" + action + " only)");

                        var tmpl = new XmlMessageTemplateLoader();

                        XmlElement templFile = test.GetElement("templatesfile");
                        tmpl.LoadTemplateIdFromAuxId = true;
                        if (templFile != null)
                        {
                            using (FileStream stream = File.OpenRead(templFile.GetAttribute("path")))
                                tmpl.Load(stream);
                        }
                        else
                        {
                            XmlElement templXml = test.GetElement("templates", FastConstants.TemplateDefinition11);
                            if (templXml == null)
                            {
                                throw new InvalidOperationException("Expected <templates> element not found");
                            }
                            tmpl.Load(templXml);
                        }


                        XmlElement         binFile = test.GetElement("binfile");
                        MessageInputStream mis;
                        byte[]             binData;
                        if (binFile != null)
                        {
                            using (FileStream stream = File.OpenRead(binFile.GetAttribute("path")))
                            {
                                mis     = new MessageInputStream(stream, tmpl.TemplateRegistry);
                                binData = File.ReadAllBytes(binFile.GetAttribute("path"));
                            }
                        }
                        else
                        {
                            XmlElement binstr = test.GetElement("binstr");
                            if (binstr != null)
                            {
                                string binStream = binstr.InnerText.Trim();
                                binData = ByteUtil.ConvertBitStringToFastByteArray(binStream);
                            }
                            else
                            {
                                XmlElement bin64 = test.GetElement("bin64");
                                binData = Convert.FromBase64String(bin64.Value);
                            }

                            mis = new MessageInputStream(new MemoryStream(binData), tmpl.TemplateRegistry);
                        }

                        //
                        // TODO - read the messages and check them against the tests
                        //

                        //
                        // TODO: check against "action" variable -- if All or Encode/Decode
                        //

                        Message    msg;
                        XmlElement target    = test.GetElement("data");
                        XmlNode    msgString = target.FirstChild;
                        var        msgStream = new MemoryStream();
                        var        mout      = new MessageOutputStream(msgStream, tmpl.TemplateRegistry);

                        while ((msg = mis.ReadMessage()) != null)
                        {
                            //TODO: Introduce FIX decoding/encoding Scheme);
                            if (msgString != null)
                            {
                                mout.WriteMessage(msg);
                                Assert.AreEqual(msgString.InnerText.Trim(), msg.ToString());
                                msgString = msgString.NextSibling;
                            }
                            else
                            {
                                Console.WriteLine(msg);
                            }
                        }
                        if (action == Actions.All)
                        {
                            //Verifying Encoding
                            if (binData != null)
                            {
                                byte[] outStrem = msgStream.ToArray();
                                if (outStrem.Length > 0)
                                {
                                    for (int i = 0; i < binData.Length; i++)
                                    {
                                        Assert.AreEqual(binData[i], outStrem[i]);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("WARNING: No data emitted during encoding.");
                                }
                            }
                        }
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
        }
        public void TestMultipleMessages()
        {
            var outStream = new MemoryStream();
            var output = new MessageOutputStream(outStream);
            output.RegisterTemplate(ObjectMother.AllocInstrctnTemplateId,
                                    ObjectMother.AllocationInstruction);

            var allocations = new SequenceValue(ObjectMother.AllocationInstruction
                                                    .GetSequence("Allocations"));
            allocations.Add(ObjectMother.NewAllocation("fortyFiveFund", 22.5, 75.0));
            allocations.Add(ObjectMother.NewAllocation("fortyFund", 24.6, 25.0));

            Message ai1 = ObjectMother.NewAllocInstrctn(
                "ltg0001", 1, 100.0, 23.4, ObjectMother.NewInstrument("CTYA", "200910"), allocations);

            allocations = new SequenceValue(
                ObjectMother.AllocationInstruction.GetSequence("Allocations"));

            allocations.Add(ObjectMother.NewAllocation("fortyFiveFund", 22.5, 75.0));
            allocations.Add(ObjectMother.NewAllocation("fortyFund", 24.6, 25.0));

            Message ai2 = ObjectMother.NewAllocInstrctn(
                "ltg0001", 1, 100.0, 23.4, ObjectMother.NewInstrument("CTYA", "200910"), allocations);

            allocations = new SequenceValue(
                ObjectMother.AllocationInstruction.GetSequence("Allocations"));
            allocations.Add(ObjectMother.NewAllocation("fortyFiveFund", 22.5, 75.0));
            allocations.Add(ObjectMother.NewAllocation("fortyFund", 24.6, 25.0));

            Message ai3 = ObjectMother.NewAllocInstrctn(
                "ltg0001", 1, 100.0, 23.4, ObjectMother.NewInstrument("CTYA", "200910"), allocations);

            output.WriteMessage(ai1);
            output.WriteMessage(ai2);
            output.WriteMessage(ai3);

            byte[] bytes = outStream.ToArray();
            var input = new MessageInputStream(new MemoryStream(bytes));
            input.RegisterTemplate(ObjectMother.AllocInstrctnTemplateId,
                                   ObjectMother.AllocationInstruction);

            Message message = input.ReadMessage();
            Assert.AreEqual(ai1, message);
            message = input.ReadMessage();
            Assert.AreEqual(ai2, message);
            Assert.AreEqual(ai3, input.ReadMessage());
        }
Beispiel #16
0
        private void ListenForMessages()
        {
            if (_listeningThread == null)
            {
                _listeningThread = new Thread(
                    () =>
                {
                    while (_listening)
                    {
                        try
                        {
                            Message message = MessageInputStream.ReadMessage();

                            if (message == null)
                            {
                                _listening = false;
                                break;
                            }
                            if (_protocol.IsProtocolMessage(message))
                            {
                                _protocol.HandleMessage(this, message);
                            }
                            else if (_messageListener != null)
                            {
                                _messageListener.OnMessage(this, message);
                            }
                            else
                            {
                                throw new InvalidOperationException(
                                    "Received non-protocol message without a message listener.");
                            }
                        }
                        catch (Exception e)
                        {
                            Exception cause = e.InnerException;

                            if (cause != null && cause.GetType().Equals(typeof(SocketException)) &&
                                cause.Message.Equals("Socket closed"))
                            {
                                _listening = false;
                            }
                            else if (e is DynErrorException)
                            {
                                var fastException = ((DynErrorException)e);
                                _errorHandler.OnError(e, fastException.Error, fastException.Message);
                            }
                            else
                            {
                                _errorHandler.OnError(e, DynError.GeneralError, e.Message);
                            }
                        }
                    }
                })
                {
                    Name = "FAST Session Message Reader"
                };
            }

            if (_listeningThread.IsAlive)
            {
                return;
            }

            _listeningThread.Start();
        }
Beispiel #17
0
        public void TestComplexMessage()
        {
            var template = new MessageTemplate(
                "Company",
                new Field[]
            {
                new Scalar("Name", FastType.String, Operator.None, ScalarValue.Undefined, false),
                new Scalar("Id", FastType.U32, Operator.Increment, ScalarValue.Undefined, false),
                new Sequence(
                    "Employees",
                    new Field[]
                {
                    new Scalar("First Name", FastType.String, Operator.Copy, ScalarValue.Undefined,
                               false),
                    new Scalar("Last Name", FastType.String, Operator.Copy, ScalarValue.Undefined, false)
                    ,
                    new Scalar("Age", FastType.U32, Operator.Delta, ScalarValue.Undefined, false)
                }, false),
                new Group(
                    "Tax Information",
                    new Field[]
                {
                    new Scalar("EIN", FastType.String, Operator.None, ScalarValue.Undefined, false)
                }, false)
            });

            var aaaInsurance = new Message(template);

            aaaInsurance.SetFieldValue(1, new StringValue("AAA Insurance"));
            aaaInsurance.SetFieldValue(2, new IntegerValue(5));

            var employees = new SequenceValue(template.GetSequence(
                                                  "Employees"));

            employees.Add(new IFieldValue[]
            {
                new StringValue("John"), new StringValue("Doe"),
                new IntegerValue(45)
            });
            employees.Add(new IFieldValue[]
            {
                new StringValue("Jane"), new StringValue("Doe"),
                new IntegerValue(48)
            });
            aaaInsurance.SetFieldValue(3, employees);
            aaaInsurance.SetFieldValue(4,
                                       new GroupValue(template.GetGroup("Tax Information"),
                                                      new IFieldValue[] { new StringValue("99-99999999") }));

            var outStream = new MemoryStream();
            var output    = new MessageOutputStream(outStream);

            output.RegisterTemplate(2, template);
            output.WriteMessage(aaaInsurance);

            var abcBuilding = new Message(template);

            abcBuilding.SetFieldValue(1, new StringValue("ABC Building"));
            abcBuilding.SetFieldValue(2, new IntegerValue(6));
            employees = new SequenceValue(template.GetSequence("Employees"));
            employees.Add(new IFieldValue[]
            {
                new StringValue("Bob"), new StringValue("Builder"),
                new IntegerValue(3)
            });
            employees.Add(new IFieldValue[]
            {
                new StringValue("Joe"), new StringValue("Rock"),
                new IntegerValue(59)
            });
            abcBuilding.SetFieldValue(3, employees);
            abcBuilding.SetFieldValue(4,
                                      new GroupValue(template.GetGroup("Tax Information"),
                                                     new IFieldValue[] { new StringValue("99-99999999") }));
            output.WriteMessage(abcBuilding);

            var input = new MessageInputStream(new MemoryStream(outStream.ToArray()));

            input.RegisterTemplate(2, template);

            GroupValue message = input.ReadMessage();

            Assert.AreEqual(aaaInsurance, message);

            message = input.ReadMessage();
            Assert.AreEqual(abcBuilding, message);
        }
        public void TestComplexMessage()
        {
            var template = new MessageTemplate(
                "Company",
                new Field[]
                    {
                        new Scalar("Name", FastType.String, Operator.None, ScalarValue.Undefined, false),
                        new Scalar("Id", FastType.U32, Operator.Increment, ScalarValue.Undefined, false),
                        new Sequence(
                            "Employees",
                            new Field[]
                                {
                                    new Scalar("First Name", FastType.String, Operator.Copy, ScalarValue.Undefined,
                                               false),
                                    new Scalar("Last Name", FastType.String, Operator.Copy, ScalarValue.Undefined, false)
                                    ,
                                    new Scalar("Age", FastType.U32, Operator.Delta, ScalarValue.Undefined, false)
                                }, false),
                        new Group(
                            "Tax Information",
                            new Field[]
                                {
                                    new Scalar("EIN", FastType.String, Operator.None, ScalarValue.Undefined, false)
                                }, false)
                    });

            var aaaInsurance = new Message(template);
            aaaInsurance.SetFieldValue(1, new StringValue("AAA Insurance"));
            aaaInsurance.SetFieldValue(2, new IntegerValue(5));

            var employees = new SequenceValue(template.GetSequence(
                "Employees"));
            employees.Add(new IFieldValue[]
                              {
                                  new StringValue("John"), new StringValue("Doe"),
                                  new IntegerValue(45)
                              });
            employees.Add(new IFieldValue[]
                              {
                                  new StringValue("Jane"), new StringValue("Doe"),
                                  new IntegerValue(48)
                              });
            aaaInsurance.SetFieldValue(3, employees);
            aaaInsurance.SetFieldValue(4,
                                       new GroupValue(template.GetGroup("Tax Information"),
                                                      new IFieldValue[] {new StringValue("99-99999999")}));

            var outStream = new MemoryStream();
            var output = new MessageOutputStream(outStream);
            output.RegisterTemplate(1, template);
            output.WriteMessage(aaaInsurance);

            var abcBuilding = new Message(template);
            abcBuilding.SetFieldValue(1, new StringValue("ABC Building"));
            abcBuilding.SetFieldValue(2, new IntegerValue(6));
            employees = new SequenceValue(template.GetSequence("Employees"));
            employees.Add(new IFieldValue[]
                              {
                                  new StringValue("Bob"), new StringValue("Builder"),
                                  new IntegerValue(3)
                              });
            employees.Add(new IFieldValue[]
                              {
                                  new StringValue("Joe"), new StringValue("Rock"),
                                  new IntegerValue(59)
                              });
            abcBuilding.SetFieldValue(3, employees);
            abcBuilding.SetFieldValue(4,
                                      new GroupValue(template.GetGroup("Tax Information"),
                                                     new IFieldValue[] {new StringValue("99-99999999")}));
            output.WriteMessage(abcBuilding);

            var input = new MessageInputStream(new MemoryStream(outStream.ToArray()));
            input.RegisterTemplate(1, template);

            GroupValue message = input.ReadMessage();
            Assert.AreEqual(aaaInsurance, message);

            message = input.ReadMessage();
            Assert.AreEqual(abcBuilding, message);
        }
        public void RunAllTests()
        {
            Console.WriteLine("Initializing...");

            // throw args.Exception;
            ValidationEventHandler errorHandler =
                (sender, args) => Console.WriteLine("Error {0}\n{1}", args.Message, args.Exception);

            Type thisType = MethodBase.GetCurrentMethod().DeclaringType;
            Stream schema = thisType.Assembly.GetManifestResourceStream(thisType, "TestSchema.xsd");
            Assert.IsNotNull(schema, "Unable to load XSD from the resources");

            var settings = new XmlReaderSettings();
            settings.Schemas.Add(XmlSchema.Read(schema, errorHandler));

            //
            // BUG!  TODO! change to schema-validated input
            //
            settings.ValidationType = ValidationType.None; // ValidationType.Schema;
            settings.ValidationEventHandler += errorHandler;

            foreach (string xmlFile in Directory.GetFiles(XmlTestFilesDir, "*.xml"))
            {
                Console.WriteLine("Processing {0}...", xmlFile);

                XmlReader reader = XmlReader.Create(xmlFile, settings);
                try
                {
                    var xml = new XmlDocument();
                    xml.Load(reader);

                    foreach (XmlElement test in xml.GetElementsByTagName("test"))
                    {
                        XmlElement desc = test.GetElement("desc");

                        string actionStr = test.GetAttribute("action");
                        if (string.IsNullOrEmpty(actionStr)) actionStr = "all";
                        var action = (Actions) Enum.Parse(typeof (Actions), actionStr, true);

                        Console.WriteLine("  Test {0}{1}{2}", test.GetAttribute("name"),
                                          desc == null || string.IsNullOrEmpty(desc.Value) ? "" : " - " + desc.Value,
                                          action == Actions.All ? "" : " (" + action + " only)");

                        var tmpl = new XmlMessageTemplateLoader();

                        XmlElement templFile = test.GetElement("templatesfile");
                        tmpl.LoadTemplateIdFromAuxId = true;
                        if (templFile != null)
                        {
                            using (FileStream stream = File.OpenRead(templFile.GetAttribute("path")))
                                tmpl.Load(stream);
                        }
                        else
                        {
                            XmlElement templXml = test.GetElement("templates", FastConstants.TemplateDefinition11);
                            if (templXml == null)
                                throw new InvalidOperationException("Expected <templates> element not found");
                            tmpl.Load(templXml);
                        }

                        XmlElement binFile = test.GetElement("binfile");
                        MessageInputStream mis;
                        byte[] binData;
                        if (binFile != null)
                        {
                            using (FileStream stream = File.OpenRead(binFile.GetAttribute("path")))
                            {
                                mis = new MessageInputStream(stream, tmpl.TemplateRegistry);
                                binData = File.ReadAllBytes(binFile.GetAttribute("path"));
                            }
                        }
                        else
                        {
                            XmlElement binstr = test.GetElement("binstr");
                            if (binstr != null)
                            {
                                string binStream = binstr.InnerText.Trim();
                                binData = ByteUtil.ConvertBitStringToFastByteArray(binStream);
                            }
                            else
                            {
                                XmlElement bin64 = test.GetElement("bin64");
                                binData = Convert.FromBase64String(bin64.Value);
                            }

                            mis = new MessageInputStream(new MemoryStream(binData), tmpl.TemplateRegistry);

                        }

                        //
                        // TODO - read the messages and check them against the tests
                        //

                        //
                        // TODO: check against "action" variable -- if All or Encode/Decode
                        //

                        Message msg;
                        XmlElement target = test.GetElement("data");
                        XmlNode msgString = target.FirstChild;
                        var msgStream = new MemoryStream();
                        var mout = new MessageOutputStream(msgStream, tmpl.TemplateRegistry);

                        while ((msg = mis.ReadMessage()) != null)
                        {
                            //TODO: Introduce FIX decoding/encoding Scheme);
                            if (msgString != null)
                            {
                                mout.WriteMessage(msg);
                                Assert.AreEqual(msgString.InnerText.Trim(), msg.ToString());
                                msgString = msgString.NextSibling;

                            }
                            else
                            {
                                Console.WriteLine(msg);
                            }
                        }
                        if (action == Actions.All)
                        {
                            //Verifying Encoding
                            if (binData != null)
                            {
                                byte[] outStrem = msgStream.ToArray();
                                if (outStrem.Length > 0)
                                {
                                    for (int i = 0; i < binData.Length; i++)
                                    {
                                        Assert.AreEqual(binData[i], outStrem[i]);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("WARNING: No data emitted during encoding.");
                                }

                            }
                        }
                    }
                }
                finally
                {
                    reader.Close();
                }
            }
        }