public void ProductWasCreated(Product product) { var intent = new Intent(common.Intents.PRODUCT_CREATED); var serializedProduct = _jsonService.Serialize <Product>(product); intent.PutExtra(common.Extras.PRODUCT, serializedProduct); _context.SendBroadcast(intent, common.Permissions.TriggerOnProductCreatedPermission.Name); }
public void NullSafeSet(IDbCommand cmd, object value, int index) { if (value == null) { ((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value; } else { ((IDataParameter)cmd.Parameters[index]).Value = _jsonService.Serialize(value); } }
/// <summary> /// Serialize the HTTP content to a stream as an asynchronous operation. /// </summary> /// <param name="stream">The target stream.</param> /// <param name="context">Information about the transport (channel binding token, for example). This parameter may be null.</param> /// <returns>The task object representing the asynchronous operation.</returns> protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { char[] chars = null; byte[] bytes = null; try { // TODO can be better, the following types can make sizeable allocations var stringBuilder = new StringBuilder(256); var stringWriter = new StringWriter(stringBuilder, CultureInfo.InvariantCulture); var jsonTextWriter = new JsonTextWriter(stringWriter); _jsonService.Serialize(jsonTextWriter, _invocationRequest); int numChars = stringBuilder.Length; chars = ArrayPool <char> .Shared.Rent(numChars); stringBuilder.CopyTo(0, chars, 0, numChars); int numBytes = Encoding.UTF8.GetByteCount(chars, 0, numChars); bytes = ArrayPool <byte> .Shared.Rent(numBytes); Encoding.UTF8.GetBytes(chars, 0, numChars, bytes, 0); await stream.WriteAsync(bytes, 0, numBytes).ConfigureAwait(false); } finally { if (bytes != null) { ArrayPool <byte> .Shared.Return(bytes); } if (chars != null) { ArrayPool <char> .Shared.Return(chars); } } // TODO Stream writer allocates both a char[] and a byte[] for buffering, it is slower than just serializing to string and writing the string to the stream // (at least for small-average size payloads). Support for ArrayPool buffers is coming - https://github.com/dotnet/corefx/issues/23874, might need to target // netcoreapp2.1 // using (var streamWriter = new StreamWriter(stream, UTF8NoBOM, 256, true)) // using (var jsonWriter = new JsonTextWriter(streamWriter)) // { // _jsonService.Serialize(jsonWriter, _invocationRequest); // }; if (_invocationRequest.ModuleSourceType == ModuleSourceType.Stream) { await stream.WriteAsync(BOUNDARY_BYTES, 0, BOUNDARY_BYTES.Length).ConfigureAwait(false); await _invocationRequest.ModuleStreamSource.CopyToAsync(stream).ConfigureAwait(false); } }
private string HandleAction(Func <object> action, string failMessage) { try { var result = action?.Invoke(); return(_jsonService.Serialize(new { success = true, result = result })); } catch (Exception e) { _logger.LogError(e, failMessage); if (_env.IsDevelopment()) { throw; } else { return(_jsonService.Serialize(new { success = false, message = failMessage, })); } } }
private async Task <string> GetJsonFromGraphEndpoint(string endpoint, Action <string> error) { string result; try { var c = this.credentials.GetCredentialsFromLocker(error); if (c != null) { using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", c.Token); var response = await httpClient.GetAsync(endpoint); if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsStringAsync(); } else { result = jsonService.Serialize(new { WebError = response.ReasonPhrase }); } } } else { result = jsonService.Serialize(new { AuthError = "You need to log in first!" }); } } catch (Exception e) { result = jsonService.Serialize(new { Exception = e.Message }); } return(result); }
public async Task <int> OnExecuteAsync(IConsole console) { var address = IPAddress.Parse(TargetDevice); if (ShowJson) { var bulb = new LightBulb(address); await bulb.FetchAsync().ConfigureAwait(false); console.WriteLine(_jsonService.Serialize(bulb)); } else { var desiredState = new RequestedBulbState(); SwitchState desiredSwitchState = SwitchState.Off; bool shouldToggleState = false; if (string.Equals(DesiredState, "toggle", StringComparison.InvariantCultureIgnoreCase)) { shouldToggleState = true; } else if (Enum.TryParse(DesiredState, true, out desiredSwitchState)) { desiredState.PowerState = desiredSwitchState; } else { throw new Exception("Invalid value for parameter \"state\"."); } if (Brightness != null) { desiredState.Brightness = Brightness; } var bulb = new LightBulb(address); if (shouldToggleState) { await bulb.FetchAsync().ConfigureAwait(false); desiredState.PowerState = bulb.State.PowerState == SwitchState.Off ? SwitchState.On : SwitchState.Off; } await bulb.TransitionStateAsync(desiredState).ConfigureAwait(false); } return(0); }
public async Task <int> OnExecuteAsync(IConsole console) { var address = IPAddress.Parse(TargetDevice); if (ShowJson) { var plug = new Plug(address); await plug.FetchAsync().ConfigureAwait(false); console.WriteLine(_jsonService.Serialize(plug)); } else { SwitchState desiredState = SwitchState.Off; bool shouldToggleState = false; if (string.Equals(DesiredState, "toggle", StringComparison.InvariantCultureIgnoreCase)) { shouldToggleState = true; } var plug = new Plug(address); if (shouldToggleState) { await plug.FetchAsync().ConfigureAwait(false); desiredState = plug.RelayState == SwitchState.Off ? SwitchState.On : SwitchState.Off; } else if (!Enum.TryParse(DesiredState, true, out desiredState)) { throw new Exception("Invalid value for parameter \"state\"."); } await plug.SetRelayStateAsync(desiredState).ConfigureAwait(false); } return(0); }
public static HttpResponseMessage Post <T>(this HttpClient client, IJsonService jsonService, string uri, T obj) { return(client.PostAsync(uri, new StringContent(jsonService.Serialize(obj), Encoding.UTF8, "application/json")) .GetAwaiter() .GetResult()); }
public Task <bool> Set <T>(string key, T data) => Database.StringSetAsync(key, _json.Serialize(data));
public async Task <HttpResponse> PostAsync <T>(string url, T content = default, Dictionary <string, string> formUrlEncoded = null, Dictionary <string, string> parameters = null, int timeout = 60, Dictionary <string, string> customHeaders = null) { try { if (Connectivity.NetworkAccess != NetworkAccess.Internet) { throw new NotConnectedException(); } _httpclient.Timeout = TimeSpan.FromSeconds(timeout); _httpclient.DefaultRequestHeaders.Clear(); if (customHeaders != null && customHeaders.Any()) { foreach (var customHeader in customHeaders) { _httpclient.DefaultRequestHeaders.Add(customHeader.Key, customHeader.Value); } } var parameter = string.Empty; var formencoded = string.Empty; var serialized = string.Empty; if (parameters != null) { parameter = parameters.Aggregate(parameter, (current, keyvalue) => current + $"{keyvalue.Key}={keyvalue.Value}&"); } if (formUrlEncoded != null) { formencoded = formUrlEncoded.Aggregate(formencoded, (current, keyvalue) => current + $"{keyvalue.Key}={keyvalue.Value}&"); serialized = formencoded; } var uriLink = !string.IsNullOrEmpty(parameter) ? $"{url}?{parameter}" : url; if (uriLink.EndsWith("&")) { uriLink = uriLink.Substring(0, uriLink.Length - 1); } if (content != null && content as string != string.Empty) { serialized = _jsonService.Serialize(content, Converter.Settings); // } if (serialized.EndsWith("&")) { serialized = serialized.Substring(0, serialized.Length - 1); } HttpContent httpContent = new StringContent(serialized, Encoding.UTF8, string.IsNullOrEmpty(formencoded) ? "application/json" : "application/x-www-form-urlencoded"); _httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(string.IsNullOrEmpty(formencoded) ? "application/json" : "application/x-www-form-urlencoded")); //httpContent.Headers.ContentType = new MediaTypeHeaderValue(string.IsNullOrEmpty(formencoded) ? "application/json" : "application/x-www-form-urlencoded"); var s = await _httpclient.PostAsync(uriLink.Replace(',', '.'), httpContent).ConfigureAwait(false); if (s.IsSuccessStatusCode) { var response = await s.Content.ReadAsStringAsync(); return(new HttpResponse() { ErrorMessage = string.Empty, Response = response, Success = true }); } return(new HttpResponse() { ErrorMessage = await s.Content.ReadAsStringAsync(), Response = string.Empty, Success = false }); } catch (TaskCanceledException exception) { Debug.WriteLine("**** TASK CANCELLED EXCEPTION." + exception); if (!exception.CancellationToken.IsCancellationRequested) { throw new TimeoutException( "The connection timed out; please check your internet connection and try again.", exception); } throw; } catch (JsonException exception) { Debug.WriteLine("**** JSON EXCEPTION." + exception); throw; } catch (Exception exception) { Debug.WriteLine("**** GENERAL EXCEPTION." + exception); throw; } }
/// <summary> /// Saves the data to the cache /// </summary> /// <typeparam name="T">The type of item to save</typeparam> /// <param name="data">The data to save</param> /// <param name="filename">The name of the cached item</param> /// <returns>A task representing the completion of the saved cache item</returns> public Task Save <T>(T data, string filename) { var str = _json.Serialize(data); return(File.WriteAllTextAsync(filename, str)); }