/// <summary>
        /// Encodes a byte array to a Socket.IO binary encoded message
        /// </summary>
        private byte[] EncodeData(byte[] data, PayloadTypes type, byte[] afterHeaderData)
        {
            // Packet binary encoding:
            // [          0|1         ][            length of data           ][    FF    ][data]
            // <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number 255><data>

            // Get the length of the payload. Socket.IO uses a wasteful encoding to send the length of the data.
            // If the data is 16 bytes we have to send the length as two bytes: byte value of the character '1' and byte value of the character '6'.
            // Instead of just one byte: 0xF. If the payload is 123 bytes, we can't send as 0x7B...
            int    afterHeaderLength = (afterHeaderData != null ? afterHeaderData.Length : 0);
            string lenStr            = (data.Length + afterHeaderLength).ToString();

            byte[] len = new byte[lenStr.Length];
            for (int cv = 0; cv < lenStr.Length; ++cv)
            {
                len[cv] = (byte)char.GetNumericValue(lenStr[cv]);
            }

            // We need another buffer to store the final data
            byte[] buffer = new byte[data.Length + len.Length + 2 + afterHeaderLength];

            // The payload is textual -> 0
            buffer[0] = (byte)type;

            // Copy the length of the data
            for (int cv = 0; cv < len.Length; ++cv)
            {
                buffer[1 + cv] = len[cv];
            }

            int idx = 1 + len.Length;

            // End of the header data
            buffer[idx++] = 0xFF;

            if (afterHeaderData != null && afterHeaderData.Length > 0)
            {
                Array.Copy(afterHeaderData, 0, buffer, idx, afterHeaderData.Length);
                idx += afterHeaderData.Length;
            }

            // Copy our payload data to the buffer
            Array.Copy(data, 0, buffer, idx, data.Length);

            return(buffer);
        }
        public void GivenValidInputs_WhenContructAcceptHeaderDescriptor_ShouldSucceed()
        {
            PayloadTypes  payloadType = PayloadTypes.MultipartRelated;
            string        mediaType   = KnownContentTypes.ApplicationDicom;
            bool          isTransferSyntaxMandatory  = false;
            string        transferSyntaxWhenMissing  = DicomTransferSyntaxUids.ExplicitVRLittleEndian;
            ISet <string> acceptableTransferSyntaxes = new HashSet <string>()
            {
                transferSyntaxWhenMissing
            };
            AcceptHeaderDescriptor descriptor = new AcceptHeaderDescriptor(payloadType, mediaType, isTransferSyntaxMandatory, transferSyntaxWhenMissing, acceptableTransferSyntaxes);

            Assert.Equal(payloadType, descriptor.PayloadType);
            Assert.Equal(mediaType, descriptor.MediaType);
            Assert.Equal(isTransferSyntaxMandatory, descriptor.IsTransferSyntaxMandatory);
            Assert.Equal(transferSyntaxWhenMissing, descriptor.TransferSyntaxWhenMissing);
            Assert.Equal(acceptableTransferSyntaxes, descriptor.AcceptableTransferSyntaxes);
        }
        public AcceptHeaderDescriptor(PayloadTypes payloadType, string mediaType, bool isTransferSyntaxMandatory, string transferSyntaxWhenMissing, ISet <string> acceptableTransferSyntaxes)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(mediaType, nameof(mediaType));

            // When transfersyntax is not mandatory, transferSyntaxWhenMissing has to be presented
            if (!isTransferSyntaxMandatory)
            {
                EnsureArg.IsNotEmptyOrWhiteSpace(transferSyntaxWhenMissing, nameof(transferSyntaxWhenMissing));
            }

            EnsureArg.IsNotNull(acceptableTransferSyntaxes, nameof(acceptableTransferSyntaxes));

            PayloadType = payloadType;
            MediaType   = mediaType;
            IsTransferSyntaxMandatory  = isTransferSyntaxMandatory;
            TransferSyntaxWhenMissing  = transferSyntaxWhenMissing;
            AcceptableTransferSyntaxes = acceptableTransferSyntaxes;
        }
Beispiel #4
0
 /// <summary>
 /// Parameterized constructor
 /// </summary>
 public payload_type(PayloadTypes type) : base(TlvTag)
 {
     this.Value = type;
 }
        private (AcceptHeader, AcceptHeaderDescriptor) CreateAcceptHeaderAndDescriptorForPayloadType(PayloadTypes descriptorPayloadType, PayloadTypes acceptHeaderPayloadType)
        {
            AcceptHeader           acceptHeader = AcceptHeaderHelpers.CreateAcceptHeader(payloadType: acceptHeaderPayloadType);
            AcceptHeaderDescriptor descriptor   = new AcceptHeaderDescriptor(
                payloadType: descriptorPayloadType,
                mediaType: acceptHeader.MediaType.Value,
                isTransferSyntaxMandatory: true,
                transferSyntaxWhenMissing: string.Empty,
                acceptableTransferSyntaxes: new HashSet <string>()
            {
                acceptHeader.TransferSyntax.Value
            });

            return(acceptHeader, descriptor);
        }
Beispiel #6
0
        /// <summary>
        /// Will parse the response, and send out the parsed packets.
        /// </summary>
        private void ParseResponse(HTTPResponse resp)
        {
            try
            {
                if (resp != null && resp.Data != null && resp.Data.Length >= 1)
                {
                    int idx = 0;

                    while (idx < resp.Data.Length)
                    {
                        PayloadTypes type   = PayloadTypes.Text;
                        int          length = 0;

                        if (resp.Data[idx] < '0')
                        {
                            type = (PayloadTypes)resp.Data[idx++];

                            byte num = resp.Data[idx++];
                            while (num != 0xFF)
                            {
                                length = (length * 10) + num;
                                num    = resp.Data[idx++];
                            }
                        }
                        else
                        {
                            byte next = resp.Data[idx++];
                            while (next != ':')
                            {
                                length = (length * 10) + (next - '0');
                                next   = resp.Data[idx++];
                            }

                            // Because length can be different from the byte length, we have to do a little post-processing to support unicode characters.

                            int brackets = 0;
                            int tmpIdx   = idx;
                            while (tmpIdx < idx + length)
                            {
                                if (resp.Data[tmpIdx] == '[')
                                {
                                    brackets++;
                                }
                                else if (resp.Data[tmpIdx] == ']')
                                {
                                    brackets--;
                                }

                                tmpIdx++;
                            }

                            if (brackets > 0)
                            {
                                while (brackets > 0)
                                {
                                    if (resp.Data[tmpIdx] == '[')
                                    {
                                        brackets++;
                                    }
                                    else if (resp.Data[tmpIdx] == ']')
                                    {
                                        brackets--;
                                    }
                                    tmpIdx++;
                                }

                                length = tmpIdx - idx;
                            }
                        }

                        Packet packet = null;
                        switch (type)
                        {
                        case PayloadTypes.Text:
                            packet = new Packet(Encoding.UTF8.GetString(resp.Data, idx, length));
                            break;

                        case PayloadTypes.Binary:
                            if (PacketWithAttachment != null)
                            {
                                // First byte is the packet type. We can skip it, so we advance our idx and we also have
                                // to decrease length
                                idx++;
                                length--;

                                byte[] buffer = new byte[length];
                                Array.Copy(resp.Data, idx, buffer, 0, length);

                                PacketWithAttachment.AddAttachmentFromServer(buffer, true);

                                if (PacketWithAttachment.HasAllAttachment)
                                {
                                    packet = PacketWithAttachment;
                                    PacketWithAttachment = null;
                                }
                            }
                            break;
                        } // switch

                        if (packet != null)
                        {
                            try
                            {
                                OnPacket(packet);
                            }
                            catch (Exception ex)
                            {
                                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket", ex);
                                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
                            }
                        }

                        idx += length;
                    }// while
                }
            }
            catch (Exception ex)
            {
                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);

                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse", ex);
            }
        }
        static ZoneServerMetadataMarker()
        {
            PayloadTypes = typeof(ClientSessionClaimRequestPayload)
                           .Assembly
                           .GetExportedTypes()
                           .Where(t => typeof(GameClientPacketPayload).IsAssignableFrom(t) || typeof(GameServerPacketPayload).IsAssignableFrom(t))
                           .Distinct()
                           .ToArray();

            _ServerPayloadTypesByOpcode = new Lazy <IReadOnlyDictionary <GamePayloadOperationCode, Type> >(() => PayloadTypes
                                                                                                           .Where(t => typeof(GameServerPacketPayload).IsAssignableFrom(t))
                                                                                                           .ToDictionary(type => type.GetCustomAttribute <GamePayloadAttribute>().OperationCode), true);

            _ClientPayloadTypesByOpcode = new Lazy <IReadOnlyDictionary <GamePayloadOperationCode, Type> >(() => PayloadTypes
                                                                                                           .Where(t => typeof(GameClientPacketPayload).IsAssignableFrom(t))
                                                                                                           .ToDictionary(type => type.GetCustomAttribute <GamePayloadAttribute>().OperationCode), true);

            AllProtobufModels = typeof(ClientSessionClaimRequestPayload)
                                .Assembly
                                .GetTypes()
                                .Where(t => t.GetCustomAttribute <ProtoContractAttribute>() != null)
                                .Concat(new Type[] { typeof(GameClientPacketPayload), typeof(GameServerPacketPayload) })
                                .Distinct()
                                .ToArray();
        }
        /// <summary>
        /// Will parse the response, and send out the parsed packets.
        /// </summary>
        private void ParseResponse(HTTPResponse resp)
        {
            try
            {
                if (resp != null && resp.Data != null && resp.Data.Length >= 1)
                {
// 1.x
//00000000  00 09 07 ff 30 7b 22 73 69 64 22 3a 22 6f 69 48       0{"sid":"oiH
//00000010  34 31 33 73 61 49 4e 52 53 67 37 41 4b 41 41 41   413saINRSg7AKAAA
//00000020  41 22 2c 22 75 70 67 72 61 64 65 73 22 3a 5b 22   A","upgrades":["
//00000030  77 65 62 73 6f 63 6b 65 74 22 5d 2c 22 70 69 6e   websocket"],"pin
//00000040  67 49 6e 74 65 72 76 61 6c 22 3a 32 35 30 30 30   gInterval":25000
//00000050  2c 22 70 69 6e 67 54 69 6d 65 6f 75 74 22 3a 36   ,"pingTimeout":6
//00000060  30 30 30 30 7d                                    0000}

// 2.x
//00000000  39 37 3a 30 7b 22 73 69 64 22 3a 22 73 36 62 5a   97:0{"sid":"s6bZ
//00000010  6c 43 37 66 51 59 6b 4f 46 4f 62 35 41 41 41 41   lC7fQYkOFOb5AAAA
//00000020  22 2c 22 75 70 67 72 61 64 65 73 22 3a 5b 22 77   ","upgrades":["w
//00000030  65 62 73 6f 63 6b 65 74 22 5d 2c 22 70 69 6e 67   ebsocket"],"ping
//00000040  49 6e 74 65 72 76 61 6c 22 3a 32 35 30 30 30 2c   Interval":25000,
//00000050  22 70 69 6e 67 54 69 6d 65 6f 75 74 22 3a 36 30   "pingTimeout":60
//00000060  30 30 30 7d 32 3a 34 30                           000}2:40

                    int idx = 0;

                    while (idx < resp.Data.Length)
                    {
                        PayloadTypes type   = PayloadTypes.Text;
                        int          length = 0;

                        if (resp.Data[idx] < '0')
                        {
                            type = (PayloadTypes)resp.Data[idx++];

                            byte num = resp.Data[idx++];
                            while (num != 0xFF)
                            {
                                length = (length * 10) + num;
                                num    = resp.Data[idx++];
                            }
                        }
                        else
                        {
                            byte next = resp.Data[idx++];
                            while (next != ':')
                            {
                                length = (length * 10) + (next - '0');
                                next   = resp.Data[idx++];
                            }
                        }

                        Packet packet = null;
                        switch (type)
                        {
                        case PayloadTypes.Text:
                            packet = new Packet(Encoding.UTF8.GetString(resp.Data, idx, length));
                            break;

                        case PayloadTypes.Binary:
                            if (PacketWithAttachment != null)
                            {
                                // First byte is the packet type. We can skip it, so we advance our idx and we also have
                                // to decrease length
                                idx++;
                                length--;

                                byte[] buffer = new byte[length];
                                Array.Copy(resp.Data, idx, buffer, 0, length);

                                PacketWithAttachment.AddAttachmentFromServer(buffer, true);

                                if (PacketWithAttachment.HasAllAttachment)
                                {
                                    packet = PacketWithAttachment;
                                    PacketWithAttachment = null;
                                }
                            }
                            break;
                        } // switch

                        if (packet != null)
                        {
                            try
                            {
                                OnPacket(packet);
                            }
                            catch (Exception ex)
                            {
                                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket", ex);
                                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
                            }
                        }

                        idx += length;
                    }// while
                }
            }
            catch (Exception ex)
            {
                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);

                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse", ex);
            }
        }
        public async Task GivenStoredInstances_WhenRetrieveRequestForInstance_ThenInstanceIsRetrievedSuccessfully(PayloadTypes payloadTypes)
        {
            // Add multiple instances to validate that we return the requested instance and ignore the other(s).
            List <VersionedInstanceIdentifier> versionedInstanceIdentifiers = SetupInstanceIdentifiersList(ResourceType.Instance);

            // For the first instance identifier, set up the fileStore to return a stream containing a file associated with the identifier.
            KeyValuePair <DicomFile, Stream> streamAndStoredFile = StreamAndStoredFileFromDataset(GenerateDatasetsFromIdentifiers(versionedInstanceIdentifiers.First())).Result;

            _fileStore.GetFileAsync(streamAndStoredFile.Key.Dataset.ToVersionedInstanceIdentifier(0), DefaultCancellationToken).Returns(streamAndStoredFile.Value);

            RetrieveResourceResponse response = await _retrieveResourceService.GetInstanceResourceAsync(
                new RetrieveResourceRequest(
                    _studyInstanceUid,
                    _firstSeriesInstanceUid,
                    _sopInstanceUid,
                    new[] { AcceptHeaderHelpers.CreateAcceptHeaderForGetInstance(payloadTypes: payloadTypes) }),
                DefaultCancellationToken);

            // Validate response status code and ensure response stream has expected file - it should be equivalent to what the store was set up to return.
            ValidateResponseStreams(new List <DicomFile>()
            {
                streamAndStoredFile.Key
            }, response.ResponseStreams);

            // Validate content type
            Assert.Equal(KnownContentTypes.ApplicationDicom, response.ContentType);

            // Dispose created streams.
            streamAndStoredFile.Value.Dispose();
        }
Beispiel #10
0
        IFluentLogObject IFluentLogObject.WithExtraPayload(IPayload payload)
        {
            if (payload == null)
                throw new ArgumentNullException("payload");

            PayloadTypes pldt;

            try
            {
                pldt = payload.GetType().GetPayloadType();
            }
            catch (ArgumentException x)
            {
                throw new ArgumentException("Given payload is of unkown type.", x);
            }

            if ((this.PayloadTypes & pldt) == 0)
                this.PayloadTypes |= pldt;
            else
                throw new InvalidOperationException("The object already contains a payload of the same type." + Environment.NewLine + "Duplicated type: " + pldt);

            this.payloads.Add(payload);

            return this;
        }
Beispiel #11
0
        private async Task ReceivePacketsAsync()
        {
            bool isClosed = false;
            int  length;
            DisconnectedEventArgs disconnectArgs = null;

            while (_receiver != null && _receiver.IsConnected && !isClosed)
            {
                // receive a single packet
                try
                {
                    // read the header
                    int headerOffset = 0;
                    while (headerOffset < TransportConstants.MaxHeaderLength)
                    {
                        length = await _receiver.ReceiveAsync(_receiveHeaderBuffer, headerOffset, TransportConstants.MaxHeaderLength - headerOffset).ConfigureAwait(false);

                        if (length == 0)
                        {
                            throw new TransportDisconnectedException("Stream closed while reading header bytes");
                        }

                        headerOffset += length;
                    }

                    // deserialize the bytes into a header
                    var header = HeaderSerializer.Deserialize(_receiveHeaderBuffer, 0, TransportConstants.MaxHeaderLength);

                    // read the payload
                    var contentStream = _getStream(header);

                    var buffer = PayloadTypes.IsStream(header) ?
                                 new byte[header.PayloadLength] :
                                 _receiveContentBuffer;

                    int offset = 0;

                    if (header.PayloadLength > 0)
                    {
                        do
                        {
                            // read in chunks
                            int count = Math.Min(header.PayloadLength - offset, TransportConstants.MaxPayloadLength);

                            // read the content
                            length = await _receiver.ReceiveAsync(buffer, offset, count).ConfigureAwait(false);

                            if (length == 0)
                            {
                                throw new TransportDisconnectedException("Stream closed while reading payload bytes");
                            }

                            if (contentStream != null)
                            {
                                // write chunks to the contentStream if it's not a stream type
                                if (!PayloadTypes.IsStream(header))
                                {
                                    await contentStream.WriteAsync(buffer, offset, length).ConfigureAwait(false);
                                }
                            }

                            offset += length;
                        }while (offset < header.PayloadLength);

                        // give the full payload buffer to the contentStream if it's a stream
                        if (contentStream != null && PayloadTypes.IsStream(header))
                        {
                            ((PayloadStream)contentStream).GiveBuffer(buffer, length);
                        }
                    }

                    _receiveAction(header, contentStream, offset);
                }
                catch (TransportDisconnectedException de)
                {
                    isClosed       = true;
                    disconnectArgs = new DisconnectedEventArgs()
                    {
                        Reason = de.Reason,
                    };
                }
                catch (Exception e)
                {
                    isClosed       = true;
                    disconnectArgs = new DisconnectedEventArgs()
                    {
                        Reason = e.Message,
                    };
                }
            }

            Disconnect(disconnectArgs);
        }
        public void GivenPayloadType_WhenCheckIsAcceptable_ShouldSucceed(PayloadTypes descriptorPayloadType, PayloadTypes acceptHeaderPayloadType, bool isAcceptable)
        {
            (AcceptHeader, AcceptHeaderDescriptor)testData = CreateAcceptHeaderAndDescriptorForPayloadType(descriptorPayloadType, acceptHeaderPayloadType);
            string                 transferSyntax;
            AcceptHeader           acceptHeader = testData.Item1;
            AcceptHeaderDescriptor descriptor   = testData.Item2;

            Assert.Equal(isAcceptable, descriptor.IsAcceptable(acceptHeader, out transferSyntax));
        }
Beispiel #13
0
        /// <summary>
        /// Will parse the response, and send out the parsed packets.
        /// </summary>
        private void ParseResponse(HTTPResponse resp)
        {
            try
            {
                if (resp != null && resp.Data != null && resp.Data.Length >= 1)
                {
                    int idx = 0;

                    while (idx < resp.Data.Length)
                    {
                        PayloadTypes type   = (PayloadTypes)resp.Data[idx++];
                        int          length = 0;

                        byte num = resp.Data[idx++];
                        while (num != 0xFF)
                        {
                            length = (length * 10) + num;
                            num    = resp.Data[idx++];
                        }

                        Packet packet = null;
                        switch (type)
                        {
                        case PayloadTypes.Text:
                            packet = new Packet(Encoding.UTF8.GetString(resp.Data, idx, length));
                            break;

                        case PayloadTypes.Binary:
                            if (PacketWithAttachment != null)
                            {
                                // First byte is the packet type. We can skip it, so we advance our idx and we also have
                                // to decrease length
                                idx++;
                                length--;

                                byte[] buffer = new byte[length];
                                Array.Copy(resp.Data, idx, buffer, 0, length);

                                PacketWithAttachment.AddAttachmentFromServer(buffer, true);

                                if (PacketWithAttachment.HasAllAttachment)
                                {
                                    packet = PacketWithAttachment;
                                    PacketWithAttachment = null;
                                }
                            }
                            break;
                        } // switch

                        if (packet != null)
                        {
                            try
                            {
                                OnPacket(packet);
                            }
                            catch (Exception ex)
                            {
                                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket", ex);
                                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
                            }
                        }

                        idx += length;
                    }// while
                }
            }
            catch (Exception ex)
            {
                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);

                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse", ex);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Will parse the response, and send out the parsed packets.
        /// </summary>
        private void ParseResponse(HTTPResponse resp)
        {
            try
            {
                if (resp != null && resp.Data != null && resp.Data.Length >= 1)
                {
// 1.x
//00000000  00 09 07 ff 30 7b 22 73 69 64 22 3a 22 6f 69 48       0{"sid":"oiH
//00000010  34 31 33 73 61 49 4e 52 53 67 37 41 4b 41 41 41   413saINRSg7AKAAA
//00000020  41 22 2c 22 75 70 67 72 61 64 65 73 22 3a 5b 22   A","upgrades":["
//00000030  77 65 62 73 6f 63 6b 65 74 22 5d 2c 22 70 69 6e   websocket"],"pin
//00000040  67 49 6e 74 65 72 76 61 6c 22 3a 32 35 30 30 30   gInterval":25000
//00000050  2c 22 70 69 6e 67 54 69 6d 65 6f 75 74 22 3a 36   ,"pingTimeout":6
//00000060  30 30 30 30 7d                                    0000}

// 2.x
//00000000  39 37 3a 30 7b 22 73 69 64 22 3a 22 73 36 62 5a   97:0{"sid":"s6bZ
//00000010  6c 43 37 66 51 59 6b 4f 46 4f 62 35 41 41 41 41   lC7fQYkOFOb5AAAA
//00000020  22 2c 22 75 70 67 72 61 64 65 73 22 3a 5b 22 77   ","upgrades":["w
//00000030  65 62 73 6f 63 6b 65 74 22 5d 2c 22 70 69 6e 67   ebsocket"],"ping
//00000040  49 6e 74 65 72 76 61 6c 22 3a 32 35 30 30 30 2c   Interval":25000,
//00000050  22 70 69 6e 67 54 69 6d 65 6f 75 74 22 3a 36 30   "pingTimeout":60
//00000060  30 30 30 7d 32 3a 34 30                           000}2:40

//00000000  38 30 3a 34 32 5b 22 50 6f 6c 6c 69 6e 67 20 69   80:42["Polling i
//00000010  73 20 77 6f 72 6b 69 6e 67 20 6e 6f 72 6d 61 6c   s working normal
//00000020  6c 79 20 62 75 74 20 63 72 61 73 68 65 73 20 6f   ly but crashes o
//00000030  6e 20 72 65 63 65 69 76 69 6e 67 20 6d 75 74 61   n receiving muta
//00000040  74 65 64 20 76 6f 77 65 6c 73 20 c3 bc 20 c3 b6   ted vowels
//00000050  20 c3 a4 2e 22 5d                                    ."]



                    int idx = 0;

                    while (idx < resp.Data.Length)
                    {
                        PayloadTypes type   = PayloadTypes.Text;
                        int          length = 0;

                        if (resp.Data[idx] < '0')
                        {
                            type = (PayloadTypes)resp.Data[idx++];

                            byte num = resp.Data[idx++];
                            while (num != 0xFF)
                            {
                                length = (length * 10) + num;
                                num    = resp.Data[idx++];
                            }
                        }
                        else
                        {
                            byte next = resp.Data[idx++];
                            while (next != ':')
                            {
                                length = (length * 10) + (next - '0');
                                next   = resp.Data[idx++];
                            }
                        }

                        Packet packet = null;
                        switch (type)
                        {
                        case PayloadTypes.Text:
                            // While we already received a length for the packet, it contains the character count of the packet not the byte count.
                            // So, when the packet contains UTF8 characters, length will contain less than the actual byte count.
                            // To fix this, we have to find the last square or curly bracket and if the sent and calculated lengths are different
                            //  we will use the larger one.
                            int  customLength = 1;
                            byte next         = resp.Data[idx];
                            while (next != SquareBrackets[0] && next != CurlyBrackets[0] && idx + customLength < resp.Data.Length)
                            {
                                next = resp.Data[idx + customLength++];
                            }

                            if (idx + customLength < resp.Data.Length)
                            {
                                byte[] brackets = SquareBrackets;
                                if (next == CurlyBrackets[0])
                                {
                                    brackets = CurlyBrackets;
                                }

                                int bracketCount = 1;
                                while (bracketCount != 0 && idx + customLength < resp.Data.Length)
                                {
                                    next = resp.Data[idx + customLength++];
                                    if (next == brackets[0])
                                    {
                                        bracketCount++;
                                    }
                                    else if (next == brackets[1])
                                    {
                                        bracketCount--;
                                    }
                                }
                            }

                            packet = new Packet(Encoding.UTF8.GetString(resp.Data, idx, Math.Max(length, customLength)));
                            break;

                        case PayloadTypes.Binary:
                            if (PacketWithAttachment != null)
                            {
                                // First byte is the packet type. We can skip it, so we advance our idx and we also have
                                // to decrease length
                                idx++;
                                length--;

                                byte[] buffer = new byte[length];
                                Array.Copy(resp.Data, idx, buffer, 0, length);

                                PacketWithAttachment.AddAttachmentFromServer(buffer, true);

                                if (PacketWithAttachment.HasAllAttachment)
                                {
                                    packet = PacketWithAttachment;
                                    PacketWithAttachment = null;
                                }
                            }
                            break;
                        } // switch

                        if (packet != null)
                        {
                            try
                            {
                                OnPacket(packet);
                            }
                            catch (Exception ex)
                            {
                                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket", ex);
                                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);
                            }
                        }

                        idx += length;
                    }// while
                }
            }
            catch (Exception ex)
            {
                (Manager as IManager).EmitError(SocketIOErrors.Internal, ex.Message + " " + ex.StackTrace);

                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse", ex);
            }
        }
        /// <summary>
        /// Encodes a byte array to a Socket.IO binary encoded message
        /// </summary>
        private byte[] EncodeData(byte[] data, PayloadTypes type, byte[] afterHeaderData)
        {
            // Packet binary encoding:
            // [          0|1         ][            length of data           ][    FF    ][data]
            // <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number 255><data>

            // Get the length of the payload. Socket.IO uses a wasteful encoding to send the length of the data.
            // If the data is 16 bytes we have to send the length as two bytes: byte value of the character '1' and byte value of the character '6'.
            // Instead of just one byte: 0xF. If the payload is 123 bytes, we can't send as 0x7B...
            int afterHeaderLength = (afterHeaderData != null ? afterHeaderData.Length : 0);
            string lenStr = (data.Length + afterHeaderLength).ToString();
            byte[] len = new byte[lenStr.Length];
            for (int cv = 0; cv < lenStr.Length; ++cv)
                len[cv] = (byte)char.GetNumericValue(lenStr[cv]);

            // We need another buffer to store the final data
            byte[] buffer = new byte[data.Length + len.Length + 2 + afterHeaderLength];

            // The payload is textual -> 0
            buffer[0] = (byte)type;

            // Copy the length of the data
            for (int cv = 0; cv < len.Length; ++cv)
                buffer[1 + cv] = len[cv];

            int idx = 1 + len.Length;

            // End of the header data
            buffer[idx++] = 0xFF;

            if (afterHeaderData != null && afterHeaderData.Length > 0)
            {
                Array.Copy(afterHeaderData, 0, buffer, idx, afterHeaderData.Length);
                idx += afterHeaderData.Length;
            }

            // Copy our payload data to the buffer
            Array.Copy(data, 0, buffer, idx, data.Length);

            return buffer;
        }
Beispiel #16
0
        /// <summary>
        /// Initializes the object with the given property values.
        /// </summary>
        /// <param name="manager">The manager which owns the object; must be non-null.</param>
        /// <param name="timestamp">The creation timestamp.</param>
        /// <param name="flags">Flags for logging the object.</param>
        /// <param name="priority">Relative priority of the object.</param>
        /// <param name="indent">Logical indentation of the object.</param>
        /// <param name="sources">An enumeration of sources of the object.</param>
        /// <param name="payloads">An enumeration of payloads of the object.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when the given manager object is null.</exception>
        /// <exception cref="System.ArgumentException">Thrown when an enumerated source is null -or- an enumerated payload is null -or- a given payload is of unknown type -or- two payloads are of the same type.</exception>
        protected FluentLogObject(IFluentManager manager, DateTime timestamp, LogFlags flags = Defaults.LogFlags, sbyte priority = Defaults.Priority, byte indent = Defaults.Indent, IEnumerable<string> sources = null, IEnumerable<IPayload> payloads = null)
        {
            if (manager == null)
                throw new ArgumentNullException("manager");

            this.Manager = manager;
            this.Timestamp = timestamp;
            this.Flags = flags;
            this.Priority = priority;
            this.Indent = indent;

            if (sources == null)
            {
                this.sources = new List<string>();
            }
            else
            {
                this.sources = new List<string>(sources);

                for (int i = 0; i < this.sources.Count; i++)
                    if (this.sources[i] == null)
                        throw new ArgumentException("The enumeration of sources contains a null element.", "sources");
            }

            this.Sources = new ReadOnlyCollection<string>(this.sources);

            if (payloads == null)
            {
                this.payloads = new List<IPayload>();
            }
            else
            {
                var plds = payloads.ToArray();

                for (int i = 0; i < plds.Length; i++)
                {
                    PayloadTypes pldt;

                    try
                    {
                        pldt = plds[i].GetType().GetPayloadType();
                    }
                    catch (ArgumentException x)
                    {
                        throw new ArgumentException("Payloads enumeration contains a payload of unkown type.", x);
                    }
                    catch (NullReferenceException x)
                    {
                        throw new ArgumentException("Payloads enumeration contains a null payload.", x);
                    }

                    if ((this.PayloadTypes & pldt) == 0)
                        this.PayloadTypes |= pldt;
                    else
                        throw new ArgumentException("Payloads enumerations may not contain two payloads of the same type." + Environment.NewLine + "Duplicated type: " + pldt);
                }

                this.payloads = new List<IPayload>(plds);
            }

            this.Payloads = new ReadOnlyCollection<IPayload>(this.payloads);
        }
Beispiel #17
0
        IFluentLogObject IFluentLogObject.WithPayloads(IEnumerable<IPayload> payloads)
        {
            if (payloads == null)
                throw new ArgumentNullException("payloads");

            this.payloads.Clear();
            this.PayloadTypes = 0;

            this.payloads.AddRange(payloads);

            for (int i = 0; i < this.payloads.Count; i++)
            {
                PayloadTypes pldt;

                try
                {
                    pldt = this.payloads[i].GetType().GetPayloadType();
                }
                catch (ArgumentException x)
                {
                    throw new ArgumentException("Payloads enumeration contains a payload of unkown type.", x);
                }
                catch (NullReferenceException x)
                {
                    throw new ArgumentException("Payloads enumeration contains a null payload.", x);
                }

                if ((this.PayloadTypes & pldt) == 0)
                    this.PayloadTypes |= pldt;
                else
                    throw new ArgumentException("Payloads enumerations may not contain two payloads of the same type." + Environment.NewLine + "Duplicated type: " + pldt);
            }

            return this;
        }
Beispiel #18
0
        IFluentLogObject IFluentLogObject.WithExtraPayloads(IEnumerable<IPayload> payloads)
        {
            if (payloads == null)
                throw new ArgumentNullException("payloads");

            var start = this.payloads.Count;

            this.payloads.AddRange(payloads);

            for (int i = start; i < this.payloads.Count; i++)
            {
                PayloadTypes pldt;

                try
                {
                    pldt = this.payloads[i].GetType().GetPayloadType();
                }
                catch (ArgumentException x)
                {
                    throw new ArgumentException("Extra payloads enumeration contains a payload of unkown type.", x);
                }
                catch (NullReferenceException x)
                {
                    throw new ArgumentException("Extra payloads enumeration contains a null payload.", x);
                }

                if ((this.PayloadTypes & pldt) == 0)
                    this.PayloadTypes |= pldt;
                else
                    throw new InvalidOperationException("An attempt was made to add a payload of a type that was already added to the object." + Environment.NewLine + "Duplicated type: " + pldt);
            }

            return this;
        }
 public OutgoingPayloadHandler(byte[] rawData, PayloadTypes pType)
 {
     Header      = new byte[Properties.TS3SRV_WEBLIST_PROTOCOL_HEADERLEN];
     Payload     = rawData;
     PayloadType = pType;
 }
Beispiel #20
0
 public static AcceptHeader CreateAcceptHeaderForGetInstance(string transferSyntax = "*", string mediaType = KnownContentTypes.ApplicationDicom, double?quality = null, PayloadTypes payloadTypes = PayloadTypes.SinglePart)
 {
     return(CreateAcceptHeader(
                transferSyntax: transferSyntax,
                payloadType: payloadTypes,
                mediaType: mediaType,
                quality: quality));
 }
Beispiel #21
0
 public static AcceptHeader CreateAcceptHeader(string transferSyntax = "*", PayloadTypes payloadType = PayloadTypes.MultipartRelated, string mediaType = KnownContentTypes.ApplicationOctetStream, double?quality = null)
 {
     return(new AcceptHeader(mediaType, payloadType, transferSyntax, quality));
 }
        private void ParseResponse(HTTPResponse resp)
        {
            try
            {
                if (((resp != null) && (resp.Data != null)) && (resp.Data.Length >= 1))
                {
                    int num2;
                    for (int i = 0; i < resp.Data.Length; i += num2)
                    {
                        PayloadTypes text = PayloadTypes.Text;
                        num2 = 0;
                        if (resp.Data[i] < 0x30)
                        {
                            text = (PayloadTypes)resp.Data[i++];
                            for (byte j = resp.Data[i++]; j != 0xff; j = resp.Data[i++])
                            {
                                num2 = (num2 * 10) + j;
                            }
                        }
                        else
                        {
                            for (byte j = resp.Data[i++]; j != 0x3a; j = resp.Data[i++])
                            {
                                num2 = (num2 * 10) + (j - 0x30);
                            }
                        }
                        Packet packetWithAttachment = null;
                        switch (text)
                        {
                        case PayloadTypes.Text:
                            packetWithAttachment = new Packet(Encoding.UTF8.GetString(resp.Data, i, num2));
                            break;

                        case PayloadTypes.Binary:
                            if (this.PacketWithAttachment != null)
                            {
                                i++;
                                num2--;
                                byte[] destinationArray = new byte[num2];
                                Array.Copy(resp.Data, i, destinationArray, 0, num2);
                                this.PacketWithAttachment.AddAttachmentFromServer(destinationArray, true);
                                if (this.PacketWithAttachment.HasAllAttachment)
                                {
                                    packetWithAttachment      = this.PacketWithAttachment;
                                    this.PacketWithAttachment = null;
                                }
                            }
                            break;
                        }
                        if (packetWithAttachment != null)
                        {
                            try
                            {
                                this.OnPacket(packetWithAttachment);
                            }
                            catch (Exception exception)
                            {
                                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse - OnPacket", exception);
                                ((IManager)this.Manager).EmitError(SocketIOErrors.Internal, exception.Message + " " + exception.StackTrace);
                            }
                        }
                    }
                }
            }
            catch (Exception exception2)
            {
                ((IManager)this.Manager).EmitError(SocketIOErrors.Internal, exception2.Message + " " + exception2.StackTrace);
                HTTPManager.Logger.Exception("PollingTransport", "ParseResponse", exception2);
            }
        }