Exemplo n.º 1
0
        public void Encode()
        {
            FormatterContext formatterContext =
                new FormatterContext(FormatterContext.DefaultBufferSize);

            int[] sizes = { 3, 15, 999, 4510, 16384, 681115 };

            StringLengthEncoder encoder;
            string data;

            for (int i = 0; i < sizes.Length; i++)
            {
                encoder = StringLengthEncoder.GetInstance(sizes[i]);
                encoder.Encode(sizes[i], ref formatterContext);
                data = formatterContext.GetDataAsString();
                Assert.IsTrue(data.Length == (i + 1));
                Assert.IsTrue(Convert.ToInt32(data) == sizes[i]);
                formatterContext.Clear();
            }

            encoder = StringLengthEncoder.GetInstance(999);
            try {
                encoder.Encode(1000, ref formatterContext);
                Assert.Fail();
            } catch (ArgumentOutOfRangeException e) {
                Assert.IsTrue(e.ParamName == "length");
            }
        }
Exemplo n.º 2
0
        protected override Task <object> OnReadFromStreamAsync(Type type, Stream stream,
                                                               HttpContentHeaders contentHeaders,
                                                               FormatterContext formatterContext)
        {
            var serializer = JsonSerializer.Create(jsonSerializerSettings);
            var tcs        = new TaskCompletionSource <object>();

            try
            {
                using (var streamReader = new StreamReader(stream, Encoding))
                {
                    using (var jsonTextReader = new JsonTextReader(streamReader))
                    {
                        var result = serializer.Deserialize(jsonTextReader, type);
                        tcs.SetResult(result);
                    }
                }
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }

            return(tcs.Task);
        }
Exemplo n.º 3
0
        public void GetLeafMessage()
        {
            MessageExpression me = new MessageExpression();
            ParserContext     pc = new ParserContext(ParserContext.DefaultBufferSize);
            FormatterContext  fc = new FormatterContext(FormatterContext.DefaultBufferSize);

            // Passing null message (as parameter and in the contexts).
            try {
                me.GetLeafMessage(ref fc, null);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            try {
                me.GetLeafMessage(ref pc, null);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            Message msg        = MessagesProvider.GetMessage();
            Message anotherMsg = MessagesProvider.GetAnotherMessage();

            Assert.IsTrue(me.GetLeafMessage(ref fc, msg) == msg);
            fc.CurrentMessage = anotherMsg;
            Assert.IsTrue(me.GetLeafMessage(ref fc, msg) == msg);
            Assert.IsTrue(me.GetLeafMessage(ref fc, null) == anotherMsg);

            Assert.IsTrue(me.GetLeafMessage(ref pc, msg) == msg);
            pc.CurrentMessage = anotherMsg;
            Assert.IsTrue(me.GetLeafMessage(ref pc, msg) == msg);
            Assert.IsTrue(me.GetLeafMessage(ref pc, null) == anotherMsg);
        }
Exemplo n.º 4
0
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream,
                                               HttpContentHeaders contentHeaders,
                                               FormatterContext formatterContext,
                                               TransportContext transportContext)
        {
            string callback;

               if (IsJsonpRequest(formatterContext.Response.RequestMessage, out callback))
               {
            return Task.Factory.StartNew(() =>
            {
             var writer = new StreamWriter(stream);
             writer.Write(callback + "(");
             writer.Flush();

             base.OnWriteToStreamAsync(type, value, stream, contentHeaders,
                             formatterContext, transportContext).Wait();

             writer.Write(")");
             writer.Flush();
            });
               }
               else
               {
            return base.OnWriteToStreamAsync(type, value, stream, contentHeaders, formatterContext, transportContext);
               }
        }
        public void Encode()
        {
            FormatterContext formatterContext =
                new FormatterContext(FormatterContext.DefaultBufferSize);

            _encoder.Encode(_data1, ref formatterContext);

            Assert.IsTrue(formatterContext.DataLength == _encodedData1.Length);

            byte[] encodedData = formatterContext.GetData();

            for (int i = _encodedData1.Length - 1; i >= 0; i--)
            {
                Assert.IsTrue(_encodedData1[i] == encodedData[i]);
            }

            formatterContext.Clear();

            _encoder.Encode(_data2, ref formatterContext);

            Assert.IsTrue(formatterContext.DataLength == _encodedData2.Length);

            encodedData = formatterContext.GetData();

            for (int i = _encodedData2.Length - 1; i >= 0; i--)
            {
                Assert.IsTrue(_encodedData2[i] == encodedData[i]);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// It formats the MTI.
 /// </summary>
 /// <param name="message">
 /// The message to be formatted.
 /// </param>
 /// <param name="formatterContext">
 /// The formatter context.
 /// </param>
 public override void BeforeFieldsFormatting(Message message,
                                             ref FormatterContext formatterContext)
 {
     _mtiField.Value = Convert.ToString((( Iso8583Message)
                                         (message)).MessageTypeIdentifier, CultureInfo.InvariantCulture);
     _mtiFormatter.Format(_mtiField, ref formatterContext);
 }
        public void Evaluate()
        {
            ParserContext    pc = new ParserContext(ParserContext.DefaultBufferSize);
            FormatterContext fc = new FormatterContext(FormatterContext.DefaultBufferSize);

            ConditionalAndOperator op = new ConditionalAndOperator(
                new MockBooleanExpression(true), new MockBooleanExpression(true));

            Assert.IsTrue(op.EvaluateParse(ref pc));
            Assert.IsTrue(op.EvaluateFormat(new StringField(3, "000000"), ref fc));

            op = new ConditionalAndOperator(
                new MockBooleanExpression(false), new MockBooleanExpression(true));

            Assert.IsFalse(op.EvaluateParse(ref pc));
            Assert.IsFalse(op.EvaluateFormat(new StringField(3, "000000"), ref fc));

            op = new ConditionalAndOperator(
                new MockBooleanExpression(true), new MockBooleanExpression(false));

            Assert.IsFalse(op.EvaluateParse(ref pc));
            Assert.IsFalse(op.EvaluateFormat(new StringField(3, "000000"), ref fc));

            op = new ConditionalAndOperator(
                new MockBooleanExpression(false), new MockBooleanExpression(false));

            Assert.IsFalse(op.EvaluateParse(ref pc));
            Assert.IsFalse(op.EvaluateFormat(new StringField(3, "000000"), ref fc));
        }
Exemplo n.º 8
0
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream,
                                                     HttpContentHeaders contentHeaders,
                                                     FormatterContext formatterContext,
                                                     TransportContext transportContext)
        {
            var serializer = JsonSerializer.Create(jsonSerializerSettings);
            var tcs        = new TaskCompletionSource <object>();

            try
            {
                using (var streamWriter = new StreamWriter(stream, Encoding))
                {
                    using (var jsonTextWriter = new JsonTextWriter(streamWriter))
                    {
                        serializer.Serialize(jsonTextWriter, value);
                        tcs.SetResult(null);
                    }
                }
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }

            return(tcs.Task);
        }
Exemplo n.º 9
0
 protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
 {
     return new TaskFactory().StartNew(() =>
                                                   {
                                                       new StreamWriter(stream).Write((string)value);
                                                   });
 }
Exemplo n.º 10
0
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream,
                                                     HttpContentHeaders contentHeaders,
                                                     FormatterContext formatterContext,
                                                     TransportContext transportContext)
        {
            var serializer = JsonSerializer.Create(jsonSerializerSettings);
            var tcs = new TaskCompletionSource<object>();

            try
            {
                using (var streamWriter = new StreamWriter(stream, Encoding))
                {
                    using (var jsonTextWriter = new JsonTextWriter(streamWriter))
                    {
                        serializer.Serialize(jsonTextWriter, value);
                        tcs.SetResult(null);
                    }
                }
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }

            return tcs.Task;
        }
Exemplo n.º 11
0
        protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream,
                                                              HttpContentHeaders contentHeaders,
                                                              FormatterContext formatterContext)
        {
            var serializer = JsonSerializer.Create(jsonSerializerSettings);
            var tcs = new TaskCompletionSource<object>();

            try
            {
                using (var streamReader = new StreamReader(stream, Encoding))
                {
                    using (var jsonTextReader = new JsonTextReader(streamReader))
                    {
                        var result = serializer.Deserialize(jsonTextReader, type);
                        tcs.SetResult(result);
                    }
                }
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }

            return tcs.Task;
        }
Exemplo n.º 12
0
 protected override System.Threading.Tasks.Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
 {
     return new TaskFactory<object>().StartNew(() =>
                                                   {
                                                       return new StreamReader(stream).ReadToEnd();
                                                   });
 }
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream,
                                                     HttpContentHeaders contentHeaders,
                                                     FormatterContext formatterContext,
                                                     TransportContext transportContext)
        {
            string callback;

            if (IsJsonpRequest(formatterContext.Response.RequestMessage, out callback))
            {
                return(Task.Factory.StartNew(() =>
                {
                    var writer = new StreamWriter(stream);
                    writer.Write(callback + "(");
                    writer.Flush();

                    base.OnWriteToStreamAsync(type, value, stream, contentHeaders,
                                              formatterContext, transportContext).Wait();

                    writer.Write(")");
                    writer.Flush();
                }));
            }
            else
            {
                return(base.OnWriteToStreamAsync(type, value, stream, contentHeaders, formatterContext, transportContext));
            }
        }
Exemplo n.º 14
0
        public void Evaluate()
        {
            ParserContext    pc = new ParserContext(ParserContext.DefaultBufferSize);
            FormatterContext fc = new FormatterContext(FormatterContext.DefaultBufferSize);

            IsSetExpression ee = new IsSetExpression(new MessageExpression(3));

            // Passing null message (as parameter and in the contexts).
            try {
                ee.EvaluateParse(ref pc);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            try {
                ee.EvaluateFormat(new StringField(3, "000000"), ref fc);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            // Evaluate.
            Message msg = MessagesProvider.GetMessage();

            pc.CurrentMessage = msg;
            Assert.IsTrue(ee.EvaluateParse(ref pc));
            fc.CurrentMessage = msg;
            Assert.IsTrue(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));
            ee = new IsSetExpression(new MessageExpression(4));
            Assert.IsFalse(ee.EvaluateParse(ref pc));
            Assert.IsFalse(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));
        }
Exemplo n.º 15
0
        protected override Task <object> OnReadFromStreamAsync(Type type,
                                                               Stream stream, HttpContentHeaders contentHeaders,
                                                               FormatterContext formatterContext)
        {
            Task <object> task;

            if (type == typeof(IKeyValueModel))
            {
                task = base.OnReadFromStreamAsync(type, stream, contentHeaders, formatterContext);
            }
            else
            {
                task = Task <object> .Factory.StartNew(() =>
                {
                    var settings = new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                    };

                    var sr      = new StreamReader(stream);
                    var jreader = new JsonTextReader(sr);

                    var ser = new JsonSerializer();
                    ser.Converters.Add(new IsoDateTimeConverter());

                    object val = ser.Deserialize(jreader, type);
                    return(val);
                });
            }

            return(task);
        }
        public void GetLeafFieldValueBytes()
        {
            Message          msg = MessagesProvider.GetMessage();
            ParserContext    pc  = new ParserContext(ParserContext.DefaultBufferSize);
            FormatterContext fc  = new FormatterContext(FormatterContext.DefaultBufferSize);

            SubMessageExpression sme = new SubMessageExpression(24, null);

            // Sub field of a field isn't an inner message.
            try {
                sme.GetLeafFieldValueString(ref fc, msg);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            sme = new SubMessageExpression(61, null);
            msg.Fields.Add(new InnerMessageField(61));
            try {
                sme.GetLeafFieldValueString(ref fc, msg);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            sme = new SubMessageExpression(62, new MessageExpression(7));

            // Passing null message (as parameter and in the contexts).
            try {
                sme.GetLeafFieldValueBytes(ref fc, null);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            try {
                sme.GetLeafFieldValueBytes(ref pc, null);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            msg = MessagesProvider.GetMessage();
            Message anotherMsg = MessagesProvider.GetAnotherMessage();

            Assert.IsTrue(MessagesProvider.CompareByteArrays(sme.GetLeafFieldValueBytes(ref fc, msg),
                                                             new byte[] { 0x75, 0xB0, 0xB5 }));
            fc.CurrentMessage = anotherMsg;
            Assert.IsTrue(MessagesProvider.CompareByteArrays(sme.GetLeafFieldValueBytes(ref fc, msg),
                                                             new byte[] { 0x75, 0xB0, 0xB5 }));
            Assert.IsTrue(MessagesProvider.CompareByteArrays(sme.GetLeafFieldValueBytes(ref fc, null),
                                                             new byte[] { 0x95, 0xA0, 0xA5 }));

            Assert.IsTrue(MessagesProvider.CompareByteArrays(sme.GetLeafFieldValueBytes(ref pc, msg),
                                                             new byte[] { 0x75, 0xB0, 0xB5 }));
            pc.CurrentMessage = anotherMsg;
            Assert.IsTrue(MessagesProvider.CompareByteArrays(sme.GetLeafFieldValueBytes(ref pc, msg),
                                                             new byte[] { 0x75, 0xB0, 0xB5 }));
            Assert.IsTrue(MessagesProvider.CompareByteArrays(sme.GetLeafFieldValueBytes(ref pc, null),
                                                             new byte[] { 0x95, 0xA0, 0xA5 }));
        }
        /// <summary>
        /// Updates the data length to be sent to the remote system.
        /// </summary>
        /// <param name="formatterContext">
        /// It's the message formatter context.
        /// </param>
        protected override void UpdateDataLengthHeader(ref FormatterContext formatterContext)
        {
            byte[] buffer = formatterContext.GetBuffer();
            int    length = formatterContext.DataLength - 2;

            buffer[0] = ( byte)(length >> 8);
            buffer[1] = ( byte)length;
        }
Exemplo n.º 18
0
 protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
 {
     var singleContact = value as Contact;
     if (singleContact != null)
     {
         WriteContact(singleContact, stream);
     }
 }
 // This method serializes a type by writing it to a stream. If your formatter supports deserialization, also override the ReadFromStream method.
 protected override Task OnWriteToStreamAsync(
     Type type, object value, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext)
 {
     return Task.Factory.StartNew(() =>
         {
             WriteHigFormat(value, stream);
         });
 }
Exemplo n.º 20
0
 private string GetDescriptFormatterContext(FormatterContext formatterContext)
 {
     return(String.Format("ContentType {0}, HasRequest {1}, HasResponse {2}, IsRead {3} ",
                          formatterContext.ContentType,
                          formatterContext.Request != null,
                          formatterContext.Response != null,
                          formatterContext.IsRead));
 }
 private string GetDescriptFormatterContext(FormatterContext formatterContext)
 {
     return String.Format("ContentType {0}, HasRequest {1}, HasResponse {2}, IsRead {3} ",
                     formatterContext.ContentType ,
                     formatterContext.Request != null,
                     formatterContext.Response != null,
                     formatterContext.IsRead);
 }
Exemplo n.º 22
0
 protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext)
 {
     var view = (View)value;
     view.WriteToStream(stream, _viewEngine);
     var tcs = new TaskCompletionSource<Stream>();
     tcs.SetResult(stream);
     return tcs.Task;
 }
 protected override Task OnWriteToStreamAsync(Type type, object value, System.IO.Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext)
 {
     return Task.Factory.StartNew(() =>
     {
         JsConfig.DateHandler = _dateHandler;
         JsonSerializer.SerializeToStream(value, type, stream);
         JsConfig.Reset();
     });
 }
Exemplo n.º 24
0
        /// <summary>
        /// It returns the field value as string.
        /// </summary>
        /// <param name="formatterContext">
        /// It's the context of formatting to be used by the method.
        /// </param>
        /// <param name="message">
        /// The message to get the field.
        /// </param>
        /// <returns>
        /// The field value.
        /// </returns>
        public string GetLeafFieldValueString(ref FormatterContext formatterContext, Message message)
        {
            if (message == null)
            {
                message = formatterContext.CurrentMessage;
            }

            return(GetString(message));
        }
        public new MediaTypeFormatter SelectWriteFormatter(Type type, FormatterContext formatterContext, IEnumerable<MediaTypeFormatter> formatters, out MediaTypeHeaderValue mediaType)
        {
            string descriptFormatterContext = GetDescriptFormatterContext(formatterContext);

            Console.WriteLine("Selecting Write Formatter for type {0} based on formatter context: {1}", type.Name, descriptFormatterContext);
            var mediaTypeFormatter = _FormatterSelector.SelectWriteFormatter(type, formatterContext, formatters, out mediaType);
            Console.WriteLine("Selected Write Formatter : {0} {1}", mediaTypeFormatter.GetType().Name, mediaType);
            return mediaTypeFormatter;
        }
Exemplo n.º 26
0
        /// <summary>
        /// It formats a ISO 8583 message.
        /// </summary>
        /// <param name="message">
        /// It's the message to be formatted.
        /// </param>
        /// <param name="formatterContext">
        /// It's the formatter context to be used in the format.
        /// </param>
        /// <exception cref="MessagingException">
        /// If the MTI formatter it's unknown.
        /// </exception>
        public override void Format(Message message, ref FormatterContext formatterContext)
        {
            if (_mtiFormatter == null)
            {
                throw new MessagingException(SR.MtiFormatterRequired);
            }

            base.Format(message, ref formatterContext);
        }
        public MediaTypeFormatter SelectReadFormatter(Type type, FormatterContext formatterContext, IEnumerable<MediaTypeFormatter> formatters)
        {
            string descriptFormatterContext = GetDescriptFormatterContext(formatterContext);

            Console.WriteLine("Selecting Read Formatter for type {0} based on formatter context: {1}", type.Name, descriptFormatterContext);
            var mediaTypeFormatter = _FormatterSelector.SelectReadFormatter(type, formatterContext, formatters);
            Console.WriteLine("Selected Read Formatter : {0}", mediaTypeFormatter.GetType().Name);
            return mediaTypeFormatter;
        }
Exemplo n.º 28
0
        /// <summary>
        /// It returns the field value as a byte array.
        /// </summary>
        /// <param name="formatterContext">
        /// It's the context of formatting to be used by the method.
        /// </param>
        /// <param name="message">
        /// The message to get the field.
        /// </param>
        /// <returns>
        /// The field value.
        /// </returns>
        public byte[] GetLeafFieldValueBytes(ref FormatterContext formatterContext, Message message)
        {
            if (message == null)
            {
                message = formatterContext.CurrentMessage;
            }

            return(GetBytes(message));
        }
        /// <summary>
        /// It returns the message.
        /// </summary>
        /// <param name="formatterContext">
        /// It's the context of formatting to be used by the method.
        /// </param>
        /// <param name="message">
        /// The message to get the message field.
        /// </param>
        /// <returns>
        /// The message.
        /// </returns>
        public Message GetLeafMessage(ref FormatterContext formatterContext, Message message)
        {
            if (message == null)
            {
                message = formatterContext.CurrentMessage;
            }

            return(_messageExpression.GetLeafMessage(ref formatterContext, GetInnerMessage(message)));
        }
        /// <summary>
        /// It returns the field value as a byte array.
        /// </summary>
        /// <param name="formatterContext">
        /// It's the context of formatting to be used by the method.
        /// </param>
        /// <param name="message">
        /// The message to get the field.
        /// </param>
        /// <returns>
        /// The field value.
        /// </returns>
        public byte[] GetLeafFieldValueBytes(ref FormatterContext formatterContext, Message message)
        {
            if (message == null)
            {
                message = formatterContext.CurrentMessage;
            }

            return(_messageExpression.GetLeafFieldValueBytes(
                       ref formatterContext, GetInnerMessage(message)));
        }
Exemplo n.º 31
0
        public MediaTypeFormatter SelectWriteFormatter(Type type, FormatterContext formatterContext, IEnumerable <MediaTypeFormatter> formatters, out MediaTypeHeaderValue mediaType)
        {
            string descriptFormatterContext = GetDescriptFormatterContext(formatterContext);

            Console.WriteLine("Selecting Write Formatter for type {0} based on formatter context: {1}", type.Name, descriptFormatterContext);
            var mediaTypeFormatter = _FormatterSelector.SelectWriteFormatter(type, formatterContext, formatters, out mediaType);

            Console.WriteLine("Selected Write Formatter : {0} {1}", mediaTypeFormatter.GetType().Name, mediaType);
            return(mediaTypeFormatter);
        }
        /// <summary>
        /// It returns the field value as string.
        /// </summary>
        /// <param name="formatterContext">
        /// It's the context of formatting to be used by the method.
        /// </param>
        /// <param name="message">
        /// The message to get the field.
        /// </param>
        /// <returns>
        /// The field value.
        /// </returns>
        public string GetLeafFieldValueString(ref FormatterContext formatterContext, Message message)
        {
            if (message == null)
            {
                message = formatterContext.CurrentMessage;
            }

            return(_messageExpression.GetLeafFieldValueString(
                       ref formatterContext, GetParentMessage(message)));
        }
        /// <summary>
        /// Evaluates the field to format to decide the field formatter to be used.
        /// </summary>
        /// <param name="field">
        /// It's the field to format.
        /// </param>
        /// <param name="formatterContext">
        /// It's the context of formatting to be used by the method.
        /// </param>
        /// <returns>
        /// A logical value indicating the field formatter to be used.
        /// </returns>
        public bool EvaluateFormat(Field field, ref FormatterContext formatterContext)
        {
            if (_compiledExpression == null)
            {
                throw new ApplicationException(
                          "The conditional field formatter does not know the expression to evaluate.");
            }

            return(_compiledExpression.EvaluateFormat(field, ref formatterContext));
        }
 protected override Task<object> OnReadFromStreamAsync(Type type, System.IO.Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
 {
     return Task.Factory.StartNew(() =>
     {
         JsConfig.DateHandler = _dateHandler;
         var result = JsonSerializer.DeserializeFromStream(type, stream);
         JsConfig.Reset();
         return result;
     });
 }
        /// <summary>
        /// Updates the data length to be sent to the remote system.
        /// </summary>
        /// <param name="formatterContext">
        /// It's the message formatter context.
        /// </param>
        protected override void UpdateDataLengthHeader(ref FormatterContext formatterContext)
        {
            byte[] buffer = formatterContext.GetBuffer();
            int    length = formatterContext.DataLength - 4;

            for (int i = 3; i >= 0; i--)
            {
                buffer[i] = Convert.ToByte((length % 10) + 0x30);
                length   /= 10;
            }
        }
Exemplo n.º 36
0
        protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            var serializer = JsonSerializer.Create(jsonSerializerSettings);

            return Task.Factory.StartNew(() =>
                {
                    using (var streamReader = new StreamReader(stream, Encoding))
                    using (var jsonTextReader = new JsonTextReader(streamReader))
                        return serializer.Deserialize(jsonTextReader, type);
                });
        }
 /// <summary>
 /// Formats the specified field.
 /// </summary>
 /// <param name="field">
 /// It's the field to format.
 /// </param>
 /// <param name="formatterContext">
 /// It's the context of formatting to be used by the method.
 /// </param>
 public override void Format(Field field, ref FormatterContext formatterContext)
 {
     if (_evaluator.EvaluateFormat(field, ref formatterContext))
     {
         _trueFormatter.Format(field, ref formatterContext);
     }
     else
     {
         _falseFormatter.Format(field, ref formatterContext);
     }
 }
Exemplo n.º 38
0
 protected override System.Threading.Tasks.Task <object> OnReadFromStreamAsync(
     Type type,
     System.IO.Stream stream,
     HttpContentHeaders contentHeaders,
     FormatterContext formatterContext)
 {
     return
         (new Task <object>(() => {
         return new StreamReader(stream).ReadToEnd();
     }));
 }
        public void GetLeafMessage()
        {
            Message          msg = MessagesProvider.GetMessage();
            ParserContext    pc  = new ParserContext(ParserContext.DefaultBufferSize);
            FormatterContext fc  = new FormatterContext(FormatterContext.DefaultBufferSize);

            SubMessageExpression sme = new SubMessageExpression(24, null);

            // Sub field of a field isn't an inner message.
            try {
                sme.GetLeafMessage(ref fc, msg);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            sme = new SubMessageExpression(61, null);
            msg.Fields.Add(new InnerMessageField(61));
            try {
                sme.GetLeafMessage(ref fc, msg);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            sme = new SubMessageExpression(61, new MessageExpression());

            // Passing null message (as parameter and in the contexts).
            try {
                sme.GetLeafMessage(ref fc, null);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            try {
                sme.GetLeafMessage(ref pc, null);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            msg = MessagesProvider.GetMessage();
            Message anotherMsg = MessagesProvider.GetAnotherMessage();

            Assert.IsTrue((sme.GetLeafMessage(ref fc, msg)[6].Value as string) == "123");
            fc.CurrentMessage = anotherMsg;
            Assert.IsTrue((sme.GetLeafMessage(ref fc, msg)[6].Value as string) == "123");
            Assert.IsTrue((sme.GetLeafMessage(ref fc, null)[6].Value as string) == "456");

            Assert.IsTrue((sme.GetLeafMessage(ref pc, msg)[6].Value as string) == "123");
            pc.CurrentMessage = anotherMsg;
            Assert.IsTrue((sme.GetLeafMessage(ref pc, msg)[6].Value as string) == "123");
            Assert.IsTrue((sme.GetLeafMessage(ref pc, null)[6].Value as string) == "456");
        }
        protected override Task OnWriteToStreamAsync(
            Type type,
            object value,
            Stream stream,
            HttpContentHeaders contentHeaders,
            FormatterContext formatterContext,
            TransportContext transportContext) {

            return Task.Factory.StartNew(() => {
                writeStream(type, value, stream, contentHeaders);
            });
        }
        protected override Task<object> OnReadFromStreamAsync(Type type,
                                                              System.IO.Stream stream,
                                                              System.Net.Http.Headers.HttpContentHeaders contentHeaders,
                                                              FormatterContext formatterContext) {
            return
                Task.Factory.StartNew(() => {
                                          var serializer = new JavaScriptSerializer();

                                          using(var reader = new StreamReader(stream))
                                              return serializer.Deserialize(reader.ReadToEnd(), type);
                                      });
        }
Exemplo n.º 42
0
 protected override Task OnWriteToStreamAsync(
     Type type,
     object value,
     Stream stream,
     HttpContentHeaders contentHeaders,
     FormatterContext formatterContext,
     TransportContext transportContext)
 {
     return(Task.Factory.StartNew(() => {
         writeStream(type, value, stream, contentHeaders);
     }));
 }
Exemplo n.º 43
0
        public void GetLeafFieldValueBytes()
        {
            Message          msg = MessagesProvider.GetMessage();
            ParserContext    pc  = new ParserContext(ParserContext.DefaultBufferSize);
            FormatterContext fc  = new FormatterContext(FormatterContext.DefaultBufferSize);

            ParentMessageExpression pme = new ParentMessageExpression(
                new MessageExpression(52));

            // Parent of a message without one.
            try {
                pme.GetLeafFieldValueString(ref fc, msg);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            // Passing null message (as parameter and in the contexts).
            try {
                pme.GetLeafFieldValueString(ref fc, null);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            try {
                pme.GetLeafFieldValueString(ref pc, null);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            msg = msg[62].Value as Message;
            Message anotherMsg = MessagesProvider.GetAnotherMessage();

            anotherMsg = anotherMsg[61].Value as Message;

            Assert.IsTrue(MessagesProvider.CompareByteArrays(pme.GetLeafFieldValueBytes(ref fc, msg),
                                                             new byte[] { 0x15, 0x20, 0x25, 0x30, 0x35, 0x40, 0x45, 0x50 }));
            fc.CurrentMessage = anotherMsg;
            Assert.IsTrue(MessagesProvider.CompareByteArrays(pme.GetLeafFieldValueBytes(ref fc, msg),
                                                             new byte[] { 0x15, 0x20, 0x25, 0x30, 0x35, 0x40, 0x45, 0x50 }));
            Assert.IsTrue(MessagesProvider.CompareByteArrays(pme.GetLeafFieldValueBytes(ref fc, null),
                                                             new byte[] { 0x55, 0x60, 0x65, 0x70, 0x75, 0x80, 0x85, 0x90 }));

            Assert.IsTrue(MessagesProvider.CompareByteArrays(pme.GetLeafFieldValueBytes(ref pc, msg),
                                                             new byte[] { 0x15, 0x20, 0x25, 0x30, 0x35, 0x40, 0x45, 0x50 }));
            pc.CurrentMessage = anotherMsg;
            Assert.IsTrue(MessagesProvider.CompareByteArrays(pme.GetLeafFieldValueBytes(ref pc, msg),
                                                             new byte[] { 0x15, 0x20, 0x25, 0x30, 0x35, 0x40, 0x45, 0x50 }));
            Assert.IsTrue(MessagesProvider.CompareByteArrays(pme.GetLeafFieldValueBytes(ref pc, null),
                                                             new byte[] { 0x55, 0x60, 0x65, 0x70, 0x75, 0x80, 0x85, 0x90 }));
        }
Exemplo n.º 44
0
        public void Evaluate()
        {
            ParserContext    pc = new ParserContext(ParserContext.DefaultBufferSize);
            FormatterContext fc = new FormatterContext(FormatterContext.DefaultBufferSize);

            MtiEqualsExpression ee = new MtiEqualsExpression(200, new MessageExpression());

            // Passing null message (as parameter and in the contexts).
            try {
                ee.EvaluateParse(ref pc);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            try {
                ee.EvaluateFormat(new StringField(3, "000000"), ref fc);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            // Evaluate with incorrect message type.
            Message msg = MessagesProvider.GetMessage();

            pc.CurrentMessage = msg;
            try {
                ee.EvaluateParse(ref pc);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }
            fc.CurrentMessage = msg;
            try {
                ee.EvaluateFormat(new StringField(3, "000000"), ref fc);
                Assert.Fail();
            }
            catch (ExpressionEvaluationException) {
            }

            // Evaluate against an ISO 8583 message.
            Iso8583Message isoMsg = MessagesProvider.GetIso8583Message();

            pc.CurrentMessage = isoMsg;
            Assert.IsTrue(ee.EvaluateParse(ref pc));
            fc.CurrentMessage = isoMsg;
            Assert.IsTrue(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));
            isoMsg            = MessagesProvider.GetAnotherIso8583Message();
            pc.CurrentMessage = isoMsg;
            Assert.IsFalse(ee.EvaluateParse(ref pc));
            fc.CurrentMessage = isoMsg;
            Assert.IsFalse(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));
        }
Exemplo n.º 45
0
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        {
            var serializer = JsonSerializer.Create(jsonSerializerSettings);

            return Task.Factory.StartNew(() =>
            {
                using (var jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, Encoding)) { Formatting = Formatting.Indented, CloseOutput = false })
                {
                    serializer.Serialize(jsonTextWriter, value);
                    jsonTextWriter.Flush();
                }
            });
        }
        protected override Task <object> OnReadFromStreamAsync(Type type,
                                                               System.IO.Stream stream,
                                                               System.Net.Http.Headers.HttpContentHeaders contentHeaders,
                                                               FormatterContext formatterContext)
        {
            return
                (Task.Factory.StartNew(() => {
                var serializer = new JavaScriptSerializer();

                using (var reader = new StreamReader(stream))
                    return serializer.Deserialize(reader.ReadToEnd(), type);
            }));
        }
Exemplo n.º 47
0
        public void Evaluate()
        {
            ParserContext    pc = new ParserContext(ParserContext.DefaultBufferSize);
            FormatterContext fc = new FormatterContext(FormatterContext.DefaultBufferSize);

            FieldValueEqualsBinaryOperator ee = new FieldValueEqualsBinaryOperator(
                new MessageExpression(1), new BinaryConstantExpression(null));

            Message msg = new Message();

            msg.Fields.Add(new BinaryField(1, null));

            // Both values are null.
            pc.CurrentMessage = msg;
            Assert.IsTrue(ee.EvaluateParse(ref pc));
            fc.CurrentMessage = msg;
            Assert.IsTrue(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));

            ee = new FieldValueEqualsBinaryOperator(
                new MessageExpression(1), new BinaryConstantExpression("1520253035404550"));
            // Field value is null.
            Assert.IsFalse(ee.EvaluateParse(ref pc));
            Assert.IsFalse(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));

            ee = new FieldValueEqualsBinaryOperator(
                new MessageExpression(52), new BinaryConstantExpression(null));
            msg = MessagesProvider.GetMessage();
            // Constant is null.
            pc.CurrentMessage = msg;
            Assert.IsFalse(ee.EvaluateParse(ref pc));
            fc.CurrentMessage = msg;
            Assert.IsFalse(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));

            ee = new FieldValueEqualsBinaryOperator(
                new MessageExpression(52), new BinaryConstantExpression("152025303540"));
            // Different lengths.
            Assert.IsFalse(ee.EvaluateParse(ref pc));
            Assert.IsFalse(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));

            ee = new FieldValueEqualsBinaryOperator(
                new MessageExpression(52), new BinaryConstantExpression("1520253035404551"));
            // Different data.
            Assert.IsFalse(ee.EvaluateParse(ref pc));
            Assert.IsFalse(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));

            ee = new FieldValueEqualsBinaryOperator(
                new MessageExpression(52), new BinaryConstantExpression("1520253035404550"));
            // Equals.
            Assert.IsTrue(ee.EvaluateParse(ref pc));
            Assert.IsTrue(ee.EvaluateFormat(new StringField(3, "000000"), ref fc));
        }
Exemplo n.º 48
0
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        {
            // Create a serializer
            JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
            // Create task writing the serialized content
            return Task.Factory.StartNew(() =>
            {
                using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, Encoding)) )
                {

                    serializer.Serialize(jsonTextWriter, value);
                    jsonTextWriter.Flush();
                }
            });
        }
Exemplo n.º 49
0
        protected override Task OnWriteToStreamAsync(
            Type type, 
            object value, 
            Stream stream, 
            HttpContentHeaders contentHeaders, 
            FormatterContext formatterContext, 
            System.Net.TransportContext transportContext) {

            return
                new Task(() => {

                    var writer = new StreamWriter(stream);
                    writer.Write(value.ToString());
                });
        }
Exemplo n.º 50
0
        protected override Task OnWriteToStreamAsync(Type type,
                                                     object value,
                                                     Stream stream,
                                                     HttpContentHeaders contentHeaders,
                                                     FormatterContext formatterContext,
                                                     TransportContext transportContext)
        {
            if(IsDebugEnabled)
                log.Debug("객체정보를 스트림에 씁니다...");

            return
                Task.Factory.StartNew(() =>
                                      JsonConvert.SerializeObject(value,
                                                                  Formatting.Indented,
                                                                  MvcTool.DefaultJsonSerializerSettings));
        }
 protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
 {
     if (type == typeof(JsonObject))
     {
         return Task.Factory.StartNew(() =>
         {
             var pairs = new List<string>();
             Flatten(pairs, value as JsonObject);
             var bytes = encoding.GetBytes(string.Join("&", pairs));
             stream.Write(bytes, 0, bytes.Length);
         });
     }
     else
     {
         return base.OnWriteToStreamAsync(type, value, stream, contentHeaders, formatterContext, transportContext);
     }
 }
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream,
                                                     HttpContentHeaders contentHeaders,
                                                     FormatterContext formatterContext,
                                                     TransportContext transportContext)
        {
            var task = Task.Factory.StartNew(() =>
            {
                var ser = new JavaScriptSerializer();
                var json = ser.Serialize(value);
                var buf = System.Text.Encoding.Default.GetBytes(json);

                stream.Write(buf, 0, buf.Length);
                stream.Flush();
            });

            return task;
        }
        protected override Task OnWriteToStreamAsync(Type type, object value,
                                                     System.IO.Stream stream,
                                                     System.Net.Http.Headers.HttpContentHeaders contentHeaders,
                                                     FormatterContext formatterContext,
                                                     System.Net.TransportContext transportContext) {
            return
                Task.Factory.StartNew(() => {
                                          var serializer = new JavaScriptSerializer();
                                          var sb = new StringBuilder();

                                          serializer.Serialize(value, sb);

                                          var buffer = Encoding.UTF8.GetBytes(sb.ToString());
                                          stream.Write(buffer, 0, buffer.Length);
                                          stream.Flush();
                                      });
        }
 protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
 {
     return SyncTask.From(() =>
                              {
                                  var s = value as string;
                                  if (s == null) return;
                                  using (var synth = new SpeechSynthesizer())
                                  {
                                      var ms = new MemoryStream();
                                      synth.SetOutputToWaveStream(ms);
                                      //synth.Rate -= 10;
                                      synth.Speak("response is "+s);
                                      ms.Seek(0, SeekOrigin.Begin);
                                      ms.CopyTo(stream);
                                  }
                                  stream.Close();
                              });
 }
        protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream,
                                                              HttpContentHeaders contentHeaders,
                                                              FormatterContext formatterContext)
        {
            var task = Task.Factory.StartNew(() =>
            {
                using (var rdr = new StreamReader(stream))
                {
                    var json = rdr.ReadToEnd();
                    var ser = new JavaScriptSerializer();
                    var result = ser.Deserialize(json, type);

                    return result;
                }
            });

            return task;
        }
Exemplo n.º 56
0
        protected override Task<object> OnReadFromStreamAsync(Type type,
                                                              Stream stream,
                                                              HttpContentHeaders contentHeaders,
                                                              FormatterContext formatterContext)
        {
            if(IsDebugEnabled)
                log.Debug("스트림으로부터 정보를 읽습니다...");

            return
                Task.Factory.StartNew(() =>
                                      {
                                          using(var reader = new StreamReader(stream))
                                          {
                                              var jsonText = reader.ReadToEnd();
                                              return JsonConvert.DeserializeObject(jsonText,
                                                                                   MvcTool.DefaultJsonSerializerSettings);
                                          }
                                      });
        }
        protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        {
            return SyncTask.From(() =>
                                     {
                                         var text = value as string;
                                         const int pts = 40;
                                         var bm = new Bitmap(text.Length*pts, 2*pts);
                                         var g = Graphics.FromImage(bm);
                                         g.DrawString(text, new Font("Arial", pts), Brushes.White, 1.0f, 1.0f);

                                         var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
                                         var myEncoder =
                                             System.Drawing.Imaging.Encoder.Quality;
                                         var myEncoderParameters = new EncoderParameters(1);
                                         var myEncoderParameter = new EncoderParameter(myEncoder, 100L);
                                         myEncoderParameters.Param[0] = myEncoderParameter;

                                         bm.Save(stream, jgpEncoder, myEncoderParameters);
                                     });
        }
Exemplo n.º 58
0
        //protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        //{
        //    // Create a serializer
        //    JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
        //    // Create task reading the content
        //    return Task.Factory.StartNew(() =>
        //   {
        //       using (StreamReader streamReader = new StreamReader(stream, Encoding))
        //       {
        //           using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
        //           {
        //               return serializer.Deserialize(jsonTextReader, type);
        //           }
        //       }
        //   });
        //}
        //protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        //{
        //    // Create a serializer
        //    JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
        //    // Create task writing the serialized content
        //    return Task.Factory.StartNew(() =>
        //    {
        //        using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, Encoding)) { CloseOutput = false })
        //        {
        //            serializer.Serialize(jsonTextWriter, value);
        //            jsonTextWriter.Flush();
        //        }
        //    });
        //}
        protected override System.Threading.Tasks.Task<object> OnReadFromStreamAsync(Type type, System.IO.Stream stream, System.Net.Http.Headers.HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            var task = Task<object>.Factory.StartNew(() =>
            {
                var settings = new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore,
                };

                var sr = new StreamReader(stream);
                var jreader = new JsonTextReader(sr);

                var ser = new JsonSerializer();
                ser.Converters.Add(new IsoDateTimeConverter());

                object val = ser.Deserialize(jreader, type);
                return val;
            });

            return task;
        }
Exemplo n.º 59
0
    protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
    {
        // Create a serializer
        JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
        //var test = new StreamReader(stream, Encoding).ReadToEnd();

        // Create task reading the content
        return Task.Factory.StartNew(() =>
        {
            using (StreamReader streamReader = new StreamReader(stream, Encoding))
            {
                using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
                {
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(PatchModel<>))
                    {
                        return Activator.CreateInstance(type, new object[] { serializer.Deserialize<Dictionary<string, object>>(jsonTextReader) });
                    }

                    return serializer.Deserialize(jsonTextReader, type);
                }
            }
        });
    }
        protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, System.Net.TransportContext transportContext)
        {
            var json = value as JsonArray;
            var head = json[0];

            var tw = new StreamWriter(stream);

            foreach (var p in head)
            {
                tw.Write(p.Key);
                tw.Write(", ");
            }
            tw.WriteLine();
            foreach (var line in json)
            {
                foreach (var p in line)
                {
                    tw.Write(p.Value.ReadAs<string>());
                    tw.Write(", ");
                }
                tw.WriteLine();
            }
            tw.Flush();
        }