diff --git a/NetCore8583.Test/TestConfigParser.cs b/NetCore8583.Test/TestConfigParser.cs index 1b44a4d..674e3e8 100644 --- a/NetCore8583.Test/TestConfigParser.cs +++ b/NetCore8583.Test/TestConfigParser.cs @@ -252,6 +252,23 @@ public void TestSimpleCompositeTemplate() Assert.False(m.HasField(4)); } + [Fact] + public void TestCreatingResponseWithTypeNotInConfig() + { + var configXml = @"/Resources/issue36.xml"; + var mfact = Config(configXml); + + var m = mfact.NewMessage(0x100); + Assert.NotNull(m); + Assert.True(m.HasField(2)); + Assert.True(m.HasField(3)); + + var r = mfact.CreateResponse(m); + Assert.NotNull(r); + Assert.True(r.HasField(2)); + Assert.True(r.HasField(3)); + } + [Fact] public void TestAllTypesHaveParseInfo() { diff --git a/NetCore8583/MessageFactory.cs b/NetCore8583/MessageFactory.cs index f652498..1dbcf22 100644 --- a/NetCore8583/MessageFactory.cs +++ b/NetCore8583/MessageFactory.cs @@ -148,6 +148,25 @@ protected T CreateIsoMessage(string isoHeader) return (T) new IsoMessage(isoHeader); } + /// + /// Creates a new message of the specified type, with proper ISO header set. + /// + /// The message type, for example 0x200, 0x400, etc. used to define header if available + /// + protected T CreateIsoMessageWithType(int type) + { + T m; + if (_binIsoHeaders.ContainsKey(type)) + m = CreateIsoMessageWithBinaryHeader(_binIsoHeaders[type]); + else if (_isoHeaders.ContainsKey(type)) + m = CreateIsoMessage(_isoHeaders[type]); + else + m = CreateIsoMessage(string.Empty); + + m.Type = type; + return m; + } + /// /// Creates a new message of the specified type, with optional trace and date values as well /// as any other values specified in a message template. If the factory is set to use binary @@ -157,17 +176,7 @@ protected T CreateIsoMessage(string isoHeader) /// public T NewMessage(int type) { - var keyPresent = _binIsoHeaders.ContainsKey(type); - sbyte[] val = null; - var valStr = string.Empty; - - if (keyPresent) - val = _binIsoHeaders[type]; - else if (_isoHeaders.ContainsKey(type)) - valStr = _isoHeaders[type]; - - var m = keyPresent ? CreateIsoMessageWithBinaryHeader(val) : CreateIsoMessage(valStr); - m.Type = type; + T m = CreateIsoMessageWithType(type); m.Etx = Etx; m.Binary = UseBinaryMessages; m.EnforceSecondBitmap = EnforceSecondBitmap; @@ -209,14 +218,13 @@ public T NewMessage(int type) /// public T CreateResponse(T request, bool copyAllFields = true) { - var resp = CreateIsoMessage(_isoHeaders[request.Type + 16]); + var resp = CreateIsoMessageWithType(request.Type + 16); resp.Encoding = request.Encoding; resp.Binary = request.Binary; resp.BinBitmap = request.BinBitmap; - resp.Type = request.Type + 16; resp.Etx = request.Etx; resp.EnforceSecondBitmap = request.EnforceSecondBitmap; - IsoMessage templ = _typeTemplates[resp.Type]; + IsoMessage templ = _typeTemplates.ContainsKey(resp.Type) ? _typeTemplates[resp.Type] : null; if (templ == null) { for (var i = 2; i < 128; i++)