/// <summary>
        ///     Flushes remaining data to the file and then manually writes JSON tags to close the file out
        /// </summary>
        internal override async Task FlushWriter()
        {
            if (!FileCreated)
            {
                return;
            }

            if (Queue.Count > 0)
            {
                await WriteData();
            }

            var meta = new MetaTag
            {
                Count             = Count,
                CollectionMethods = (long)_context.ResolvedCollectionMethods,
                DataType          = DataType,
                Version           = DataVersion
            };

            await _jsonWriter.FlushAsync();

            await _jsonWriter.WriteEndArrayAsync();

            await _jsonWriter.WritePropertyNameAsync("meta");

            await _jsonWriter.WriteRawValueAsync(JsonConvert.SerializeObject(meta, PrettyPrint));

            await _jsonWriter.FlushAsync();

            await _jsonWriter.CloseAsync();
        }
Example #2
0
        public void Write(IEnumerable <IRow> rows)
        {
            var jw = new JsonTextWriter(_streamWriter)
            {
                Formatting = _context.Connection.Format == "json" ? Formatting.Indented : Formatting.None
            };

            jw.WriteStartArrayAsync().ConfigureAwait(false);

            foreach (var row in rows)
            {
                jw.WriteStartObjectAsync().ConfigureAwait(false);

                for (int i = 0; i < _fields.Length; i++)
                {
                    jw.WritePropertyNameAsync(_fields[i].Alias).ConfigureAwait(false);
                    if (_formats[i] == string.Empty)
                    {
                        jw.WriteValueAsync(row[_fields[i]]).ConfigureAwait(false);
                    }
                    else
                    {
                        jw.WriteValueAsync(string.Format(_formats[i], row[_fields[i]])).ConfigureAwait(false);
                    }
                }
                jw.WriteEndObjectAsync().ConfigureAwait(false);
                _context.Entity.Inserts++;

                jw.FlushAsync().ConfigureAwait(false);
            }

            jw.WriteEndArrayAsync().ConfigureAwait(false);

            jw.FlushAsync().ConfigureAwait(false);
        }
Example #3
0
        /// <inheritdoc/>
        public async Task <string> ExportAsJsonAsync <TLog>(Predicate <TLog> predicate) where TLog : LogBase
        {
            // Open the destination streams
            using (MemoryStream stream = new MemoryStream())
                using (StreamWriter writer = new StreamWriter(stream))
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer)
                    {
                        Formatting = Formatting.Indented
                    })
                    {
                        JObject jObj = new JObject();
                        await Task.Run(() =>
                        {
                            IList <JObject> jlogs = (
                                from pair in LoadAsync <TLog>()
                                where predicate(pair.Log)
                                select JObject.FromObject(pair.Log)).ToList();
                            jObj["LogsCount"] = jlogs.Count;
                            jObj["Logs"]      = new JArray(jlogs);
                        });

                        // Write the JSON data
                        await jObj.WriteToAsync(jsonWriter);

                        await jsonWriter.FlushAsync();

                        // Return the JSON
                        byte[] bytes = stream.ToArray();
                        return(Encoding.UTF8.GetString(bytes));
                    }
        }
Example #4
0
        private async Task <HttpContent> BuildHttpContent(ResourceRootSingle root)
        {
            /* The streaming approach appears to have reduced the memory footprint by a decent
             * margin (maybe a third). I suspect that StringContent just copies the string to a
             * MemoryStream anyway so we're only reducing that extra step of string to stream. */
            //return new StringContent(root.ToJson(JsonSettings), Encoding.UTF8, JsonApiHeader);

            var serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                Formatting        = Formatting.None
            });

            var stream = new MemoryStream();
            var sr     = new StreamWriter(stream);
            var writer = new JsonTextWriter(sr);

            serializer.Serialize(writer, root);
            await writer.FlushAsync();

            stream.Seek(0, SeekOrigin.Begin);
            var content = new StreamContent(stream);

            content.Headers.ContentType = new MediaTypeHeaderValue(JsonApiHeader)
            {
                CharSet = Encoding.UTF8.WebName
            };
            return(content);
        }
Example #5
0
        public async Task Write(Stream stream, IEnumerable <Article> products)
        {
            using (TextWriter sw = new StreamWriter(stream))
                using (JsonWriter writer = new JsonTextWriter(sw))
                {
                    writer.WriteStartArray();

                    foreach (var product in products)
                    {
                        using (var productStream = new MemoryStream())
                        {
                            await _formatter.Write(productStream, product);

                            productStream.Position = 0;

                            using (var sr = new StreamReader(productStream))
                                using (var reader = new JsonTextReader(sr))
                                {
                                    await writer.WriteTokenAsync(reader);

                                    await writer.FlushAsync();
                                }
                        }
                    }

                    writer.WriteEndArray();
                    writer.Flush();
                }
        }
Example #6
0
        public static async Task SerializeAsync(TextWriter target, CompleteScoreboardSummary summary,
                                                IDictionary <TeamId, ScoreboardDetails> teamDetails, CompetitionRound round = 0)
        {
            using (JsonWriter jw = new JsonTextWriter(target))
            {
                jw.CloseOutput = false;

                // write
                await jw.WriteStartObjectAsync().ConfigureAwait(false);

                await jw.WritePropertyNameAsync("summary").ConfigureAwait(false);

                var serializer = JsonSerializer.CreateDefault();
                // serialize
                serializer.Serialize(jw, summary);
                await jw.WritePropertyNameAsync("teams").ConfigureAwait(false);

                serializer.Serialize(jw, teamDetails);
                await jw.WritePropertyNameAsync("round").ConfigureAwait(false);

                await jw.WriteValueAsync((int)round).ConfigureAwait(false);

                await jw.WriteEndObjectAsync().ConfigureAwait(false);

                await jw.FlushAsync().ConfigureAwait(false);
            }
        }
Example #7
0
        static async Task <T> GetObjectAsync <T>(string jsonFilePath, string objName, CancellationToken cancellationToken)
        {
            using (TextReader tr = File.OpenText(jsonFilePath))
            {
                using (JsonTextReader jr = new JsonTextReader(tr))
                {
                    while (await jr.ReadAsync(cancellationToken))
                    {
                        if (jr.TokenType == JsonToken.PropertyName && $"{jr.Value}" == objName)
                        {
                            StringBuilder sb = new StringBuilder();

                            using (TextWriter tw = new StringWriter(sb))
                            {
                                using (JsonTextWriter jw = new JsonTextWriter(tw))
                                {
                                    await jr.ReadAsync(cancellationToken);

                                    //write current JsonReader's token with children
                                    await jw.WriteTokenAsync(jr, cancellationToken);

                                    await jw.FlushAsync(cancellationToken);

                                    string objJson = sb.ToString();
                                    return(await Task.Run(() => JsonConvert.DeserializeObject <T>(objJson)));
                                }
                            }
                        }
                    }

                    throw new Exception($"'{objName}' not found...");
                }
            }
        }
Example #8
0
            public async Task WriteBody(StreamWriter writer)
            {
                var jwriter = new JsonTextWriter(writer);
                await Json.WriteToAsync(jwriter);

                await jwriter.FlushAsync();
            }
Example #9
0
        public async Task SaveDataAsync(object response, string identifier)
        {
            var fileName   = _settings.UseIdDirectlyAsName ? identifier : identifier + ".json";
            var serverPath = Path.Combine(_settings.RootPath, fileName);

            if (File.Exists(serverPath))
            {
                File.Delete(serverPath);
            }

            // make sure data directory exists
            var dataFolderPath = _settings.RootPath;

            if (!Directory.Exists(dataFolderPath))
            {
                Directory.CreateDirectory(dataFolderPath);
            }

            // write asynchronously to a file
            using (var asyncFileStream = new FileStream(serverPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, 4096, true))
            {
                using (var writer = new JsonTextWriter(new StreamWriter(asyncFileStream)))
                {
                    _serializer.Serialize(writer, response);
                    await writer.FlushAsync();
                }
            }
        }
Example #10
0
        private static async Task MakeRequest(Stream stream, Request request)
        {
            var writer = new JsonTextWriter(new StreamWriter(stream));

            Serializer.Serialize(writer, request);
            await writer.FlushAsync();
        }
        public async Task <IApiResponse> PostAsJsonAsync(IEvent events, JsonSerializer serializer)
        {
            var memoryStream = new MemoryStream();
            var sw           = new StreamWriter(memoryStream, leaveOpen: true);

            using (var content = new StreamContent(memoryStream))
            {
                using (JsonWriter writer = new JsonTextWriter(sw)
                {
                    CloseOutput = true
                })
                {
                    serializer.Serialize(writer, events);
                    content.Headers.ContentType = new MediaTypeHeaderValue(MimeTypes.Json);
                    _request.Content            = content;
                    await writer.FlushAsync().ConfigureAwait(false);

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    var response = new HttpClientResponse(await _client.SendAsync(_request).ConfigureAwait(false));
                    if (response.StatusCode != 200 && response.StatusCode != 202)
                    {
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        using var sr = new StreamReader(memoryStream);
                        var headers = string.Join(", ", _request.Headers.Select(h => $"{h.Key}: {string.Join(", ", h.Value)}"));

                        var payload = await sr.ReadToEndAsync().ConfigureAwait(false);

                        Log.Warning("AppSec event not correctly sent to backend {statusCode} by class {className} with response {responseText}, request headers: were {headers}, payload was: {payload}", new object[] { response.StatusCode, nameof(HttpClientRequest), await response.ReadAsStringAsync().ConfigureAwait(false), headers, payload });
                    }

                    return(response);
                }
            }
        }
Example #12
0
        public void OnNext(Airplane airplane)
        {
            Task.Run(async() => {
                try
                {
                    writer_.WriteStartObject();

                    writer_.WritePropertyName("CallSign");
                    writer_.WriteValue(airplane.FlightPlan.CallSign);

                    writer_.WritePropertyName("State");
                    writer_.WriteValue(airplane.StateDescription);

                    writer_.WriteEndObject();

                    writer_.WriteWhitespace("\n");

                    // Ensure that the value is written out immediately to the network stream
                    // (the writer will flush the underlying stream too)
                    await writer_.FlushAsync();
                }
                catch (Exception e)
                {
                    logger_.LogWarning(LoggingEvents.StreamingAirplaneInformationFailed, e, "Writing airplane information to network stream failed");
                    throw;
                }
            });
        }
Example #13
0
        public static async Task WriteJsonAsync(JObject json, Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            using (var writer = new StreamWriter(stream, JsonEncoding, bufferSize: 8192, leaveOpen: true))
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    jsonWriter.Formatting = Formatting.None;
#if USEJSONNET901
                    json.WriteTo(jsonWriter);
#else
                    await json.WriteToAsync(jsonWriter);
#endif
                    await writer.FlushAsync();

#if USEJSONNET901
                    jsonWriter.Flush();
#else
                    await jsonWriter.FlushAsync();
#endif
                }

            if (stream.CanSeek)
            {
                stream.Position = 0;
            }
        }
Example #14
0
 public static async Task SerializeToJsonAndWriteAsync <T>(this Stream stream, T objectToWrite,
                                                           Encoding encoding, int bufferSize, bool leaveOpen, bool resetStream = false)
 {
     if (stream == null)
     {
         throw new ArgumentNullException(nameof(stream));
     }
     if (!stream.CanWrite)
     {
         throw new NotSupportedException("Can't write to this stream.");
     }
     if (encoding == null)
     {
         throw new ArgumentNullException(nameof(encoding));
     }
     using (var streamWriter = new StreamWriter(stream, encoding, bufferSize, leaveOpen))
     {
         using (var jsonTextWriter = new JsonTextWriter(streamWriter))
         {
             var jsonSerializer = new JsonSerializer();
             jsonSerializer.Serialize(jsonTextWriter, objectToWrite);
             await jsonTextWriter.FlushAsync();
         }
     }
     if (resetStream && stream.CanSeek)
     {
         stream.Seek(0, SeekOrigin.Begin);
     }
 }
Example #15
0
        /// <summary>
        /// Creates an IoTCentral JSON message for a event change notification, based on the event configuration for the endpoint.
        /// </summary>
        private async Task <string> CreateIoTCentralJsonForEventChangeAsync(EventMessageData messageData, CancellationToken shutdownToken)
        {
            try
            {
                // build the JSON message for IoTCentral
                StringBuilder jsonStringBuilder = new StringBuilder();
                StringWriter  jsonStringWriter  = new StringWriter(jsonStringBuilder);
                using (JsonWriter jsonWriter = new JsonTextWriter(jsonStringWriter))
                {
                    await jsonWriter.WriteStartObjectAsync(shutdownToken).ConfigureAwait(false);

                    await jsonWriter.WritePropertyNameAsync(messageData.DisplayName, shutdownToken).ConfigureAwait(false);

                    var eventValues = string.Join(",", messageData.EventValues.Select(s => new {
                        s.Name,
                        s.Value
                    }));
                    await jsonWriter.WriteValueAsync(eventValues, shutdownToken).ConfigureAwait(false);

                    await jsonWriter.WritePropertyNameAsync("messageType", shutdownToken).ConfigureAwait(false);

                    await jsonWriter.WriteValueAsync("event", shutdownToken).ConfigureAwait(false);

                    await jsonWriter.WriteEndObjectAsync(shutdownToken).ConfigureAwait(false);

                    await jsonWriter.FlushAsync(shutdownToken).ConfigureAwait(false);
                }
                return(jsonStringBuilder.ToString());
            }
            catch (Exception e)
            {
                _logger.Error(e, "Generation of IoTCentral JSON message failed.");
            }
            return(string.Empty);
        }
Example #16
0
        public async Task DoExportAsync(Stream outStream, Action <ExportImportProgressInfo> progressCallback, ICancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var progressInfo = new ExportImportProgressInfo {
                Description = "Loading data..."
            };

            progressCallback(progressInfo);

            using (var sw = new StreamWriter(outStream, Encoding.UTF8))
                using (var writer = new JsonTextWriter(sw))
                {
                    await writer.WriteStartObjectAsync();

                    await writer.WritePropertyNameAsync("DynamicAssociations");

                    await writer.SerializeJsonArrayWithPagingAsync(_serializer, _batchSize, async (skip, take) =>
                                                                   (GenericSearchResult <Association>) await _associationSearchService.SearchAssociationsAsync(new AssociationSearchCriteria {
                        Skip = skip, Take = take
                    })
                                                                   , (processedCount, totalCount) =>
                    {
                        progressInfo.Description = $"{ processedCount } of { totalCount } dynamic associations have been exported";
                        progressCallback(progressInfo);
                    }, cancellationToken);

                    await writer.WriteEndObjectAsync();

                    await writer.FlushAsync();
                }
        }
Example #17
0
        /// <inheritdoc />
        public async Task SaveAzureCredentialsAsync(string organization, string username, string token)
        {
            var settings = new CliSettings();

            settings.AzureDevOps.Organization         = organization;
            settings.AzureDevOps.Credentials.Token    = token;
            settings.AzureDevOps.Credentials.Username = username;
            var jsonToken = JToken.FromObject(settings);
            var fileInfo  = new FileInfo(this.GetPath());

            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }

            using (var stream = File.Open(fileInfo.FullName, FileMode.OpenOrCreate))
            {
                stream.SetLength(0);
                using (var streamWriter = new StreamWriter(stream))
                {
                    using (var writer = new JsonTextWriter(streamWriter))
                    {
                        await jsonToken.WriteToAsync(writer);

                        await writer.FlushAsync();
                    }
                }
            }
        }
Example #18
0
        private async Task SaveBlobEntityAsync(
            Guid operationId,
            string blockchainType,
            TransactionExecutionBlobEntity blobEntity)
        {
            var containerName = TransactionExecutionBlobEntity.GetContainerName(blockchainType);
            var blobName      = TransactionExecutionBlobEntity.GetBlobName(operationId);

            using (var stream = new MemoryStream())
                using (var textWriter = new StreamWriter(stream))
                    using (var jsonWriter = new JsonTextWriter(textWriter))
                    {
                        _blobJsonSerializer.Serialize(jsonWriter, blobEntity);

                        await jsonWriter.FlushAsync();

                        await textWriter.FlushAsync();

                        await stream.FlushAsync();

                        stream.Position = 0;

                        await _blob.SaveBlobAsync(containerName, blobName, stream);
                    }
        }
Example #19
0
        private static async Task WriteResponse(Stream stream, Response response)
        {
            var writer = new JsonTextWriter(new StreamWriter(stream));

            Serializer.Serialize(writer, response);
            await writer.FlushAsync();
        }
Example #20
0
        internal static async Task <HttpResponseMessage> PostJsonAsync(this HttpClient client,
                                                                       string path,
                                                                       object requestBody,
                                                                       CancellationToken cancellationToken = default)
        {
            using var stream       = new MemoryStream();
            using var streamWriter = new StreamWriter(stream);
            using var jsonWriter   = new JsonTextWriter(streamWriter);

            Serializer.Serialize(jsonWriter, requestBody);
            await jsonWriter.FlushAsync(cancellationToken);

            stream.Position = 0;

            var requestContent = new StreamContent(stream);

            requestContent.Headers.ContentType = new MediaTypeHeaderValue(JsonContentType)
            {
                CharSet = Encoding.UTF8.WebName
            };

            var response = await client.PostAsync(path, requestContent, cancellationToken);

            return(response);
        }
Example #21
0
        private async Task SendResponse(HttpContext httpContext, JsonRpcResponse response)
        {
            var jObject = JObject.FromObject(response, _server.Serializer);

            // append jsonrpc constant if enabled
            if (_options.UseJsonRpcConstant)
            {
                jObject.AddFirst(new JProperty("jsonrpc", "2.0"));
            }

            // ensure that respose has either result or error property
            if (jObject.Property("result") == null && jObject.Property("error") == null)
            {
                jObject.Add("result", null);
            }

            httpContext.Response.StatusCode  = 200;
            httpContext.Response.ContentType = "application/json";
            using (var writer = new StreamWriter(httpContext.Response.Body))
                using (var jsonWriter = new JsonTextWriter(writer))
                {
                    await jObject.WriteToAsync(jsonWriter);

                    await jsonWriter.FlushAsync();

                    await writer.FlushAsync();
                }
        }
Example #22
0
        public async Task <HttpResponseMessage> PostAsync <T>(
            string uri,
            T value,
            IDictionary <string, string[]> headers,
            CancellationToken cancellationToken = default)
        {
            using (var stream = s_streamManager.GetStream())
                using (var writer = new JsonTextWriter(new StreamWriter(stream))
                {
                    CloseOutput = false
                })
                {
                    var token = JToken.FromObject(value, _serializer);

                    await token.WriteToAsync(writer, cancellationToken);

                    await writer.FlushAsync(cancellationToken);

                    stream.Position = 0;

                    using (var client = _clientFactory())
                        using (var request = new HttpRequestMessage(HttpMethod.Post, uri)
                        {
                            Content = new StreamContent(stream)
                            {
                                Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
                            }
                        })
                        {
                            CopyHeaders(headers, request);

                            return(await client.SendAsync(request, cancellationToken));
                        }
                }
        }
        public async Task SaveAsync(string tenant, IDictionary <string, string> data)
        {
            JObject tenantsSettings;

            var fileInfo = await _shellsFileStore.GetFileInfoAsync(_tenantsBlobName);

            if (fileInfo != null)
            {
                using (var stream = await _shellsFileStore.GetFileStreamAsync(_tenantsBlobName))
                {
                    using (var streamReader = new StreamReader(stream))
                    {
                        using (var reader = new JsonTextReader(streamReader))
                        {
                            tenantsSettings = await JObject.LoadAsync(reader);
                        }
                    }
                }
            }
            else
            {
                tenantsSettings = new JObject();
            }

            var settings = tenantsSettings.GetValue(tenant) as JObject ?? new JObject();

            foreach (var key in data.Keys)
            {
                if (data[key] != null)
                {
                    settings[key] = data[key];
                }
                else
                {
                    settings.Remove(key);
                }
            }

            tenantsSettings[tenant] = settings;

            using (var memoryStream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(memoryStream))
                {
                    using (var jsonWriter = new JsonTextWriter(streamWriter)
                    {
                        Formatting = Formatting.Indented
                    })
                    {
                        await tenantsSettings.WriteToAsync(jsonWriter);

                        await jsonWriter.FlushAsync();

                        memoryStream.Position = 0;
                        await _shellsFileStore.CreateFileFromStreamAsync(_tenantsBlobName, memoryStream);
                    }
                }
            }
        }
        public async Task SerializeAsync <TIn>(Stream outpuStream, TIn input)
        {
            using StreamWriter writer       = new StreamWriter(outpuStream, leaveOpen: true);
            using JsonTextWriter jsonWriter = new JsonTextWriter(writer);

            _jsonSerializer.Serialize(jsonWriter, input);
            await jsonWriter.FlushAsync();
        }
Example #25
0
        public async Task DoExportAsync(Stream outStream, Action <ExportImportProgressInfo> progressCallback, ICancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var progressInfo = new ExportImportProgressInfo {
                Description = "loading data..."
            };

            progressCallback(progressInfo);

            using (var sw = new StreamWriter(outStream, Encoding.UTF8))
            {
                using (var writer = new JsonTextWriter(sw))
                {
                    await writer.WriteStartObjectAsync();

                    progressInfo.Description = "Options are started to export";
                    progressCallback(progressInfo);

                    await writer.WritePropertyNameAsync("Options");

                    await writer.SerializeJsonArrayWithPagingAsync(_jsonSerializer, _batchSize, async (skip, take) =>
                    {
                        var searchCriteria  = AbstractTypeFactory <ThumbnailOptionSearchCriteria> .TryCreateInstance();
                        searchCriteria.Take = take;
                        searchCriteria.Skip = skip;
                        var searchResult    = await _optionSearchService.SearchAsync(searchCriteria);
                        return((GenericSearchResult <ThumbnailOption>)searchResult);
                    }, (processedCount, totalCount) =>
                    {
                        progressInfo.Description = $"{processedCount} of {totalCount} Options have been exported";
                        progressCallback(progressInfo);
                    }, cancellationToken);

                    progressInfo.Description = "Tasks are started to export";
                    progressCallback(progressInfo);

                    await writer.WritePropertyNameAsync("Tasks");

                    await writer.SerializeJsonArrayWithPagingAsync(_jsonSerializer, _batchSize, async (skip, take) =>
                    {
                        var searchCriteria  = AbstractTypeFactory <ThumbnailTaskSearchCriteria> .TryCreateInstance();
                        searchCriteria.Take = take;
                        searchCriteria.Skip = skip;
                        var searchResult    = await _taskSearchService.SearchAsync(searchCriteria);
                        return((GenericSearchResult <ThumbnailTask>)searchResult);
                    }, (processedCount, totalCount) =>
                    {
                        progressInfo.Description = $"{processedCount} of {totalCount} Tasks have been exported";
                        progressCallback(progressInfo);
                    }, cancellationToken);

                    await writer.WriteEndObjectAsync();

                    await writer.FlushAsync();
                }
            }
        }
 public async Task SerializeAsync <T>(Stream stream, T data)
 {
     using (var writer = new StreamWriter(stream))
         using (var jsonWriter = new JsonTextWriter(writer))
         {
             _serializer.Serialize(jsonWriter, data);
             await jsonWriter.FlushAsync();
         }
 }
Example #27
0
        public async Task SaveAsync(string tenant, IDictionary <string, string> data)
        {
            var appsettings = IFileStoreExtensions.Combine(null, _container, tenant, "appsettings.json");

            JObject config;
            var     fileInfo = await _shellsFileStore.GetFileInfoAsync(appsettings);

            if (fileInfo != null)
            {
                using (var stream = await _shellsFileStore.GetFileStreamAsync(appsettings))
                {
                    using (var streamReader = new StreamReader(stream))
                    {
                        using (var reader = new JsonTextReader(streamReader))
                        {
                            config = await JObject.LoadAsync(reader);
                        }
                    }
                }
            }
            else
            {
                config = new JObject();
            }

            foreach (var key in data.Keys)
            {
                if (data[key] != null)
                {
                    config[key] = data[key];
                }
                else
                {
                    config.Remove(key);
                }
            }

            using (var memoryStream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(memoryStream))
                {
                    using (var jsonWriter = new JsonTextWriter(streamWriter)
                    {
                        Formatting = Formatting.Indented
                    })
                    {
                        await config.WriteToAsync(jsonWriter);

                        await jsonWriter.FlushAsync();

                        memoryStream.Position = 0;
                        await _shellsFileStore.CreateFileFromStreamAsync(appsettings, memoryStream);
                    }
                }
            }
        }
        private async Task <T> SendCommandAsync <T>(string command, object[] parameters = null, bool noReturn = false, bool isArray = false, CancellationToken cancellation = default(CancellationToken))
        {
            parameters = parameters ?? Array.Empty <string>();
            using (Socket socket = await Connect())
            {
                using (var networkStream = new NetworkStream(socket))
                {
                    using (var textWriter = new StreamWriter(networkStream, UTF8, 1024 * 10, true))
                    {
                        using (var jsonWriter = new JsonTextWriter(textWriter))
                        {
                            var req = new JObject();
                            req.Add("id", 0);
                            req.Add("method", command);
                            req.Add("params", new JArray(parameters));
                            await req.WriteToAsync(jsonWriter, cancellation);

                            await jsonWriter.FlushAsync(cancellation);
                        }
                        await textWriter.FlushAsync();
                    }
                    await networkStream.FlushAsync(cancellation);

                    using (var textReader = new StreamReader(networkStream, UTF8, false, 1024 * 10, true))
                    {
                        using (var jsonReader = new JsonTextReader(textReader))
                        {
                            var resultAsync = JObject.LoadAsync(jsonReader, cancellation);

                            // without this hack resultAsync is blocking even if cancellation happen
                            using (cancellation.Register(() =>
                            {
                                socket.Dispose();
                            }))
                            {
                                var result = await resultAsync;
                                var error  = result.Property("error");
                                if (error != null)
                                {
                                    throw new LightningRPCException(error.Value["message"].Value <string>(), error.Value["code"].Value <int>());
                                }
                                if (noReturn)
                                {
                                    return(default(T));
                                }
                                if (isArray)
                                {
                                    return(result["result"].Children().First().Children().First().ToObject <T>());
                                }
                                return(result["result"].ToObject <T>());
                            }
                        }
                    }
                }
            }
        }
Example #29
0
        /// <summary>
        /// Serializes the given data to JSON
        /// </summary>
        /// <typeparam name="T">The type of data to serialize</typeparam>
        /// <param name="data">The data to serialize</param>
        /// <param name="stream">The stream to write the serialized data to</param>
        /// <returns>A task representing the completion of the serialization process</returns>
        public async Task Serialize <T>(T data, Stream stream)
        {
            var ser = new JsonSerializer();

            using var sw  = new StreamWriter(stream);
            using var jtw = new JsonTextWriter(sw);

            ser.Serialize(jtw, data);
            await jtw.FlushAsync();
        }
        protected override async Task WriteObject(Stream outputStream, System.Data.IDataRecord objectData, string[] fieldNames)
        {
            var streamWriter = new StreamWriter(outputStream, options.Encoding, 1024 * 8, leaveOpen: true);
            var jsonWriter   = new JsonTextWriter(streamWriter);

            WriteSingleRow(objectData, fieldNames, jsonWriter);
            await jsonWriter.FlushAsync();

            await streamWriter.FlushAsync();
        }