public Alert(JObject simpleAlert, int id, Task <JObject?> task) { SimpleAlert = simpleAlert; Id = id; Task = task; FullAlert = null; }
public StartWorkflowArgs(StateMachine definition, JObject?input, ObservableAction[]?actions, string?telemetryUri) { this.Definition = definition ?? throw new ArgumentNullException(nameof(definition)); this.Input = input; this.Actions = actions; this.TelemetryUri = telemetryUri; }
public AppearancePayload(Coordinates coordinates, uint state, bool isInMultiAction, JObject?settings = null) { Coordinates = coordinates; State = state; IsInMultiAction = isInMultiAction; Settings = settings; }
private static Color?ReadObject(JObject?obj, string path) { if (obj is null) { return(null); } try { if (!obj.TryGetValueIgnoreCase("R", out int R) || !obj.TryGetValueIgnoreCase("G", out int G) || !obj.TryGetValueIgnoreCase("B", out int B) ) { return(null); } if (obj.TryGetValueIgnoreCase("A", out int A)) { return(new Color(R, G, B, A)); } return(new Color(R, G, B)); } catch (Exception ex) { throw new JsonReaderException($"Can't parse Color? from JSON object node (path: {path}).", ex); } }
private static bool tryReadParseFile(string key, [NotNullWhen(true)] out JObject?data) { data = null; var path = Combine( Folder, $"{key}.json" ); if (!File.Exists(path)) { return(false); } string?fileText = null; try { fileText = File.ReadAllText(path); } catch { } if (fileText.IsNullOrWhitespace()) { return(false); } try { data = JObject.Parse(fileText); } catch { } return(!(data is null)); }
public string ToDescription(JObject?jObject = null, bool disableSettingsHints = false) { if (!string.IsNullOrWhiteSpace(ErrorMessage)) { return(ErrorMessage); } var authMessage = disableSettingsHints ? $" Please confirm you are using a Personal Access Token authorized {HttpJsonClient.AuthMessageScope}." : $" Please confirm the Personal Access Token is configured correctly in Azure DevOps Issue Tracker settings, and is authorized {HttpJsonClient.AuthMessageScope}."; if (SignInPage) { return("The server returned a sign-in page." + authMessage); } var description = $"{(int) HttpStatusCode} ({HttpStatusCode})."; var bodyMessage = jObject?["message"]?.ToString(); if (!string.IsNullOrWhiteSpace(bodyMessage)) { description += $" \"{bodyMessage}\""; } if (HttpStatusCode == HttpStatusCode.Unauthorized) { description += authMessage; } return(description); }
internal static IEnumerable <JProperty> PropertiesOf(this JToken?token, string?key = null) { JObject?obj = token as JObject; if (obj == null) { return(Array.Empty <JProperty>()); } if (key != null) { JToken?element; if (!obj.TryGetValue(key, StringComparison.OrdinalIgnoreCase, out element)) { return(Array.Empty <JProperty>()); } obj = element as JObject; } if (obj == null) { return(Array.Empty <JProperty>()); } return(obj.Properties()); }
internal static string?ToString(this JToken?token, string?key) { if (key == null) { if (token == null || token.Type != JTokenType.String) { return(null); } return(token.ToString()); } JObject?obj = token as JObject; if (obj == null) { return(null); } JToken?element; if (!obj.TryGetValue(key, StringComparison.OrdinalIgnoreCase, out element) || element.Type != JTokenType.String) { return(null); } return(element.ToString()); }
public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.HttpContext.Request.Method.Equals(HttpMethod.Get.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return; } if (TryModelBindFromHttpContextItems(bindingContext)) { return; } var strJson = await bindingContext.HttpContext.Request.GetRawBodyStringAsync(); if (string.IsNullOrWhiteSpace(strJson)) { return; } JObject?json = JsonConvert.DeserializeObject <JObject>(strJson); //if no explicit json path then use the model name JToken?match = json?.SelectToken(bindingContext.FieldName ?? bindingContext.ModelName); if (match == null) { return; } var model = match.ToObject(bindingContext.ModelType); bindingContext.Result = ModelBindingResult.Success(model); }
async Task <ExecutionResult> Execute(string query, string?operationName, JObject?variables, CancellationToken cancellation) { var options = new ExecutionOptions { Schema = schema, Query = query, OperationName = operationName, Inputs = variables?.ToInputs(), CancellationToken = cancellation, #if (DEBUG) ThrowOnUnhandledException = true, EnableMetrics = true, #endif }; var executeAsync = await executer.ExecuteAsync(options); return(new ExecutionResult { Data = executeAsync.Data, Errors = executeAsync.Errors }); }
public async Task UploadMultipleFiles() { JObject?linkToUpload = await Api.Get <JObject>("/upload", _token); JObject?[] uploadedFiles = await Api.Post <JObject>( $"https:{linkToUpload?["uploadLink"]}", new[] { Path.Join(_directoryProjectPath, "images", "cat.jpg"), Path.Join(_directoryProjectPath, "images", "dog_hello.gif") } ); Assert.True(uploadedFiles.Length == 2); const string actual1 = "cat.jpg"; string? expected1 = uploadedFiles[0]?["files"]?[0]?["name"]?.ToString(); Assert.AreEqual(expected1, actual1); Assert.IsTrue(!string.IsNullOrEmpty((string)uploadedFiles[0]?["files"]?[0]?["url"])); Assert.IsTrue(!string.IsNullOrEmpty((string)uploadedFiles[0]?["files"]?[0]?["deleteUrl"])); const string actual2 = "dog_hello.gif"; string? expected2 = uploadedFiles[1]?["files"]?[0]?["name"]?.ToString(); Assert.AreEqual(expected2, actual2); Assert.IsTrue(!string.IsNullOrEmpty((string)uploadedFiles[0]?["files"]?[0]?["url"])); Assert.IsTrue(!string.IsNullOrEmpty((string)uploadedFiles[0]?["files"]?[0]?["deleteUrl"])); }
public async Task <IMergeGraphSyncer?> SyncEmbedded(ContentItem contentItem) { _logger.LogDebug("Syncing embedded {ContentItem}.", contentItem.ToString()); JObject?graphSyncPartContent = (JObject?)contentItem.Content[nameof(GraphSyncPart)]; if (graphSyncPartContent == null) { return(null); } var embeddedMergeContext = _graphMergeContext !.ChildContexts .Single(c => c.ContentItem.ContentItemId == contentItem.ContentItemId); _logger.LogDebug("Found existing GraphMergeContext for {ContentItem}.", contentItem.ToString()); var embeddedMergeGraphSyncer = (MergeGraphSyncer)embeddedMergeContext.MergeGraphSyncer; if (!embeddedMergeGraphSyncer._syncNameProvider.GraphSyncPartSettings.PreexistingNode) { await((MergeGraphSyncer)embeddedMergeContext.MergeGraphSyncer).SyncEmbedded(); } return(embeddedMergeGraphSyncer); }
public async ValueTask <bool> MoveNextAsync() { _cancellationToken.ThrowIfCancellationRequested(); if (_jsonReader == null) { _query ??= _cosmosClientWrapper.CreateQuery(_containerId, _partitionKey, _cosmosSqlQuery); if (!_query.HasMoreResults) { _current = null; return(false); } _responseMessage = await _query.ReadNextAsync(_cancellationToken).ConfigureAwait(false); _responseMessage.EnsureSuccessStatusCode(); _responseStream = _responseMessage.Content; _reader = new StreamReader(_responseStream); _jsonReader = CreateJsonReader(_reader); } if (TryReadJObject(_jsonReader, out var jObject)) { _current = jObject; return(true); } await ResetReadAsync().ConfigureAwait(false); return(await MoveNextAsync().ConfigureAwait(false)); }
/// <summary> /// Deletes a whitelist entry /// </summary> /// <returns></returns> public async Task <bool> DeleteWhiteListEntryAsync(string entry) { CheckInitialized(); HttpClient client = await GetHttpClient().ConfigureAwait(false); var response = await client.DeleteAsync(new Uri(string.Format("{0}config/whitelist/{1}", ApiBase, entry))).ConfigureAwait(false); var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false); JArray jresponse = JArray.Parse(stringResponse); JObject?result = (JObject?)jresponse.First; if (result != null && result.TryGetValue("error", out JToken? error)) { if (error?["type"]?.Value <int>() == 3) // entry not available { return(false); } else { throw new HueException(error?["description"]?.Value <string>()); } } return(true); }
private void SaveJson(JsonConfigurationProvider?provider, JObject?json) { if (provider is null) { return; } lock (_locker) { if (provider.Source.FileProvider is PhysicalFileProvider physicalFileProvider) { var jsonFilePath = Path.Combine(physicalFileProvider.Root, provider.Source.Path); try { using (var sw = new StreamWriter(jsonFilePath, false)) using (var jsonTextWriter = new JsonTextWriter(sw) { Formatting = Formatting.Indented, }) { json?.WriteTo(jsonTextWriter); } } catch (IOException exception) { _logger.LogWarning(exception, "JSON configuration could not be written: {path}", jsonFilePath); } } } }
public bool MoveNext() { if (_jsonReader == null) { _query ??= _cosmosClientWrapper.CreateQuery(_containerId, _partitionKey, _cosmosSqlQuery); if (!_query.HasMoreResults) { _current = null; return(false); } _responseMessage = _query.ReadNextAsync().GetAwaiter().GetResult(); _responseMessage.EnsureSuccessStatusCode(); _responseStream = _responseMessage.Content; _reader = new StreamReader(_responseStream); _jsonReader = CreateJsonReader(_reader); } if (TryReadJObject(_jsonReader, out var jObject)) { _current = jObject; return(true); } ResetRead(); return(MoveNext()); }
public static async Task <Fortune?> GetFortuneCookie() { var live = new HttpClient(); try { var res = await live.GetAsync(FortuneRequest); var response = await res.Content.ReadAsStringAsync(); var array = JArray.Parse(response); JObject?data = array[0].ToObject <JObject>(); if (data is null) { return(null); } return(new Fortune(data)); } catch { return(null); } }
/// <summary> /// 输出自定义类型 /// </summary> /// <param name="type"></param> /// <param name="info"></param> public Result(ContentType type, object info) : this(HttpStatusCode.OK, 0, null, info) { this.Success = (int)type; this.Message = null; this.Info = info; this.IsException = false; if (this.Type == null) { return; } switch (this.Type.Value) { case ContentType.Result: try { JObject?obj = JObject.Parse((string)this.Info); if (obj != null) { this.Success = obj["success"]?.Value <int>() ?? 0; this.Message = obj["msg"]?.Value <string>(); this.Info = obj["info"]; } } catch { this.Success = 0; this.Message = (string?)this.Info; } break; } }
internal BlobTemplateParameter(JObject jObject) { string?name = jObject.ToString(nameof(Name)); if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException($"{nameof(Name)} property should not be null or whitespace", nameof(jObject)); } Name = name !; DataType = jObject.ToString(nameof(DataType)) ?? "string"; if (DataType.Equals("choice", StringComparison.OrdinalIgnoreCase)) { Dictionary <string, ParameterChoice> choices = new Dictionary <string, ParameterChoice>(StringComparer.OrdinalIgnoreCase); JObject?cdToken = jObject.Get <JObject>(nameof(Choices)); if (cdToken != null) { foreach (JProperty cdPair in cdToken.Properties()) { choices.Add( cdPair.Name.ToString(), new ParameterChoice( cdPair.Value.ToString(nameof(ParameterChoice.DisplayName)), cdPair.Value.ToString(nameof(ParameterChoice.Description)))); } } Choices = choices; } Priority = jObject.ToEnum <TemplateParameterPriority>(nameof(Priority)); DefaultIfOptionWithoutValue = jObject.ToString(nameof(DefaultIfOptionWithoutValue)); Description = jObject.ToString(nameof(Description)); AllowMultipleValues = jObject.ToBool(nameof(AllowMultipleValues)); }
public Task <(bool, string)> ValidateCreate(JObject term, JObject taxonomy) { ContentItem?termContentItem = term.ToObject <ContentItem>(); if (termContentItem == null) { throw new InvalidOperationException("You must provide a term"); } if (termContentItem.Content.PageLocation == null) { return(Task.FromResult((true, string.Empty))); } if (termContentItem.DisplayText.Trim() != "/") { return(Task.FromResult((true, string.Empty))); } JObject?parent = _taxonomyHelper.FindParentTaxonomyTerm(term, taxonomy); if (parent == null) { throw new InvalidOperationException($"Could not find parent taxonomy term for {term}"); } if (parent.ToObject <ContentItem>()?.ContentType == ContentTypes.Taxonomy) { return(Task.FromResult((true, string.Empty))); } return(Task.FromResult((false, "'/' is not a valid Title for this page location"))); }
public async Task <IActionResult> StartStateMachine( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "statemachine/{instanceId}")] HttpRequest req, [DurableClient] IDurableClient client, string instanceId, ILogger log) { StateMachine?workflow = null; JObject? input = null; ObservableAction[]? actions = null; if (req.ContentLength != 0) { var json = JObject.Parse(await req.ReadAsStringAsync()); workflow = json.Property("workflow")?.Value.ToObject <StateMachine>(); input = (JObject)(json.Property("input")?.Value ?? new JObject()); actions = json.Property("actions")?.Value.ToObject <ObservableAction[]>(); } if (workflow == null) { return(new BadRequestObjectResult("Unable to deserialize state machine definition in request payload.")); } var args = new StartWorkflowArgs(workflow, input, actions, _config["TELEMETRY_URI"]); await client.StartWorkflowAsync(args, instanceId); log.LogInformation($"Started new workflow '{workflow.Name}' with ID = '{instanceId}."); return(client.CreateCheckStatusResponse(req, instanceId)); }
public override Task <Result> SendCommand(SessionId sessionId, string method, JObject?args, CancellationToken token) { if (args == null) { args = new JObject(); } var tcs = new TaskCompletionSource <Result>(); MessageId msgId; if (args["to"]?.Value <string>() is not string to_str) { throw new Exception($"No 'to' field found in '{args}'"); } msgId = new FirefoxMessageId("", 0, to_str); pending_cmds[msgId] = tcs; logger.LogTrace($"SendCommand: to: {args}"); var msg = args.ToString(Formatting.None); var bytes = Encoding.UTF8.GetBytes(msg); Send(bytes, token); return(tcs.Task); }
public Episode(int seriesId, JObject?bestLanguageR, JObject jsonInDefaultLang, CachedSeriesInfo si) : this(seriesId, si) { if (bestLanguageR is null) { LoadJson(jsonInDefaultLang); } else { //Here we have two pieces of JSON. One in local language and one in the default language (English). //We will populate with the best language first and then fill in any gaps with the backup Language LoadJson(bestLanguageR); //backupLanguageR should be a cachedSeries of name/value pairs (ie a JArray of JProperties) //TVDB asserts that name and overview are the fields that are localised string?epName = (string)jsonInDefaultLang["episodeName"]; if (string.IsNullOrWhiteSpace(mName) && epName != null) { mName = System.Web.HttpUtility.HtmlDecode(epName).Trim(); } string overviewFromJson = (string)jsonInDefaultLang["overview"]; if (string.IsNullOrWhiteSpace(Overview) && overviewFromJson != null) { Overview = System.Web.HttpUtility.HtmlDecode(overviewFromJson).Trim(); } } }
public async Task ContactUptobox() { const string uri = "/user/me"; JObject? json = await Api.Get <JObject>(uri, _token); Assert.AreEqual(json?["token"].ToString(), _token); }
public JObject?FindParentTaxonomyTerm(JObject termContentItem, JObject taxonomyContentItem) { JArray?terms = GetTerms(taxonomyContentItem); if (terms == null) { return(null); } if (terms.Any(x => (string?)x["ContentItemId"] == (string?)termContentItem["ContentItemId"])) { return(taxonomyContentItem); } JObject?result = null; foreach (JObject term in terms) { result = FindParentTaxonomyTerm(termContentItem, term); if (result != null) { return(result); } } return(null); }
public static void LoadFilters(string filterLoc = "filters.json") { try { using (StreamReader file = File.OpenText(filterLoc)) using (JsonTextReader reader = new JsonTextReader(file)) { config = (JObject)JToken.ReadFrom(reader); Log.Information(Strings.Get("LoadedFilters"), filterLoc); DumpFilters(); } if (config == null) { Log.Debug("Out of entries"); } } catch (Exception e) when ( e is UnauthorizedAccessException || e is ArgumentException || e is ArgumentNullException || e is PathTooLongException || e is DirectoryNotFoundException || e is FileNotFoundException || e is NotSupportedException) { config = null; //Let the user know we couldn't load their file Log.Warning(Strings.Get("Err_MalformedFilterFile"), filterLoc); return; } }
static string?GetStringProperty(JObject?obj, string name) { if (obj != null && obj.TryGetValue(name, out var value) && value.Type == JTokenType.String) { return((string)value !); } return(null); }
public TitleParametersPayload(Coordinates coordinates, uint state, string title, TitleParameters titleParameters, JObject?settings = null) { Coordinates = coordinates; State = state; Title = title; TitleParameters = titleParameters; Settings = settings; }
public byte[]? Convert(JObject?source, byte[]?destination, ResolutionContext context) { if (source == null || source.Type == JTokenType.None) { return(destination); } return(WriteToBytes(source)); }
public KeyPayload(Coordinates coordinates, uint state, uint userDesiredState, bool isInMultiAction, JObject?settings = null) { Coordinates = coordinates; State = state; UserDesiredState = userDesiredState; IsInMultiAction = isInMultiAction; Settings = settings; }