public async Task ScanProofRequest()
        {
            var expectedFormat = ZXing.BarcodeFormat.QR_CODE;
            var opts           = new ZXing.Mobile.MobileBarcodeScanningOptions {
                PossibleFormats = new List <ZXing.BarcodeFormat> {
                    expectedFormat
                }
            };

            var scanner = new ZXing.Mobile.MobileBarcodeScanner();

            var result = await scanner.Scan(opts);

            if (result == null)
            {
                return;
            }

            RequestPresentationMessage presentationMessage;

            try
            {
                presentationMessage = await MessageDecoder.ParseMessageAsync(result.Text) as RequestPresentationMessage
                                      ?? throw new Exception("Unknown message type");
            }
            catch (Exception)
            {
                DialogService.Alert("Invalid Proof Request!");
                return;
            }

            if (presentationMessage == null)
            {
                return;
            }

            try
            {
                var request = presentationMessage.Requests?.FirstOrDefault((Attachment x) => x.Id == "libindy-request-presentation-0");
                if (request == null)
                {
                    DialogService.Alert("scanned qr code does not look like a proof request", "Error");
                    return;
                }
                var proofRequest = request.Data.Base64.GetBytesFromBase64().GetUTF8String().ToObject <ProofRequest>();
                if (proofRequest == null)
                {
                    return;
                }

                var proofRequestViewModel = _scope.Resolve <ProofRequestViewModel>(new NamedParameter("proofRequest", proofRequest),
                                                                                   new NamedParameter("requestPresentationMessage", presentationMessage));

                await NavigationService.NavigateToAsync(proofRequestViewModel);
            }
            catch (Exception xx)
            {
                DialogService.Alert(xx.Message);
            }
        }
        public async Task Should_map_originators_when_message_is_not_from_user()
        {
            var conferenceId  = Guid.NewGuid();
            var loggedInUser  = "******";
            var otherUsername = "******";
            var messages      = Builder <InstantMessageResponse> .CreateListOfSize(5)
                                .TheFirst(2)
                                .With(x => x.From = loggedInUser).TheNext(3)
                                .With(x => x.From = otherUsername)
                                .Build().ToList();

            VideoApiClientMock.Setup(x => x.GetInstantMessageHistoryForParticipantAsync(conferenceId, loggedInUser))
            .ReturnsAsync(messages);

            var result = await Controller.GetConferenceInstantMessageHistoryForParticipantAsync(conferenceId, loggedInUser);

            MessageDecoder.Verify(x => x.IsMessageFromUser(
                                      It.Is <InstantMessageResponse>(m => m.From == loggedInUser), loggedInUser),
                                  Times.Exactly(2));

            MessageDecoder.Verify(x => x.IsMessageFromUser(
                                      It.Is <InstantMessageResponse>(m => m.From == otherUsername), loggedInUser),
                                  Times.Exactly(3));

            var typedResult = (OkObjectResult)result;

            typedResult.Should().NotBeNull();
            var responseModel = typedResult.Value as List <ChatResponse>;

            responseModel?.Count(x => x.FromDisplayName == "You").Should().Be(2);
        }
Ejemplo n.º 3
0
        public static DecodedMessage <byte[]> ReceiveMessage(Socket sock)
        {
            int length   = -1;
            int received = 0;

            byte[] bytes = new byte[1500];

            try
            {
                while (true)
                {
                    int bytesRec = sock.Receive(bytes, received, 1500 - received, SocketFlags.None);
                    received += bytesRec;

                    if (received >= sizeof(int) && length == -1)
                    {
                        length = BitConverter.ToInt32(bytes, 0);
                    }

                    if (received >= length && length > 0)
                    {
                        break;
                    }
                }
            }
            catch
            {
                throw new DeadConnectionException();
            }


            var response = MessageDecoder.Decode(bytes.Skip(sizeof(int)).Take(length).ToArray());

            return(response);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 获取本地设置的用户和密码
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public bool TryGetCredential(string url, out string username, out string password, out string error)
        {
            username = null;
            password = null;
            error    = null;
            Result gitCredentialOutput = this.Process.InvokeGitAgainstDotGitFolder(
                GenerateCredentialVerbCommand("fill"),
                stdin => stdin.Write($"url={url}\n\n"),
                parseStdOutLine: null);

            if (gitCredentialOutput.ExitCodeIsFailure)
            {
                EventMetadata errorData = new EventMetadata();
                error = gitCredentialOutput.Errors;
                return(false);
            }

            username = MessageDecoder.ParseValue(gitCredentialOutput.Output, "username="******"password="******"Success", success);
            if (!success)
            {
                metadata.Add("Output", gitCredentialOutput.Output);
            }

            return(success);
        }
Ejemplo n.º 5
0
        public void UnserialiseStringToObject()
        {
            var ReadCardJSON = @"{""payload"":{""track1"":{""status"":""ok"",""data"":""123456789""},""track2"":{""status"":""dataMissing"",""data"":""123456789""},""track3"":{""status"":""dataInvalid"",""data"":""123456789""},""completionCode"":""success"",""errorDescription"":""OK""},""headers"":{""name"":""CardReader.ReadRawData"",""requestId"":""ee6d592b-483c-4c22-98ef-1070e290bf4f"",""type"":""completion""}}";

            var assemblyName = Assembly.GetAssembly(typeof(ReadRawDataCompletion))?.GetName();

            IsNotNull(assemblyName);

            var decoder = new MessageDecoder(MessageDecoder.AutoPopulateType.Response, assemblyName)
            {
                { typeof(ReadRawDataCompletion) }
            };

            bool rc = decoder.TryUnserialise(ReadCardJSON, out object resultMessage);

            IsTrue(rc);
            IsNotNull(resultMessage);

            Completion <ReadRawDataCompletion.PayloadData> result = resultMessage as Completion <ReadRawDataCompletion.PayloadData> ?? throw new Exception();

            IsNotNull(result);

            IsInstanceOfType(result, typeof(ReadRawDataCompletion));
            ReadRawDataCompletion readCardCompletion = result as ReadRawDataCompletion;

            IsNotNull(readCardCompletion);
            IsNotNull(readCardCompletion.Payload);
            ReadRawDataCompletion.PayloadData readCardPayload = readCardCompletion.Payload as ReadRawDataCompletion.PayloadData;
            IsNotNull(readCardPayload);
            IsNotNull(readCardPayload.Track1);
            IsNotNull(readCardPayload.Track2);
            IsNotNull(readCardPayload.Track3);
        }
Ejemplo n.º 6
0
        public void Start(string hostname, int port)
        {
            if (client != null)
            {
                return;
            }

            if (TryToConnect(hostname, port))
            {
                Task.Factory.StartNew(() =>
                {
                    var messageDecoder = new MessageDecoder();
                    var stream         = client.GetStream();
                    try
                    {
                        while (client.Connected)
                        {
                            var message = messageDecoder.Decode(stream);
                            OnShadeSelected?.Invoke(this, new MessageEventArgs(message));
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        Stop();
                    }
                });
            }
        }
Ejemplo n.º 7
0
 public FileOperationUpdateReceiver(
     FileOperationType operationType, LSClient client)
 {
     OperationType = operationType;
     Client        = client;
     Decoder       = new MessageDecoder();
 }
Ejemplo n.º 8
0
        static void Main()
        {
            MessageIOGateway gw = new MessageIOGateway();
            MessageDecoder   d  = new MessageDecoder();
            MessageEncoder   e  = new MessageEncoder();

            Message m = new Message();

            m.what = PR_COMMAND_GETDATA;
            string text = "*";

            m.setString(PR_NAME_KEYS, text);

            e.Encode(m);

            byte [] buffer = e.GetAndResetBuffer();
            long    start  = DateTime.Now.Ticks;

            for (int i = 0; i < MESSAGE_COUNT; ++i)
            {
                d.Decode(buffer, buffer.Length);
            }

            long end     = DateTime.Now.Ticks;
            long elapsed = end - start;

            DateTime t = new DateTime(elapsed);

            Console.WriteLine("Elapsed time: " + t.ToString());
            Console.WriteLine("Messages flattened and unflattened: " + MESSAGE_COUNT.ToString());
        }
Ejemplo n.º 9
0
        public void Then_the_test_case_should_pass()
        {
            var decoder = new MessageDecoder();
            var result  = decoder.DecodeUsingLeastFrequentCharacters(Input.Test);

            Assert.That(result, Is.EqualTo("advent"));
        }
Ejemplo n.º 10
0
        public void UnserialiseStringToObjectNoHeader()
        {
            var AcceptCardJSON = @"{
                ""payload"":{
                    ""timeout"":5000,
                    ""track1"":true,
                    ""track2"": true,
                    ""track3"":true,
                    ""chip"":true,
                    ""security"":true,
                    ""fluxInactive"":true,
                    ""watermark"":true,
                    ""memoryChip"":true,
                    ""track1Front"":true,
                    ""frontImage"":true,
                    ""backImage"":true,
                    ""track1JIS"":true,
                    ""track3JIS"":true,
                    ""ddi"":true
            }";

            var assemblyName = Assembly.GetAssembly(typeof(ReadRawDataCommand))?.GetName();

            IsNotNull(assemblyName);

            var decoder = new MessageDecoder(MessageDecoder.AutoPopulateType.Command, assemblyName)
            {
                { typeof(ReadRawDataCommand) }
            };

            bool rc = decoder.TryUnserialise(AcceptCardJSON, out object result);

            IsFalse(rc);
            AreEqual(null, result);
        }
        public async Task ScanInvite()
        {
            ConnectionInvitationMessage invitation = null;
            bool isEmulated = false;  //ONLY FOR TESTING

            if (!isEmulated)
            {
                var expectedFormat = ZXing.BarcodeFormat.QR_CODE;
                var opts           = new ZXing.Mobile.MobileBarcodeScanningOptions
                {
                    PossibleFormats = new List <ZXing.BarcodeFormat> {
                        expectedFormat
                    }
                };

                var scanner = new ZXing.Mobile.MobileBarcodeScanner();

                var result = await scanner.Scan(opts);

                if (result == null)
                {
                    return;
                }

                try
                {
                    invitation = await MessageDecoder.ParseMessageAsync(result.Text) as ConnectionInvitationMessage
                                 ?? throw new Exception("Unknown message type");
                }
                catch (Exception)
                {
                    DialogService.Alert("Invalid invitation!");
                    return;
                }
            }
            else
            {
                invitation = new ConnectionInvitationMessage()
                {
                    Id            = "453b0d8e-50d0-4a18-bf44-7d7369a0c31f",
                    Label         = "Verifier",
                    Type          = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/invitation",
                    ImageUrl      = "",
                    RecipientKeys = new List <string>()
                    {
                        "DPqj1fdVajDYdVgeT36NUSoVghjkapaHpVUdwbL1z6ye"
                    },
                    RoutingKeys = new List <string>()
                    {
                        "9RUPb4jPtR2S1P9yVy85ugwiywqqzDfxRrDZnKCTQCtH"
                    },
                    ServiceEndpoint = "http://mylocalhost:5002"
                };
            }
            Device.BeginInvokeOnMainThread(async() =>
            {
                await NavigationService.NavigateToAsync <AcceptInviteViewModel>(invitation, NavigationType.Modal);
            });
        }
Ejemplo n.º 12
0
 private void DecoderInit()
 {
     if (_clientConnection.Connected)
     {
         _decoder = new MessageDecoder(_clientConnection.GetStream());
         _decoder.MessageRecieved += HandleAction;
     }
 }
Ejemplo n.º 13
0
 private void Build(byte[] buffer)
 {
     _msg = new Received(new IPEndPoint(IPAddress.Any, 90), null, new BufferSlice(buffer, 0, buffer.Length, buffer.Length));
     if (_decoder == null)
     {
         _decoder = new MessageDecoder();
         _context = new MyCtx();
     }
 }
Ejemplo n.º 14
0
            /// <summary>
            /// 读取Packet。
            /// </summary>
            private void ReadPacket()
            {
                var serializer = new PacketSerializer();
                var type       = typeof(Packet);

                while (Running)
                {
                    try
                    {
                        if (_msgQueue == null)
                        {
                            return;
                        }

                        if (_tcpClient.Available > 0)
                        {
                            var stream = _tcpClient.GetStream();
                            var packet =
                                serializer.DeserializeWithLengthPrefix(stream, null, type, PrefixStyle.Fixed32BigEndian,
                                                                       0) as Packet;
                            var msg = MessageDecoder.Decode(packet, _parent.Server);

                            if (msg != null && _msgQueue != null)
                            {
                                _msgQueue.EnqueueReadMessage(msg);
                            }
                        }
                        else
                        {
                            Thread.Sleep(DataCheckInterval);
                        }
                    }
                    catch (ObjectDisposedException e)
                    {
                        // 客户端已经被销毁了,需要断开连接。
                        if (_parent != null)
                        {
                            _parent.Close();
                        }
                    }
                    catch (IOException e)
                    {
                        // 通信发生错误,需要断开连接。
                        if (_parent != null)
                        {
                            _parent.Close();
                        }
                    }
                    catch (ThreadInterruptedException e)
                    {
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
Ejemplo n.º 15
0
        public void MessageDecoderResponseAtributeInit()
        {
            var decoder = new MessageDecoder(MessageDecoder.AutoPopulateType.Response, AssemblyName);

            var results = (from string x in decoder select x).ToArray();

            AreEqual(2, results.Length);
            AreEqual("Common.TestResponse1", results[0]);
            AreEqual("Common.TestResponse2", results[1]);
        }
Ejemplo n.º 16
0
        private async Task ScanInvite()
        {
            var expectedFormat = ZXing.BarcodeFormat.QR_CODE;

            var opts = new ZXing.Mobile.MobileBarcodeScanningOptions {
                PossibleFormats = new List <ZXing.BarcodeFormat> {
                    expectedFormat
                }
            };

            var context = await _agentContextProvider.GetContextAsync();

            var scanner = new ZXing.Mobile.MobileBarcodeScanner();

            var result = await scanner.Scan(opts);

            if (result == null)
            {
                return;
            }

            AgentMessage message = await MessageDecoder.ParseMessageAsync(result.Text);

            switch (message)
            {
            case ConnectionInvitationMessage invitation:
                break;

            case RequestPresentationMessage presentation:
                RequestPresentationMessage proofRequest = (RequestPresentationMessage)presentation;
                var         service     = message.GetDecorator <ServiceDecorator>(DecoratorNames.ServiceDecorator);
                ProofRecord proofRecord = await _proofService.ProcessRequestAsync(context, proofRequest, null);

                proofRecord.SetTag("RecipientKey", service.RecipientKeys.ToList()[0]);
                proofRecord.SetTag("ServiceEndpoint", service.ServiceEndpoint);
                await _recordService.UpdateAsync(context.Wallet, proofRecord);

                _eventAggregator.Publish(new ApplicationEvent {
                    Type = ApplicationEventType.ProofRequestUpdated
                });
                break;

            default:
                DialogService.Alert("Invalid invitation!");
                return;
            }

            Device.BeginInvokeOnMainThread(async() =>
            {
                if (message is ConnectionInvitationMessage)
                {
                    await NavigationService.NavigateToAsync <AcceptInviteViewModel>(message as ConnectionInvitationMessage, NavigationType.Modal);
                }
            });
        }
Ejemplo n.º 17
0
        public void UnserialiseStringToObject()
        {
            var ReadCardJSON = @"{
                ""headers"":{
                    ""name"":""CardReader.ReadRawData"",
                    ""requestId"":""b34800d0-9dd2-4d50-89ea-92d1b13df54b"",
                    ""type"":""command""
                },
                ""payload"":{
                    ""timeout"":5000,
                    ""track1"":true,
                    ""track2"": true,
                    ""track3"":true,
                    ""chip"":true,
                    ""security"":true,
                    ""fluxInactive"":true,
                    ""watermark"":true,
                    ""memoryChip"":true,
                    ""track1Front"":true,
                    ""frontImage"":true,
                    ""backImage"":true,
                    ""track1JIS"":true,
                    ""track3JIS"":true,
                    ""ddi"":true
                 }
            }";

            var assemblyName = Assembly.GetAssembly(typeof(ReadRawDataCommand))?.GetName();

            IsNotNull(assemblyName);

            var decoder = new MessageDecoder(MessageDecoder.AutoPopulateType.Command, assemblyName)
            {
                { typeof(ReadRawDataCommand) }
            };

            bool rc = decoder.TryUnserialise(ReadCardJSON, out object resultMessage);

            IsTrue(rc);
            IsNotNull(resultMessage);

            Command <ReadRawDataCommand.PayloadData> result = resultMessage as Command <ReadRawDataCommand.PayloadData> ?? throw new Exception();

            IsNotNull(result);

            IsInstanceOfType(result, typeof(ReadRawDataCommand));
            ReadRawDataCommand readCardCommand = result as ReadRawDataCommand;

            IsNotNull(readCardCommand);
            IsNotNull(readCardCommand.Payload);
            ReadRawDataCommand.PayloadData readCardPayload = readCardCommand.Payload as ReadRawDataCommand.PayloadData;
            IsNotNull(readCardPayload);
            AreEqual(true, readCardPayload.Track1);
        }
Ejemplo n.º 18
0
        public void CanSetAuthInfo()
        {
            var message = new MessageBuilder()
                          .PutAuthInfo("220159")
                          .PutOperationCode("24")
                          .PutPayload("Hello there")
                          .Build();

            var decoded = MessageDecoder.Decode(message.Skip(sizeof(int)).ToArray());

            Assert.AreEqual("220159", decoded.Auth);
        }
Ejemplo n.º 19
0
        public void CanMarkAsResponse()
        {
            var message = new MessageBuilder()
                          .MarkAsResponse()
                          .PutOperationCode("33")
                          .PutPayload("Hello there")
                          .Build();

            var decoded = MessageDecoder.Decode(message.Skip(sizeof(int)).ToArray());

            Assert.IsTrue(decoded.IsResponse);
        }
Ejemplo n.º 20
0
 public ClientHandler(BinaryTcpClient client,
                      string logsSourcePath, string logsDestPath,
                      ILogger logger)
 {
     this.client         = client;
     this.logsSourcePath = logsSourcePath;
     this.logsDestPath   = logsDestPath;
     this.logger         = logger;
     requestHandler      = new ClientRequestHandler(
         client, logsSourcePath, logsDestPath, this.logger);
     decoder = new MessageDecoder();
     categorizationStrategy = GetCategorizationStrategy();
 }
Ejemplo n.º 21
0
        private async Task <string> GetHeaderField(string uid, string field)
        {
            string response = await imap.ReceiveResponse($"$ UID FETCH {uid} BODY[HEADER.FIELDS ({field})]");

            int index = response.IndexOf("$ OK");

            if (index == -1)
            {
                throw new Exception($"error while Get{field}");
            }
            Regex regex = new Regex($@"(?<=\r\n{field}: )([\s\S]*?)(?=\r\n\r\n\))");


            return(MessageDecoder.DecodeEncodedLine(regex.Match(response).Value));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Starts waiting for message, returns void when client disconnects or connection has to be closed
        /// </summary>
        /// <param name="clientData"></param>
        private void WaitForMessage(Client clientData)
        {
            bool open = true;

            while (open)
            {
                // Close connection if the client disconnected
                if (!clientData.client.Connected)
                {
                    return;
                }

                // Wait untill message data is available
                while (!clientData.client.GetStream().DataAvailable)
                {
                    // Check if client is still connected
                    if (clientData.client.Client.Poll(1000, SelectMode.SelectRead))
                    {
                        // Remove the client and end WaitForMessage
                        RemoveClient(clientData.id);
                        clientData.ExecDisconnectCallback();
                        return;
                    }

                    // Put thread in low priority pool if no data is available
                    Thread.Sleep(1);
                }

                ReceivedMessage incomingMessage = MessageDecoder.DecodeMessage(ReadStream(clientData));

                if (incomingMessage.close)
                {
                    RemoveClient(clientData.id);
                    break;
                }

                clientData.ExecMessageCallback(incomingMessage.content);

                // byte[] resp = Message.GenerateMessage("                     Hello World                     Hello World                          Hello World                     Hello World                   a");
                // byte[] resp = Message.GenerateMessage("yes my dude");

                // stream.Write(resp, 0, resp.Length);

                // This is just here for testing connection closing
                // messageAmount++;
                // open = messageAmount < 50;
            }
        }
Ejemplo n.º 23
0
        public void BuildsStringMessageCorrectly()
        {
            var payload = "Hello there!";

            var message = new MessageBuilder()
                          .PutOperationCode("12")
                          .PutPayload(payload)
                          .Build();

            var decoded = MessageDecoder.Decode(message.Skip(sizeof(int)).ToArray());

            Assert.IsFalse(decoded.IsResponse);
            Assert.AreEqual("------", decoded.Auth);
            Assert.AreEqual("12", decoded.Code);
            Assert.AreEqual(payload, MessageDecoder.DecodePayload(decoded.Payload));
        }
Ejemplo n.º 24
0
        public async Task ScanInvite()
        {
            if (Result == null)
            {
                return;
            }

            try
            {
                var msg = await MessageDecoder.ParseMessageAsync(Result.Text) ?? throw new Exception("Unknown message type");

                if (msg.Type == MessageTypes.ConnectionInvitation)
                {
                    var invitation = msg as ConnectionInvitationMessage;
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        await NavigationService.NavigateToAsync <AcceptInviteViewModel>(invitation, NavigationType.Modal);
                    });
                }
                else if (msg.Type == MessageTypes.PresentProofNames.RequestPresentation)
                {
                    var requestMessage = msg as RequestPresentationMessage;

                    var request = requestMessage.Requests?.FirstOrDefault((Attachment x) => x.Id == "libindy-request-presentation-0");
                    if (request == null)
                    {
                        DialogService.Alert("scanned qr code does not look like a proof request", "Error");
                        return;
                    }
                    var proofRequest = request.Data.Base64.GetBytesFromBase64().GetUTF8String().ToObject <ProofRequest>();
                    if (proofRequest == null)
                    {
                        return;
                    }

                    var proofRequestViewModel = _scope.Resolve <ProofRequestViewModel>(new NamedParameter("proofRequest", proofRequest),
                                                                                       new NamedParameter("requestPresentationMessage", requestMessage));

                    await NavigationService.NavigateToAsync(proofRequestViewModel);
                }
            }
            catch (Exception)
            {
                DialogService.Alert("Invalid invitation!");
                return;
            }
        }
Ejemplo n.º 25
0
        public void UnserialiseStringToObjectNotJSON()
        {
            var AcceptCardJSON = @"Not JSON";
            var assemblyName   = Assembly.GetAssembly(typeof(ReadRawDataCommand))?.GetName();

            IsNotNull(assemblyName);

            var decoder = new MessageDecoder(MessageDecoder.AutoPopulateType.Command, assemblyName)
            {
                { typeof(ReadRawDataCommand) }
            };

            bool rc = decoder.TryUnserialise(AcceptCardJSON, out object result);

            IsFalse(rc);
            AreEqual(null, result);
        }
        public void MeasureTimeToDecodeQuery()
        {
            string[]     messages     = GetMessagesFromFile(MessageDecoder.QUERY_FILENAME);
            int          count        = messages.Length;
            QueryMessage queryMessage = new QueryMessage();

            Measure.Method(() =>
            {
                for (var i = 0; i < count; i++)
                {
                    MessageDecoder.DecodeQueryMessage("raycast", messages[i], ref queryMessage);
                }
            })
            .SetUp(() => SetupTests())
            .WarmupCount(3)
            .MeasurementCount(10)
            .IterationsPerMeasurement(10)
            .GC()
            .Run();
        }
        public void MeasureTimeToDecodeTransform()
        {
            string[] messages = GetMessagesFromFile(MessageDecoder.TRANSFORM_FILENAME);
            int      count    = messages.Length;

            DCL.Components.DCLTransform.Model transformModel = new DCL.Components.DCLTransform.Model();

            Measure.Method(() =>
            {
                for (var i = 0; i < count; i++)
                {
                    MessageDecoder.DecodeTransform(messages[i], ref transformModel);
                }
            })
            .SetUp(() => SetupTests())
            .WarmupCount(3)
            .MeasurementCount(10)
            .IterationsPerMeasurement(10)
            .GC()
            .Run();
        }
Ejemplo n.º 28
0
        private static string DecodeBody(string body, string encoding, string charset)
        {
            switch (encoding)
            {
            case "quoted-printable":
                return(MessageDecoder.DecodeQP(body, "utf-8"));

            case "base64":
                try
                {
                    var bytes = Convert.FromBase64String(body);
                    return(Encoding.GetEncoding(charset).GetString(bytes));
                }
                catch
                {
                    return(body);
                }

            default:
                return(body);
            }
        }
Ejemplo n.º 29
0
        public void BuildsObjectMessageCorrectly()
        {
            var user = new User()
            {
                Id   = 3,
                Name = "El hijo de Piri"
            };

            var message = new MessageBuilder()
                          .PutOperationCode("14")
                          .PutPayload(user)
                          .Build();

            var decoded = MessageDecoder.Decode(message.Skip(sizeof(int)).ToArray());
            var payload = MessageDecoder.DecodePayload <User>(decoded.Payload);

            Assert.IsFalse(decoded.IsResponse);
            Assert.AreEqual("------", decoded.Auth);
            Assert.AreEqual("14", decoded.Code);
            Assert.AreEqual(user.Id, payload.Id);
            Assert.AreEqual(user.Name, payload.Name);
        }
        public void MeasureTimeToDecodeMessages()
        {
            string[]            messages = GetMessagesFromFile(MessageDecoder.MESSAGES_FILENAME);
            int                 count    = messages.Length;
            string              sceneId;
            string              tag;
            string              message;
            PB_SendSceneMessage sendSceneMessage;

            Measure.Method(() =>
            {
                for (var i = 0; i < count; i++)
                {
                    MessageDecoder.DecodePayloadChunk(messages[i], out sceneId, out message, out tag, out sendSceneMessage);
                }
            })
            .SetUp(() => SetupTests())
            .WarmupCount(3)
            .MeasurementCount(10)
            .IterationsPerMeasurement(10)
            .GC()
            .Run();
        }