public override async Task WritePreambleAsync() { // Root object (start) _writer.WriteStartObject(); // Guild _writer.WriteStartObject("guild"); _writer.WriteString("id", Context.Guild.Id); _writer.WriteString("name", Context.Guild.Name); _writer.WriteString("iconUrl", Context.Guild.IconUrl); _writer.WriteEndObject(); // Channel _writer.WriteStartObject("channel"); _writer.WriteString("id", Context.Channel.Id); _writer.WriteString("type", Context.Channel.Type.ToString()); _writer.WriteString("category", Context.Channel.Category); _writer.WriteString("name", Context.Channel.Name); _writer.WriteString("topic", Context.Channel.Topic); _writer.WriteEndObject(); // Date range _writer.WriteStartObject("dateRange"); _writer.WriteString("after", Context.After); _writer.WriteString("before", Context.Before); _writer.WriteEndObject(); // Message array (start) _writer.WriteStartArray("messages"); await _writer.FlushAsync(); }
public async Task WriteIdentifiers(IEnumerable <GraphIdentifier> matches, Stream response) { var writer = new Utf8JsonWriter(response, new JsonWriterOptions() { Indented = true }); writer.WriteStartObject(); writer.WritePropertyName("matches"); writer.WriteStartArray(); foreach (var match in matches) { writer.WriteStartObject(); writer.WriteString("name", match.Name); writer.WriteString("kind", match.Kind); writer.WriteString("description", match.Description); writer.WriteString("namespace", match.Namespace); writer.WriteString("type", match.Type); writer.WriteString("version", match.Version.ToString()); writer.WriteEndObject(); } writer.WriteEndArray(); writer.WriteEndObject(); await writer.FlushAsync(); }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { if (writer == null) { writer = new Utf8JsonWriter(stream); } else { writer.Reset(stream); } writer.WriteStartArray(); foreach (var span in this.spans) { var zipkinSpan = span.ToZipkinSpan(this.exporter.LocalEndpoint, this.exporter.options.UseShortTraceIds); zipkinSpan.Write(writer); zipkinSpan.Return(); } writer.WriteEndArray(); return(writer.FlushAsync()); }
internal async Task <string> SerializeAsync() { using var stream = new MemoryStream(); using Utf8JsonWriter writer = new Utf8JsonWriter(stream); writer.WriteStartObject(); if (this.DueTime != null) { writer.WriteString("dueTime", ConverterUtils.ConvertTimeSpanValueInDaprFormat(this.DueTime)); } if (this.Period != null) { writer.WriteString("period", ConverterUtils.ConvertTimeSpanValueInDaprFormat(this.Period)); } if (this.Data != null) { writer.WriteString("data", Convert.ToBase64String(this.Data)); } writer.WriteEndObject(); await writer.FlushAsync(); return(Encoding.UTF8.GetString(stream.ToArray())); }
/// <summary>Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success.</summary> /// <param name="bot">BotClient</param> /// <param name="name">Sticker set name</param> /// <param name="userId">User identifier of the sticker set owner</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <returns>True</returns> public static async Task <bool> SetStickerSetThumbAsync(this BotClient bot, string name, long userId, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } if (userId == default) { throw new ArgumentNullException(nameof(userId)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteString(PropertyNames.Name, name); json.WriteNumber(PropertyNames.UserId, userId); json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <bool>(MethodNames.SetStickerSetThumb, stream, cancellationToken).ConfigureAwait(false)); }
public async Task Invoke(HttpContext context) { var telemetry = new TelemetryClient(new TelemetryConfiguration(_applicationInsights.InstrumentationKey)); telemetry.Context.Operation.Id = Guid.NewGuid().ToString(); var ex = context.Features.Get <IExceptionHandlerFeature>()?.Error; if (ex == null) { return; } telemetry.TrackException(ex); var problemDetails = new ProblemDetails { Title = "Internal Server Error", Status = StatusCodes.Status500InternalServerError, Instance = context.Request.Path.Value, Detail = ex.Message }; if (_webHostEnvironment.IsDevelopment()) { problemDetails.Detail += $": {ex.StackTrace}"; } context.Response.StatusCode = problemDetails.Status.Value; context.Response.ContentType = "application/problem+json"; using var writer = new Utf8JsonWriter(context.Response.Body); JsonSerializer.Serialize(writer, problemDetails); await writer.FlushAsync(); }
public async Task SendEvent(Events.EventBase @event) { using var m = new System.IO.MemoryStream(); using var writer = new Utf8JsonWriter(m); @event.WriteJson(writer); await writer.FlushAsync(); var frame = new MaxLib.WebServer.WebSocket.Frame() { OpCode = MaxLib.WebServer.WebSocket.OpCode.Text, Payload = m.ToArray(), FinalFrame = true, }; var sendQueue = new List <Task>(connections.Count); lockConnections.EnterReadLock(); foreach (var connection in connections) { sendQueue.Add(Task.Run(async() => await connection.SendFrame(frame))); } lockConnections.ExitReadLock(); await Task.WhenAll(sendQueue); }
private static async Task WriteResponse(HttpContext context, HealthReport result) { context.Response.ContentType = "application/json"; using var memoryStream = new MemoryStream(); using var jsonWriter = new Utf8JsonWriter(memoryStream, new JsonWriterOptions { Indented = true }); jsonWriter.WriteStartObject(); jsonWriter.WriteString("status", result.Status.ToString()); jsonWriter.WriteStartArray("results"); foreach (var entry in result.Entries) { jsonWriter.WriteStartObject(); jsonWriter.WriteStartObject(entry.Key); jsonWriter.WriteString("status", entry.Value.Status.ToString()); jsonWriter.WriteEndObject(); jsonWriter.WriteEndObject(); } jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); await jsonWriter.FlushAsync(); var json = Encoding.UTF8.GetString(memoryStream.ToArray()); await context.Response.WriteAsync(json); }
private async Task SerializeInternalAsync(IEnumerable <RpcResponse> responses, bool isBulkRequest, Stream stream) { var jsonWriter = new Utf8JsonWriter(stream); try { if (isBulkRequest) { jsonWriter.WriteStartArray(); foreach (RpcResponse response in responses) { this.SerializeResponse(response, jsonWriter); } jsonWriter.WriteEndArray(); } else { this.SerializeResponse(responses.Single(), jsonWriter); } } finally { await jsonWriter.FlushAsync(); await jsonWriter.DisposeAsync(); } }
public ActionResult Get() { // NOTE: We need this for now since `Utf8JsonWriter` will // unconditionally issue a synchronous `Flush`, even if there's // no data. Once we can call `DisposeAsync` this can go away AllowSynchronousIO(); var outerReader = _store.BeginRead(); return(Defer(async ctx => { var body = ctx.Response.Body; using var reader = outerReader; using var writer = new Utf8JsonWriter(body); writer.WriteStartArray(); foreach (var outerData in reader.Data()) { using var data = outerData; data.WriteAsValue(writer); } writer.WriteEndArray(); await writer.FlushAsync(ctx.RequestAborted); })); }
/// <summary> /// Executes the query and returns a JSON string from data set returned by the query asynchronously. /// </summary> /// <param name="dataCommand">The data command.</param> /// <param name="options">The <see cref="JsonWriterOptions"/> options.</param> /// <returns>A JSON string representing the <see cref="IDataReader"/> result of the command.</returns> public static async Task <string> QueryJsonAsync(this IDataCommand dataCommand, JsonWriterOptions options = default) { using var stream = new MemoryStream(); await using var writer = new Utf8JsonWriter(stream, options); writer.WriteStartArray(); await dataCommand.ReadAsync(reader => { while (reader.Read()) { writer.WriteStartObject(); for (int index = 0; index < reader.FieldCount; index++) { var name = reader.GetName(index); writer.WritePropertyName(name); WriteValue(reader, writer, index); } writer.WriteEndObject(); } }); writer.WriteEndArray(); await writer.FlushAsync(); return(Encoding.UTF8.GetString(stream.ToArray())); }
protected override async Task WriteCurrentResultSet(Stream outputStream, DbDataReader rdr, string[] fieldNamesToUse, bool?firstReadResult) { if (options.Encoding.BodyName != "utf-8") { throw new NotSupportedException("Only utf8 is supported"); } Type[] types = GetTypesFromReader(rdr); var jsonWriter = new Utf8JsonWriter(outputStream); jsonWriter.WriteStartArray(); if (firstReadResult == null) { firstReadResult = rdr.Read(); } if (firstReadResult == true) { do { WriteSingleRow(rdr, fieldNamesToUse, types, jsonWriter); }while (rdr.Read()); } jsonWriter.WriteEndArray(); await jsonWriter.FlushAsync(); }
/// <summary>Use this method to pin a message in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the channel. Returns True on success.</summary> /// <param name="bot">BotClient</param> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername).</param> /// <param name="messageId">Identifier of a message to pin.</param> /// <param name="disableNotification">Optional. Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public static async Task <bool> PinChatMessageAsync(this BotClient bot, long chatId, int messageId, [Optional] bool?disableNotification, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteNumber(PropertyNames.ChatId, chatId); json.WriteNumber(PropertyNames.MessageId, messageId); if (disableNotification != null) { json.WriteBoolean(PropertyNames.DisableNotification, (bool)disableNotification); } json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <bool>(MethodNames.PinChatMessage, stream, cancellationToken).ConfigureAwait(false)); }
/// <summary>Use this method to forward messages of any kind. Service messages can't be forwarded. On success, the sent Message is returned.</summary> /// <param name="api">The bot client.</param> /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername).</param> /// <param name="fromChatId">Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername).</param> /// <param name="messageId">Message identifier in the chat specified in from_chat_id.</param> /// <param name="disableNotification">Sends the message silently. Users will receive a notification with no sound.</param> /// <param name="protectContent">Protects the contents of the forwarded message from forwarding and saving.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public static async Task <Message> ForwardMessageAsync(this BotClient api, string chatId, string fromChatId, int messageId, [Optional] bool?disableNotification, [Optional] bool?protectContent, [Optional] CancellationToken cancellationToken) { if (api == null) { throw new ArgumentNullException(nameof(api)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteString(PropertyNames.ChatId, chatId); json.WriteString(PropertyNames.FromChatId, fromChatId); json.WriteNumber(PropertyNames.MessageId, messageId); if (disableNotification is not null) { json.WriteBoolean(PropertyNames.DisableNotification, (bool)disableNotification); } if (protectContent is not null) { json.WriteBoolean(PropertyNames.ProtectContent, (bool)protectContent); } json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await api.RPCA <Message>(MethodNames.ForwardMessage, stream, cancellationToken).ConfigureAwait(false)); }
public async Task ExecuteAsync(ControllerActionDescriptor action, HttpContext context) { var(executor, microtype) = SelectExecutor(action, context); var response = context.Response; response.StatusCode = StatusCodes.Status200OK; response.ContentType = $"application/vnd.microtype-container+json;introspection={this.Identifier};" + $"content={microtype.Identifier}"; await response.StartAsync(); var writer = new Utf8JsonWriter(response.Body, _options.JsonWriterOptions); writer.WriteStartObject(); writer.WritePropertyName("data"); await executor.ExecuteAsync(action, writer, _options.JsonSerializerOptions); writer.WriteStartObject("meta"); writer.WriteEndObject(); writer.WriteEndObject(); await writer.FlushAsync(); await response.CompleteAsync(); }
/// <summary>Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.</summary> /// <param name="bot">Bot Client</param> /// <param name="dropPendingUpdates">Pass True to drop all pending updates.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public static async Task <bool> DeleteWebhookAsync(this BotClient bot, [Optional] bool?dropPendingUpdates, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } if (dropPendingUpdates != null) { var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream); json.WriteStartObject(); json.WriteBoolean(PropertyNames.DropPendingUpdates, (bool)dropPendingUpdates); json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <bool>(MethodNames.DeleteWebhook, stream, cancellationToken).ConfigureAwait(false)); } else { return(await bot.RPCA <bool>(MethodNames.DeleteWebhook, cancellationToken).ConfigureAwait(false)); } }
/// <summary>Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.</summary> /// <param name="bot">BotClient</param> /// <param name="chatId">Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername).</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public static async Task <bool> DeleteChatStickerSetAsync( this BotClient bot, string chatId, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter( stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteString(PropertyNames.ChatId, chatId); json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <bool>( "deleteChatStickerSet", stream, cancellationToken).ConfigureAwait(false)); }
private async Task OnClientAuthenticated(OpenIdAuthenticatedContext context) { var userManager = context.HttpContext.RequestServices.GetService <SteamUsersController>(); var steamId = ulong.Parse(new Uri(context.Identifier).Segments.Last()); if (userManager != null && !await userManager.IsRegisteredAsync(steamId.ToString())) { await userManager.RegisterUserAsync(steamId.ToString()); } if (userManager != null && context.UserPayload != null) { await using var stream = new MemoryStream(); var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); context.UserPayload.RootElement.GetProperty("response").GetProperty("players").WriteTo(writer); await writer.FlushAsync(); var json = Encoding.UTF8.GetString(stream.ToArray()); var response = JsonConvert.DeserializeObject <SteamResponseModel>(json); foreach (var player in response.Players) { await userManager.UpdateUserAsync(player); } } context.Identity.AddClaim(new Claim("steamID", steamId.ToString())); var identity = new ClaimsPrincipal(context.Identity); context.HttpContext.User = identity; }
public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { if (!context.ModelState.IsValid || _domainNotification.HasNotifications) { var validations = !context.ModelState.IsValid ? NewtonsoftJson.JsonConvert.SerializeObject(context.ModelState.Values .SelectMany(x => x.Errors) .Select(x => x.ErrorMessage)) : NewtonsoftJson.JsonConvert.SerializeObject(_domainNotification.Notifications .Select(x => x.Value)); var problemDetails = new ProblemDetails { Title = "Bad Request", Status = StatusCodes.Status400BadRequest, Instance = context.HttpContext.Request.Path.Value, Detail = validations }; context.HttpContext.Response.StatusCode = problemDetails.Status.Value; context.HttpContext.Response.ContentType = "application/problem+json"; using var writer = new Utf8JsonWriter(context.HttpContext.Response.Body); JsonSerializer.Serialize(writer, problemDetails); await writer.FlushAsync(); return; } await next(); }
private static Task WriteResponse(HttpContext context, HealthReport result) { context.Response.ContentType = "application/json; charset=utf-8"; using var writer = new Utf8JsonWriter(context.Response.BodyWriter); writer.WriteStartObject(); writer.WriteString("status", result.Status.ToString()); writer.WriteStartObject("results"); foreach (var entry in result.Entries) { writer.WriteStartObject(entry.Key); writer.WriteString("status", entry.Value.Status.ToString()); writer.WriteString("description", entry.Value.Description); writer.WriteStartObject("data"); foreach (var item in entry.Value.Data) { writer.WritePropertyName(item.Key); JsonSerializer.Serialize( writer, item.Value, item.Value?.GetType() ?? typeof(object)); } writer.WriteEndObject(); writer.WriteEndObject(); } writer.WriteEndObject(); writer.WriteEndObject(); return(writer.FlushAsync()); }
public override async void Write( Utf8JsonWriter writer, TimerInfo value, JsonSerializerOptions options) { using var stream = new MemoryStream(); writer.WriteStartObject(); if (value.DueTime != default) { writer.WriteString("dueTime", ConverterUtils.ConvertTimeSpanValueInDaprFormat(value.DueTime)); } if (value.Period != default && value.Period >= TimeSpan.Zero) { writer.WriteString("period", ConverterUtils.ConvertTimeSpanValueInDaprFormat(value.Period)); } if (value.Data != null) { writer.WriteString("data", Convert.ToBase64String(value.Data)); } if (value.Callback != null) { writer.WriteString("callback", value.Callback); } writer.WriteEndObject(); await writer.FlushAsync(); }
/// <summary>Use this method to ban a channel chat in a supergroup or a channel. The owner of the chat will not be able to send messages and join live streams on behalf of the chat, unless it is unbanned first. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights.</summary> /// <param name="bot">BotClient</param> /// <param name="chatId">Unique identifier for the target chat or username of the target channel (in the format @channelusername)</param> /// <param name="senderChatId">Unique identifier of the target sender chat</param> /// <param name="untilDate">Date when the sender chat will be unbanned, unix time. If the chat is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <returns>True on success.</returns> public static async Task <bool> BanChatSenderChatAsync(this BotClient bot, long chatId, long senderChatId, [Optional] uint?untilDate, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteNumber(PropertyNames.ChatId, chatId); json.WriteNumber(PropertyNames.SenderChatId, senderChatId); if (untilDate != null) { json.WriteNumber(PropertyNames.UntilDate, (uint)untilDate); } json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <bool>(MethodNames.BanChatSenderChat, stream, cancellationToken).ConfigureAwait(false)); }
protected override async Task WriteResponseBodyAsync(MultiplicationTable table, OutputFormatterWriteContext context, Encoding encoding, CancellationToken cancellationToken) { using var writer = new Utf8JsonWriter(context.HttpContext.Response.Body); writer.WriteStartArray(); await foreach (var row in table.WithCancellation(cancellationToken)) { writer.WriteStartArray(); await foreach (var cell in row) { if (cell.HasValue) { writer.WriteNumberValue(cell.Value); } else { writer.WriteNullValue(); } } writer.WriteEndArray(); } writer.WriteEndArray(); await writer.FlushAsync(); }
public async Task Can_format_payload_with_multiple_fields_correctly() { // Arrange await using var ms = new MemoryStream(); await using var jsonWriter = new Utf8JsonWriter(ms); var fields = new Dictionary <string, object> { { "field1key", "field1value" }, { "field2key", 2 }, { "field3key", false } }; var timestamp = new DateTime(2017, 1, 1, 1, 1, 1, DateTimeKind.Utc); var point = new DatadogPoint(null, "measurement", fields, MetricTags.Empty, new DefaultDatadogMetricJsonWriter(), FlushInterval, timestamp); // Act jsonWriter.WriteStartArray(); await point.Write(jsonWriter); jsonWriter.WriteEndArray(); await jsonWriter.FlushAsync(); var result = Encoding.UTF8.GetString(ms.ToArray()); // Assert result.Should().Be("[{\"metric\":\"measurement.field1key\",\"points\":[[1483232461,0]],\"type\":\"gauge\",\"tags\":[]},{\"metric\":\"measurement.field2key\",\"points\":[[1483232461,2]],\"type\":\"gauge\",\"tags\":[]},{\"metric\":\"measurement.field3key\",\"points\":[[1483232461,0]],\"type\":\"gauge\",\"tags\":[]}]"); }
public async Task Invoke(HttpContext context) { var exception = context.Features.Get <IExceptionHandlerFeature>()?.Error; if (exception == null) { return; } var problemDetails = new ProblemDetails { Title = "Internal Server Error", Status = StatusCodes.Status500InternalServerError, Instance = context.Request.Path.Value, Detail = exception.InnerException == null ? $"{exception.Message}" : $"{exception.Message} | {exception.InnerException}" }; if (_webHostEnvironment.IsDevelopment()) { problemDetails.Detail += $": {exception.StackTrace}"; } context.Response.StatusCode = problemDetails.Status.Value; context.Response.ContentType = "application/problem+json"; using var writer = new Utf8JsonWriter(context.Response.Body); JsonSerializer.Serialize(writer, problemDetails); await writer.FlushAsync(); }
public async Task GetSafe2InfinityAsync(long count) { Response.Headers.Add("Content-Type", "application/json"); Response.Headers.Add("Charset", "utf-8"); var writer = new Utf8JsonWriter(Response.Body); try { var i = 1; writer.WriteStartArray(); //await writer.FlushAsync(); await foreach (var model in GenerateModelsAsync(count)) { writer.WriteStartObject(); writer.WriteString("index", model.Index.ToString()); writer.WriteString("a", model.A.ToString()); writer.WriteString("b", model.B.ToString()); writer.WriteString("c", model.C); writer.WriteEndObject(); i++; if (i % 10000 == 0) { await writer.FlushAsync(); } } writer.WriteEndArray(); //await writer.FlushAsync(); } finally { await writer.DisposeAsync(); } }
/// <summary>Use this method to unban a previously kicked user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.</summary> /// <param name="bot">BotClient</param> /// <param name="chatId">Unique identifier for the target group or username of the target supergroup or channel (in the format @username).</param> /// <param name="userId">Unique identifier of the target user.</param> /// <param name="onlyIfBanned">Do nothing if the user is not banned</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public static async Task <bool> UnbanChatMemberAsync(this BotClient bot, long chatId, long userId, [Optional] bool?onlyIfBanned, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteNumber(PropertyNames.ChatId, chatId); json.WriteNumber(PropertyNames.UserId, userId); if (onlyIfBanned != null) { json.WriteBoolean(PropertyNames.OnlyIfBanned, (bool)onlyIfBanned); } json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <bool>(MethodNames.UnbanChatMember, stream, cancellationToken).ConfigureAwait(false)); }
/// <summary>Use this method to get a list of profile pictures for a user.</summary> /// <param name="bot">BotClient</param> /// <param name="userId">Unique identifier of the target user.</param> /// <param name="offset">Sequential number of the first photo to be returned. By default, all photos are returned.</param> /// <param name="limit">Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100.</param> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> /// <returns>UserProfilePhotos Object.</returns> public static async Task <UserProfilePhotos> GetUserProfilePhotosAsync( this BotClient bot, long userId, [Optional] int?offset, [Optional] ushort?limit, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteNumber(PropertyNames.UserId, userId); if (offset != null) { json.WriteNumber(PropertyNames.Offset, (int)offset); } if (limit != null) { json.WriteNumber(PropertyNames.Limit, (ushort)limit); } json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <UserProfilePhotos>(MethodNames.GetUserProfilePhotos, stream, cancellationToken).ConfigureAwait(false)); }
/// <summary>Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.</summary> /// <param name="bot">Bot Client</param> /// <param name="preCheckoutQueryId">Unique identifier for the query to be answered.</param> /// <param name="ok">Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.</param> /// <param name="errorMessage">Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.</param> /// <returns>On success, True is returned.</returns> /// <param name="cancellationToken">The cancellation token to cancel operation.</param> /// <exception cref="BotRequestException">Thrown when a request to Telegram Bot API got an error response.</exception> /// <exception cref="ArgumentNullException">Thrown when a required parameter is null.</exception> public static async Task <bool> AnswerPreCheckoutQueryAsync(this BotClient bot, string preCheckoutQueryId, bool ok, [Optional] string errorMessage, [Optional] CancellationToken cancellationToken) { if (bot == default) { throw new ArgumentNullException(nameof(bot)); } var stream = new MemoryStream(); using var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); json.WriteStartObject(); json.WriteString("pre_checkout_query_id", preCheckoutQueryId); json.WriteBoolean("ok", ok); if (!ok) { if (errorMessage == default) { throw new ArgumentNullException(nameof(errorMessage)); } json.WriteString("error_message", errorMessage); } json.WriteEndObject(); await json.FlushAsync(cancellationToken).ConfigureAwait(false); await json.DisposeAsync().ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); return(await bot.RPCA <bool>(MethodNames.AnswerPreCheckoutQuery, stream, cancellationToken).ConfigureAwait(false)); }
private static void RenderJSON(OpenApiUrlSpaceNode urlspace, Stream outfile) { var writer = new Utf8JsonWriter(outfile); RenderJSON(writer, urlspace); writer.FlushAsync(); }