Exemple #1
0
 /// <inheritdoc/>
 protected override void Dispose(bool disposing)
 {
     if (this.IsDisposed)
     {
         return;
     }
     if (disposing)
     {
         _jdoc.Dispose();
     }
     base.Dispose(disposing);
 }
Exemple #2
0
 public void Dispose()
 {
     if (json != null)
     {
         json.Dispose();
     }
 }
Exemple #3
0
        private void TestRequestZipCodeDefault(string json)
        {
            JsonDocument jsonDocument = JsonDocument.Parse(json);
            JsonElement  jsonElement  = jsonDocument.RootElement;

            var cep         = jsonElement.GetProperty("cep").GetString();
            var logradouro  = jsonElement.GetProperty("logradouro").GetString();
            var complemento = jsonElement.GetProperty("complemento").GetString();
            var bairro      = jsonElement.GetProperty("bairro").GetString();
            var localidade  = jsonElement.GetProperty("localidade").GetString();
            var uf          = jsonElement.GetProperty("uf").GetString();
            var siafi       = jsonElement.GetProperty("siafi").GetString();
            var ibge        = jsonElement.GetProperty("ibge").GetString();
            var gia         = jsonElement.GetProperty("gia").GetString();
            var ddd         = jsonElement.GetProperty("ddd").GetString();

            Assert.IsTrue(!string.IsNullOrEmpty(json));

            Assert.IsInstanceOfType(jsonDocument.GetType(), typeof(JsonDocument).GetType());
            Assert.IsInstanceOfType(jsonElement.GetType(), typeof(JsonElement).GetType());

            Assert.AreEqual("01001-000", cep);
            //Assert.AreEqual("Praça da Sé", logradouro);
            //Assert.AreEqual("lado ímpar", complemento);
            //Assert.AreEqual("Sé", bairro);
            //Assert.AreEqual("São Paulo", localidade);
            Assert.AreEqual("SP", uf);
            Assert.AreEqual("7107", siafi);
            Assert.AreEqual("11", ddd);
            Assert.AreEqual("3550308", ibge);
            Assert.AreEqual("1004", gia);

            jsonDocument.Dispose();
        }
Exemple #4
0
 public void Dispose()
 {
     if (!disposed)
     {
         document.Dispose();
         disposed = true;
     }
 }
        /// <summary>
        /// Simple demonstration of Parse() method
        /// </summary>
        public static void JsonDocument_Parse(JsonDocumentOptions options)
        {
            // Example usage
            Console.WriteLine("JsonDocument.Parse(string)");

            // Read in the json file.
            string path       = "Data/users.json";
            string jsonString = string.Empty;

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader streamReader = new StreamReader(fs, Encoding.UTF8))
                {
                    jsonString = streamReader.ReadToEnd();
                }
            }

            JsonDocument jsonDocument = JsonDocument.Parse(jsonString, options);
            JsonElement  rootElement  = jsonDocument.RootElement;

            Console.WriteLine("Root Element ({1}): {0}", rootElement, rootElement.ValueKind);

            // // Enumerate the object
            // JsonElement.ObjectEnumerator objectEnumerator = rootElement.EnumerateObject();
            // foreach (JsonProperty property in objectEnumerator)
            // {
            //     Console.WriteLine("Element: {0}: {1}", property.Name, property.Value);
            // }
            jsonDocument.Dispose();

            // Example usage
            Console.WriteLine("JsonDocument.Parse(Stream)");

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                jsonDocument = JsonDocument.Parse(fs);
            }

            rootElement = jsonDocument.RootElement;
            Console.WriteLine("Root Element ({1}): {0}", rootElement, rootElement.ValueKind);
            jsonDocument.Dispose();
        }
        /// <summary>
        /// Look for the deserializer for this json string in the lookup dictionary, and return the object.
        /// </summary>
        /// <param name="jsonString"> A json string with a Type property inside the root object </param>
        /// <returns> The deserialized object </returns>
        public TBaseObject Deserialize(string jsonString)
        {
            JsonDocument jDoc = JsonManager.GetJsonDocument(jsonString);

            string type = jDoc.RootElement.GetProperty(TypeProperty).GetString();

            jDoc.Dispose();

            deserializerLookup.TryGetValue(type, out Func <string, TBaseObject> deserializer);

            return(deserializer(jsonString));
        }
Exemple #7
0
        public override async Task <List <StreamInfo> > GetVideoList(string url)
        {
            List <StreamInfo> videoList = new List <StreamInfo>();
            string            videoId   = url.Split('/')[5];
            string            title     = $"@{url.Split('/')[3]} Twitter video";

            using (HttpClient client = new HttpClient())
            {
                //Get javascript player url
                string pageSource = await client.GetStringAsync("https://twitter.com/i/videos/tweet/" + videoId).ConfigureAwait(false);

                string jsPlayerUrl = "";
                foreach (var line in pageSource.Split('\n'))
                {
                    if (line.Contains("script"))
                    {
                        jsPlayerUrl = line.Substring(line.IndexOf('"') + 1);
                        jsPlayerUrl = jsPlayerUrl.Remove(jsPlayerUrl.IndexOf('"'));
                        break;
                    }
                }
                //Get bearer token
                pageSource = await client.GetStringAsync(jsPlayerUrl).ConfigureAwait(false);

                string token = pageSource.Substring(pageSource.IndexOf("Bearer") + 7);
                token = token.Remove(token.IndexOf('"'));
                //Get guest_token
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
                HttpResponseMessage response = await client.PostAsync("https://api.twitter.com/1.1/guest/activate.json", null).ConfigureAwait(false);

                JsonDocument document   = JsonDocument.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
                string       guestToken = document.RootElement.GetProperty("guest_token").GetString();
                //Get m3u8 file
                client.DefaultRequestHeaders.Add("x-guest-token", guestToken);
                string jsResponse = await client.GetStringAsync($"https://api.twitter.com/1.1/videos/tweet/config/{videoId}.json").ConfigureAwait(false);

                document = JsonDocument.Parse(jsResponse);
                string playbackUrl = document.RootElement.GetProperty("track").GetProperty("playbackUrl").GetString();
                string m3u8Content = await client.GetStringAsync(playbackUrl).ConfigureAwait(false);

                //Get m3u8 playlists
                foreach (var(relativeUrl, label) in GetPlaylists(m3u8Content))
                {
                    videoList.Add(new StreamInfo($"https://video.twimg.com{relativeUrl}", false, title, label, "", 0));
                }

                document.Dispose();
            }

            return(videoList);
        }
Exemple #8
0
        private void TestRequestAddressCodeDefault(string json)
        {
            JsonDocument    jsonDocument   = JsonDocument.Parse(json);
            JsonElement     jsonElement    = jsonDocument.RootElement;
            ArrayEnumerator enumerateArray = jsonElement.EnumerateArray();

            Assert.IsTrue(!string.IsNullOrEmpty(json));
            Assert.IsTrue(jsonElement.ValueKind == JsonValueKind.Array);
            Assert.IsTrue(jsonElement.GetArrayLength() > 0);

            Assert.IsInstanceOfType(jsonDocument.GetType(), typeof(JsonDocument).GetType());
            Assert.IsInstanceOfType(jsonElement.GetType(), typeof(JsonElement).GetType());
            Assert.IsInstanceOfType(enumerateArray.GetType(), typeof(ArrayEnumerator).GetType());

            jsonDocument.Dispose();
        }
Exemple #9
0
        public async Task Create([Remainder] string rawJsonInput = "")
        {
            byte[]       byteArray = Encoding.UTF8.GetBytes(rawJsonInput);
            MemoryStream stream    = new MemoryStream(byteArray);

            try
            {
                JsonDocument json = await JsonDocument.ParseAsync(stream);

                var embed = await _service.BuildAsync(json);
                await ReplyAsync(embed : embed);

                await stream.DisposeAsync();

                await Task.Run(() => json.Dispose());
            }
            catch (Exception ex)
            {
                await _log.Log(new LogMessage(LogSeverity.Error, "input", ex.Message, ex));
            }
        }
Exemple #10
0
 public void Dispose()
 {
     json.Dispose();
 }
Exemple #11
0
 public void CleanUp()
 {
     _document.Dispose();
 }
Exemple #12
0
        async public Task handleRequest(HttpContext httpContext)
        {
            if (Introspection && httpContext.Request.Path == "/ast.json" && httpContext.Request.Method.ToUpperInvariant() == "GET")
            {
                await httpContext.Response.WriteAsync(Api.GetAstJson());

                return;
            }

            Context?     context      = null;
            JsonDocument?bodyDocument = null;
            var          stopWatch    = new Stopwatch();

            stopWatch.Start();

            try
            {
                StringValues origin;
                if (DynamicCorsOrigin && httpContext.Request.Headers.TryGetValue("origin", out origin))
                {
                    httpContext.Response.Headers.Add("Access-Control-Allow-Origin", origin);
                    httpContext.Response.Headers.Add("Vary", "Origin");
                }

                string method = httpContext.Request.Method.ToUpperInvariant();

                foreach (var header in Headers)
                {
                    if (method == "OPTIONS" && !header.Key.ToLowerInvariant().StartsWith("access-control-"))
                    {
                        continue;
                    }

                    httpContext.Response.Headers.Add(header.Key, header.Value);
                }

                if (method == "OPTIONS")
                {
                    return;
                }

                httpContext.Response.Headers.Add("Content-Type", "application/json; charset=utf-8");

                if (method == "HEAD")
                {
                    return;
                }

                if (method == "GET")
                {
                    if (httpContext.Request.Path.Value != "/")
                    {
                        httpContext.Response.StatusCode = 404;
                        return;
                    }

                    var ok = false;
                    try
                    {
                        ok = await OnHealthCheck();
                    }
                    catch (Exception)
                    {
                    }

                    httpContext.Response.StatusCode = ok ? 200 : 500;
                    await httpContext.Response.WriteAsync(ok? "{\"ok\":true}" : "{\"ok\":false}");

                    return;
                }

                if (method != "POST")
                {
                    httpContext.Response.StatusCode = 404;
                    return;
                }

                bodyDocument = await JsonDocument.ParseAsync(httpContext.Request.Body);

                context         = ContextParser.DecodeContext(bodyDocument.RootElement, "body");
                context.Headers = httpContext.Request.Headers;
                // TODO: X-Forwarded-For with trusted proxies
                context.Ip = httpContext.Connection.RemoteIpAddress.ToString();

                var duration     = stopWatch.Elapsed.TotalSeconds;
                var bufferWriter = new ArrayBufferWriter <byte>();
                using (var resultWriter = new Utf8JsonWriter(bufferWriter))
                {
                    resultWriter.WriteStartObject();
                    resultWriter.WritePropertyName("result");
                    await Api.ExecuteFunction(context, resultWriter);

                    resultWriter.WriteNull("error");
                    resultWriter.WriteNumber("duration", duration);
                    resultWriter.WriteString("host", Dns.GetHostName());
                    resultWriter.WriteEndObject();
                }

                Console.WriteLine($"{context.Id} [{duration.ToString("0.000000")}s] {context.Name}() -> OK");

                await httpContext.Response.WriteAsync(Encoding.UTF8.GetString(bufferWriter.WrittenSpan));
            }
            catch (Exception error)
            {
                Console.WriteLine(error.ToString());
                SdkgenException sdkgenError;
                if (error is SdkgenException)
                {
                    sdkgenError = (error as SdkgenException) !;
                }
                else
                {
                    sdkgenError = new SdkgenException("Fatal", error.Message, error);
                }

                var duration = stopWatch.Elapsed.TotalSeconds;

                if (OnRequestError != null && context != null)
                {
                    OnRequestError.Invoke(context, sdkgenError);
                    Console.WriteLine($"{context.Id} [{duration.ToString("0.000000")}s] {context.Name}() -> {sdkgenError.Type}");
                }

                httpContext.Response.StatusCode = sdkgenError.Type == "Fatal" ? 500 : 400;

                using (var resultWriter = new Utf8JsonWriter(httpContext.Response.Body))
                {
                    resultWriter.WriteStartObject();
                    resultWriter.WriteNull("result");
                    resultWriter.WriteStartObject("error");
                    resultWriter.WriteString("type", sdkgenError.Type);
                    resultWriter.WriteString("message", sdkgenError.Message);
                    resultWriter.WriteEndObject();
                    resultWriter.WriteNumber("duration", duration);
                    resultWriter.WriteString("host", Dns.GetHostName());
                    resultWriter.WriteEndObject();
                }
            }
            finally
            {
                bodyDocument?.Dispose();
            }
        }
Exemple #13
0
 public void Dispose()
 {
     _value.Dispose();
     _ownedValueMemory?.Dispose();
 }
Exemple #14
0
 public void Dispose()
 {
     _config.Dispose();
     _config = null;
 }
 public void Dispose()
 {
     _assetManifestManifestDom.Dispose();
 }
Exemple #16
0
 public void Dispose()
 {
     _appendHyperSchema.Dispose();
     _deleteStreamHyperSchema.Dispose();
 }
 public void Dispose()
 => _wrapped.Dispose();
Exemple #18
0
        public void LoadAsTexture(string fileLocation, string resourceName)
        {
            if (_SDL_Renderer == IntPtr.Zero)
            {
                Debug.Log("ResourceManager.LoadAsTexture()", "SDL Renderer not yet initialized, waiting for init.");
                Debug.Log("ResourceManager.LoadAsTexture()", "Warning! Call 'GameEngine.Start()' first before loading game resources.");
                Debug.Log("ResourceManager.LoadAsTexture()", "Otherwise, this will be an endless loop.");
                while (_SDL_Renderer == IntPtr.Zero)
                {
                    SDL_Delay(100);
                }
                Debug.Log("ResourceManager.LoadAsTexture()", "SDL Renderer initialized.");
                //throw new ResourceException($"SDL Renderer not yet initialized, try calling GameEngine.InitGraphics() first", fileLocation);
            }
            if (_Textures.Contains(resourceName))
            {
                throw new ResourceException($"A resource with the same name '{resourceName}' already exists.", fileLocation);
            }
            if (!File.Exists(fileLocation))
            {
                throw new ResourceException($"Error loading resource '{resourceName}'. File not found.", fileLocation);
            }
            ZipArchive archive;

            try
            {
                archive = ZipFile.OpenRead(fileLocation);
            }
            catch
            {
                throw new ResourceException($"Error loading resource '{resourceName}'.", fileLocation);
            }
            bool          loadedMetadata = false;
            List <string> files = new List <string>();
            Size          spriteSize = new Size(), sheetSize = new Size();
            bool          isSheet = false;

            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                if (entry.Name == "metadata")
                {
                    loadedMetadata = true;
                    using (Stream ms = entry.Open())
                    {
                        try
                        {
                            StreamReader reader = new StreamReader(ms);
                            string       json   = reader.ReadToEnd();
                            reader.Close();
                            JsonDocument doc  = JsonDocument.Parse(json);
                            var          meta = doc.RootElement;
                            isSheet      = meta.GetProperty("IsSheet").GetBoolean();
                            spriteSize.W = meta.GetProperty("SpriteSize.W").GetInt32();
                            spriteSize.H = meta.GetProperty("SpriteSize.H").GetInt32();
                            sheetSize.W  = meta.GetProperty("SheetSize.W").GetInt32();
                            sheetSize.H  = meta.GetProperty("SheetSize.H").GetInt32();
                            doc.Dispose();
                        } catch
                        {
                            throw new ResourceException($"Error parsing metadata for '{resourceName}'.", fileLocation);
                        }
                    }
                }
                else
                {
                    files.Add(entry.Name);
                }
            }
            if (!loadedMetadata && !FLAG_ALLOW_MISSING_METADATA)
            {
                archive.Dispose();
                throw new ResourceException($"Error loading resource '{resourceName}'. Metadata not found.", fileLocation);
            }
            List <IntPtr> surfaces = new List <IntPtr>();
            List <IntPtr> textures = new List <IntPtr>();

            /* Load resource here */
            SDL_GetError();
            foreach (string file in files)
            {
                try
                {
                    ZipArchiveEntry data   = archive.GetEntry(file);
                    Stream          s      = data.Open();
                    byte[]          buffer = new byte[data.Length];
                    //GCHandle handle = GCHandle.Alloc(byteData, GCHandleType.Pinned);
                    IntPtr ptrArray = Marshal.AllocHGlobal(buffer.Length);
                    s.Read(buffer, 0, buffer.Length);
                    Marshal.Copy(buffer, 0, ptrArray, buffer.Length);
                    Debug.Log("ResourceManager.LoadAsTexture()", $"Read texture data from {file}#{resourceName} @ {buffer.Length} byte(s).");
                    IntPtr rwops = SDL_RWFromMem(ptrArray, buffer.Length);
                    IntPtr surface;
                    surface = IMG_Load_RW(rwops, 0);
                    string sE1 = SDL_GetError();
                    if (surface == IntPtr.Zero || rwops == IntPtr.Zero)
                    {
                        Debug.Log("ResourceManager.LoadAsTexture()", $"Error reading texture data {file}#{resourceName}. {sE1}");
                        continue;
                    }
                    Debug.Log("ResourceManager.LoadAsTexture()", $"Loaded texture data as surface from {file}#{resourceName}.");
                    IntPtr texture;
                    while (_SDL_Renderer == IntPtr.Zero)
                    {
                        SDL_Delay(100);
                    }
                    try
                    {
                        if (!FLAG_USE_ALTERNATE_TEXTURE_STRAT)
                        {
                            //SDL_Renderc
                            texture = SDL_CreateTextureFromSurface(_SDL_Renderer, surface);
                            //texture = CreateTexture(_SDL_Renderer, surface);
                        }
                        else
                        {
#pragma warning disable CS0162 // Unreachable code detected
                            texture = IMG_LoadTexture_RW(_SDL_Renderer, rwops, 0);
#pragma warning restore CS0162 // Unreachable code detected
                        }
                    } catch (Exception e)
                    {
                        Debug.Log("ResourceManager.LoadAsTexture()", $"Error creating texture data {file}#{resourceName}. {e.Message}");
                        continue;
                    }
                    string sE2 = SDL_GetError();
                    if (texture == IntPtr.Zero)
                    {
                        Debug.Log("ResourceManager.LoadAsTexture()", $"Error creating texture data {file}#{resourceName}. {sE2}");
                        continue;
                    }
                    surfaces.Add(surface);
                    textures.Add(texture);
                    Debug.Log("ResourceManager.LoadAsTexture()", $"Created texture from surface {file}#{resourceName}.");
                    //SDL_FreeSurface(surface);
                    Marshal.FreeHGlobal(ptrArray);
                    SDL_RWclose(rwops);
                } catch
                {
                    Debug.Log("ResourceManager.LoadAsTexture()", $"Error loading texture {file}#{resourceName}. Skipped file.");
                }
            }
            archive.Dispose();
            TextureResource res = new TextureResource()
            {
                IsSpriteSheet = isSheet,
                SheetSize     = sheetSize,
                SpriteSize    = spriteSize,
                DataPtr       = surfaces.ToArray(),
                Textures      = textures.ToArray(),
                ResourceName  = resourceName
            };
            _Textures.Add(res);
            Debug.Log("ResourceManager.LoadAsTexture()", $"Successfully added texture {resourceName} to resources.");
        }
Exemple #19
0
        private HubMessage ParseMessage(ReadOnlySequence <byte> input, IInvocationBinder binder)
        {
            try
            {
                // We parse using the Utf8JsonReader directly but this has a problem. Some of our properties are dependent on other properties
                // and since reading the json might be unordered, we need to store the parsed content as JsonDocument to re-parse when true types are known.
                // if we're lucky and the state we need to directly parse is available, then we'll use it.

                int?                        type                     = null;
                string                      invocationId             = null;
                string                      target                   = null;
                string                      error                    = null;
                var                         hasItem                  = false;
                object                      item                     = null;
                var                         hasResult                = false;
                object                      result                   = null;
                var                         hasArguments             = false;
                object[]                    arguments                = null;
                string[]                    streamIds                = null;
                JsonDocument                argumentsToken           = null;
                JsonDocument                itemsToken               = null;
                JsonDocument                resultToken              = null;
                ExceptionDispatchInfo       argumentBindingException = null;
                Dictionary <string, string> headers                  = null;
                var                         completed                = false;

                var reader = new Utf8JsonReader(input, isFinalBlock: true, state: default);

                reader.CheckRead();

                // We're always parsing a JSON object
                reader.EnsureObjectStart();

                do
                {
                    switch (reader.TokenType)
                    {
                    case JsonTokenType.PropertyName:
                        if (reader.TextEquals(TypePropertyNameBytes.EncodedUtf8Bytes))
                        {
                            type = reader.ReadAsInt32(TypePropertyName);

                            if (type == null)
                            {
                                throw new InvalidDataException($"Expected '{TypePropertyName}' to be of type {JsonTokenType.Number}.");
                            }
                        }
                        else if (reader.TextEquals(InvocationIdPropertyNameBytes.EncodedUtf8Bytes))
                        {
                            invocationId = reader.ReadAsString(InvocationIdPropertyName);
                        }
                        else if (reader.TextEquals(StreamIdsPropertyNameBytes.EncodedUtf8Bytes))
                        {
                            reader.CheckRead();

                            if (reader.TokenType != JsonTokenType.StartArray)
                            {
                                throw new InvalidDataException(
                                          $"Expected '{StreamIdsPropertyName}' to be of type {SystemTextJsonExtensions.GetTokenString(JsonTokenType.StartArray)}.");
                            }

                            var newStreamIds = new List <string>();
                            reader.Read();
                            while (reader.TokenType != JsonTokenType.EndArray)
                            {
                                newStreamIds.Add(reader.GetString());
                                reader.Read();
                            }

                            streamIds = newStreamIds.ToArray();
                        }
                        else if (reader.TextEquals(TargetPropertyNameBytes.EncodedUtf8Bytes))
                        {
                            target = reader.ReadAsString(TargetPropertyName);
                        }
                        else if (reader.TextEquals(ErrorPropertyNameBytes.EncodedUtf8Bytes))
                        {
                            error = reader.ReadAsString(ErrorPropertyName);
                        }
                        else if (reader.TextEquals(ResultPropertyNameBytes.EncodedUtf8Bytes))
                        {
                            hasResult = true;

                            reader.CheckRead();

                            if (string.IsNullOrEmpty(invocationId))
                            {
                                // If we don't have an invocation id then we need to store it as a JsonDocument so we can parse it later
                                resultToken = JsonDocument.ParseValue(ref reader);
                            }
                            else
                            {
                                // If we have an invocation id already we can parse the end result
                                var returnType = binder.GetReturnType(invocationId);
                                using var token = JsonDocument.ParseValue(ref reader);
                                result          = BindType(token.RootElement, returnType);
                            }
                        }
                        else if (reader.TextEquals(ItemPropertyNameBytes.EncodedUtf8Bytes))
                        {
                            reader.CheckRead();

                            hasItem = true;

                            string id = null;
                            if (!string.IsNullOrEmpty(invocationId))
                            {
                                id = invocationId;
                            }
                            else
                            {
                                // If we don't have an id yet then we need to store it as a JsonDocument to parse later
                                itemsToken = JsonDocument.ParseValue(ref reader);
                                continue;
                            }

                            try
                            {
                                var itemType = binder.GetStreamItemType(id);
                                using var token = JsonDocument.ParseValue(ref reader);
                                item            = BindType(token.RootElement, itemType);
                            }
                            catch (Exception ex)
                            {
                                return(new StreamBindingFailureMessage(id, ExceptionDispatchInfo.Capture(ex)));
                            }
                        }
                        else if (reader.TextEquals(ArgumentsPropertyNameBytes.EncodedUtf8Bytes))
                        {
                            reader.CheckRead();

                            int initialDepth = reader.CurrentDepth;
                            if (reader.TokenType != JsonTokenType.StartArray)
                            {
                                throw new InvalidDataException($"Expected '{ArgumentsPropertyName}' to be of type {SystemTextJsonExtensions.GetTokenString(JsonTokenType.StartArray)}.");
                            }

                            hasArguments = true;

                            if (string.IsNullOrEmpty(target))
                            {
                                // We don't know the method name yet so just store the array in JsonDocument
                                argumentsToken = JsonDocument.ParseValue(ref reader);
                            }
                            else
                            {
                                try
                                {
                                    var paramTypes = binder.GetParameterTypes(target);
                                    using var token = JsonDocument.ParseValue(ref reader);
                                    arguments       = BindTypes(token.RootElement, paramTypes);
                                }
                                catch (Exception ex)
                                {
                                    argumentBindingException = ExceptionDispatchInfo.Capture(ex);

                                    // Could be at any point in argument array JSON when an error is thrown
                                    // Read until the end of the argument JSON array
                                    while (reader.CurrentDepth == initialDepth && reader.TokenType == JsonTokenType.StartArray ||
                                           reader.CurrentDepth > initialDepth)
                                    {
                                        reader.CheckRead();
                                    }
                                }
                            }
                        }
                        else if (reader.TextEquals(HeadersPropertyNameBytes.EncodedUtf8Bytes))
                        {
                            reader.CheckRead();
                            headers = ReadHeaders(ref reader);
                        }
                        else
                        {
                            reader.CheckRead();
                            reader.Skip();
                        }
                        break;

                    case JsonTokenType.EndObject:
                        completed = true;
                        break;
                    }
                }while (!completed && reader.CheckRead());

                HubMessage message;

                switch (type)
                {
                case HubProtocolConstants.InvocationMessageType:
                {
                    if (argumentsToken != null)
                    {
                        // We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything.
                        try
                        {
                            var paramTypes = binder.GetParameterTypes(target);
                            arguments = BindTypes(argumentsToken.RootElement, paramTypes);
                        }
                        catch (Exception ex)
                        {
                            argumentBindingException = ExceptionDispatchInfo.Capture(ex);
                        }
                        finally
                        {
                            argumentsToken.Dispose();
                        }
                    }

                    message = argumentBindingException != null
                                ? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException)
                                : BindInvocationMessage(invocationId, target, arguments, hasArguments, streamIds, binder);
                }
                break;

                case HubProtocolConstants.StreamInvocationMessageType:
                {
                    if (argumentsToken != null)
                    {
                        // We weren't able to bind the arguments because they came before the 'target', so try to bind now that we've read everything.
                        try
                        {
                            var paramTypes = binder.GetParameterTypes(target);
                            arguments = BindTypes(argumentsToken.RootElement, paramTypes);
                        }
                        catch (Exception ex)
                        {
                            argumentBindingException = ExceptionDispatchInfo.Capture(ex);
                        }
                        finally
                        {
                            argumentsToken.Dispose();
                        }
                    }

                    message = argumentBindingException != null
                                ? new InvocationBindingFailureMessage(invocationId, target, argumentBindingException)
                                : BindStreamInvocationMessage(invocationId, target, arguments, hasArguments, streamIds, binder);
                }
                break;

                case HubProtocolConstants.StreamItemMessageType:
                    if (itemsToken != null)
                    {
                        try
                        {
                            var returnType = binder.GetStreamItemType(invocationId);
                            item = BindType(itemsToken.RootElement, returnType);
                        }
                        catch (JsonException ex)
                        {
                            message = new StreamBindingFailureMessage(invocationId, ExceptionDispatchInfo.Capture(ex));
                            break;
                        }
                        finally
                        {
                            itemsToken.Dispose();
                        }
                    }

                    message = BindStreamItemMessage(invocationId, item, hasItem, binder);
                    break;

                case HubProtocolConstants.CompletionMessageType:
                    if (resultToken != null)
                    {
                        try
                        {
                            var returnType = binder.GetReturnType(invocationId);
                            result = BindType(resultToken.RootElement, returnType);
                        }
                        finally
                        {
                            resultToken.Dispose();
                        }
                    }

                    message = BindCompletionMessage(invocationId, error, result, hasResult, binder);
                    break;

                case HubProtocolConstants.CancelInvocationMessageType:
                    message = BindCancelInvocationMessage(invocationId);
                    break;

                case HubProtocolConstants.PingMessageType:
                    return(PingMessage.Instance);

                case HubProtocolConstants.CloseMessageType:
                    return(BindCloseMessage(error));

                case null:
                    throw new InvalidDataException($"Missing required property '{TypePropertyName}'.");

                default:
                    // Future protocol changes can add message types, old clients can ignore them
                    return(null);
                }

                return(ApplyHeaders(message, headers));
            }
            catch (JsonException jrex)
            {
                throw new InvalidDataException("Error reading JSON.", jrex);
            }
        }
 /// <inheritdoc />
 public void Dispose()
 {
     _manifest?.Dispose();
     HttpClient?.Dispose();
 }
 public void Dispose()
 {
     _decodedToken.Dispose();
 }
 public void Dispose() => _setStreamMetadata.Dispose();