private static ParserResult ParseInternal(IEnumerable <Token> tokens, Resource?resource, Logger?logger) { if (tokens == null) { throw new ArgumentNullException(nameof(tokens)); } var context = new ParserContext { Tokens = new TokenQueue(tokens), Resource = resource }; if (context.Tokens.Count == 0) { return(ParserResult.Empty()); } if (logger != null) { context.Issues.CollectionChanged += (_, e) => IssuesChanged(logger, e); } var nodes = new List <SyntaxNode>(); while (context.Tokens.Count > 0) { nodes.Add(ParseBlock(context)); } return(new ParserResult(nodes, context.Issues)); }
public Task DuplicateClientsAreTheSameObject() { return(RunTest <Key, Resource>(async(context, pool) => { var key = new Key(0); await pool.UseAsync(context, key, async wrapper => { return await pool.UseAsync(context, key, wrapper2 => { wrapper.ReferenceCount.Should().Be(2); wrapper.Should().Be(wrapper2); return BoolResult.SuccessTask; }); }).ShouldBeSuccess(); Resource?cachedResource = null; await pool.UseAsync(context, key, wrapper => { cachedResource = wrapper.Value; return BoolResult.SuccessTask; }).ShouldBeSuccess(); await pool.UseAsync(context, key, wrapper => { Assert.Same(cachedResource, wrapper.Value); return BoolResult.SuccessTask; }).ShouldBeSuccess(); })); }
/// <inheritdoc/> public async Task <Resource> Create(Resource resource, string token) { HttpClient client = this.httpClientService.CreateDefaultHttpClient(); client.DefaultRequestHeaders.Accept.Clear(); client.BearerTokenAuthorization(token); string requestUrl = this.serverConfigurationDelegate.ServerConfiguration.ResourceRegistrationEndpoint; client.BaseAddress = new Uri(requestUrl); string jsonOutput = JsonSerializer.Serialize <Resource>(resource); using (HttpContent content = new StringContent(jsonOutput)) { HttpResponseMessage response = await client.PostAsync(new Uri(requestUrl), content).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { this.logger.LogError($"create() returned with StatusCode := {response.StatusCode}."); } string result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); Resource?resourceResponse = JsonSerializer.Deserialize <Resource>(result); return(resourceResponse !); } }
public OutputCompletionSource(Resource?resource) { _taskCompletionSource = new TaskCompletionSource <OutputData <T> >(); Output = new Output <T>( resource == null ? ImmutableHashSet <Resource> .Empty : ImmutableHashSet.Create(resource), _taskCompletionSource.Task); }
public static Field GetFromXmlElement(XmlElement elem) { Field result = null; if (elem.Name == xmlDefName) { string tstr = elem.GetAttribute(xmlTypeString); string xstr = elem.GetAttribute(xmlXString); string ystr = elem.GetAttribute(xmlYString); FieldType _type; int _x, _y; if (Enum.TryParse(tstr, out _type) && int.TryParse(xstr, out _x) && int.TryParse(ystr, out _y)) { result = new Field(_x, _y, _type); XmlElement holder = (XmlElement)elem.SelectSingleNode(xmlStackString); if (holder != null) { foreach (XmlElement reso in holder) { Resource?tmp = Resource.GetFromXmlElement(reso); if (tmp != null) { result.AddResource((Resource)tmp); } } } holder = (XmlElement)elem.SelectSingleNode(xmlBuildName); if (holder != null) { result.building = Building.GetFromXmlElement(holder); } } } return(result); }
private async Task LogAsync(LogSeverity severity, string message, Resource?resource, int?streamId, bool?ephemeral) { try { var urn = await TryGetResourceUrnAsync(resource).ConfigureAwait(false); await _engine.LogAsync(new LogRequest { Severity = severity, Message = message, Urn = urn, StreamId = streamId ?? 0, Ephemeral = ephemeral ?? false, }); } catch (Exception e) { lock (_logGate) { // mark that we had an error so that our top level process quits with an error // code. _errorCount++; } // we have a potential pathological case with logging. Consider if logging a // message itself throws an error. If we then allow the error to bubble up, our top // level handler will try to log that error, which can potentially lead to an error // repeating unendingly. So, to prevent that from happening, we report a very specific // exception that the top level can know about and handle specially. throw new LogException(e); } }
public Resource?Gather(uint ammount) { Resource?result = top < ResourceSettings.NumberOfLayers ? (Resource?)stack[top].Gather(ammount) : null; updateToolTip(); Refresh(); return(result); }
private BuildingTile(Resource resource1, Resource resource2, Resource resource3) { Resource1 = resource1; Resource2 = resource2; Resource3 = resource3; All.Add(this); }
public bool AllowedIn(Miner?miner, Resource?resource) { if (miner != null && resource != null && !miner.ResourceCategories.Contains(resource.Category)) { return(false); } return(true); }
private static void SetResourceMetadata(IEnumerable <Resource> resources, Resource?parent) { foreach (var resource in resources) { resource.Parent = parent; SetResourceMetadata(resource.Resources, resource); } }
/// <summary> /// Obtains a stream for the story file data in this Blorb. /// </summary> /// <returns>A stream containing the story file data, or null if no /// story resource is present.</returns> public Stream GetStoryStream() { Resource?storyRes = FindResource(EXEC_USAGE_ID, null); if (storyRes == null) { return(null); } byte[] lenBytes = ReadBlock(storyRes.Value.Offset + 4, 4); uint len = (uint)((lenBytes[0] << 24) + (lenBytes[1] << 16) + (lenBytes[2] << 8) + lenBytes[3]); return(new SubStream(stream, storyRes.Value.Offset + 8, len)); }
private async Task <OutputData <T> > CallAsync <T>( string token, CallArgs args, Resource?self, CallOptions?options, bool convertResult) { var(result, deps) = await CallRawAsync(token, args, self, options).ConfigureAwait(false); if (convertResult) { var converted = Converter.ConvertValue <T>($"{token} result", new Value { StructValue = result }); return(new OutputData <T>(deps, converted.Value, converted.IsKnown, converted.IsSecret)); } return(new OutputData <T>(ImmutableHashSet <Resource> .Empty, default !, isKnown: true, isSecret: false));
public static void EnsureResourceLoaded( this Resource?resource, Type resourceHolder, [CallerMemberName] string callerMethod = "") { if (string.IsNullOrEmpty(callerMethod)) { callerMethod = "Unknown"; } if ((resource == null) || (!resource.IsLoaded)) { throw new SeeingSharpResourcesNotLoadedException(resourceHolder, callerMethod); } }
private static async Task <string> TryGetResourceUrnAsync(Resource?resource) { if (resource != null) { try { return(await resource.Urn.GetValueAsync().ConfigureAwait(false)); } catch { // getting the urn for a resource may itself fail. in that case we don't want to // fail to send an logging message. we'll just send the logging message unassociated // with any resource. } } return(""); }
/// <summary> /// Determines the type of the story file contained in this Blorb. /// </summary> /// <returns>A four-character string identifying the story file type, /// or null if no story resource is present.</returns> public string GetStoryType() { Resource?storyRes = FindResource(EXEC_USAGE_ID, null); if (storyRes == null) { return(null); } byte[] type = ReadBlock(storyRes.Value.Offset, 4); StringBuilder sb = new StringBuilder(4); sb.Append((char)type[0]); sb.Append((char)type[1]); sb.Append((char)type[2]); sb.Append((char)type[3]); return(sb.ToString()); }
public Tile(int x, int y, bool walkable, bool transparent, int food, int production, int movementRequired, Resource?resource, GraphicsItem symbol, RLColor fg, RLColor bg, ICell cell) { X = x; Y = y; Walkable = walkable; Transparent = transparent; Food = food; Production = production; MovementRequired = movementRequired; Resource = resource; ForegroundColor = fg; BackgroundColor = bg; Symbol = symbol; Cell = cell; }
public Tile(Tile oldTile, GraphicsItem symbol, RLColor fg, RLColor bg, bool?walkable = null, bool?transparent = null, int?food = null, int?production = null, int?movementRequired = null, Resource?resource = null) { X = oldTile.X; Y = oldTile.Y; Walkable = walkable ?? oldTile.Walkable; Transparent = transparent ?? oldTile.Transparent; Food = food ?? oldTile.Food; Production = production ?? oldTile.Production; MovementRequired = movementRequired ?? oldTile.MovementRequired; Resource = resource ?? oldTile.Resource; Symbol = symbol; ForegroundColor = fg; BackgroundColor = bg; WasUpdated = true; }
public override async Task <IChatMessage> InitFromMessageAsync <T>(TeamsDataContext ctx, string chatId, T message) { if (message is not Resource m) { throw new ArgumentException($"Cannot init {nameof(ProcessedMessage)} from type {message.GetType()}", nameof(message)); } notificationResource = m; this.ctx = ctx; Messagetype = m.messagetype; Id = m.id; // note: this is the same ID as the one of the "real" message retrieved via the messages endpoint ChatId = m.to; OriginalArrivalTime = m.originalarrivaltime ?? Utils.JavaScriptUtcMsToDateTime(long.Parse(m.version ?? "0")); await ExtractSendersReceiversAndSubject(chatId); await GenerateTextContentExtractUsersAndUpdateSubject(); ReplaceImageUrlsByContentIds(); return(this); }
public Task SendAsync(string severity, string message, Resource?resource = null, int?streamId = null, bool?ephemeral = null) { if (severity == "Error") { LoggedErrors = true; } Logger.Invoke(new LogEntry { Severity = severity, Message = message, Resource = resource, StreamId = streamId, Ephemeral = ephemeral }); return(Task.FromResult(0)); }
public Task ExpiredInstancesGetReleasedOnReuse(bool invalidate) { var clock = new MemoryClock(); var configuration = new ResourcePoolConfiguration() { MaximumAge = TimeSpan.FromSeconds(1) }; return(RunTest <Key, Resource>(async(context, pool) => { var key = new Key(0); Resource?lastResource = null; await pool.UseAsync(context, key, wrapper => { if (invalidate) { wrapper.Invalidate(context); } lastResource = wrapper.Value; return BoolResult.SuccessTask; }).ShouldBeSuccess(); if (!invalidate) { clock.Increment(TimeSpan.FromMinutes(1)); } await pool.UseAsync(context, key, wrapper => { lastResource.Should().NotBe(wrapper.Value); pool.Counter[ResourcePoolCounters.CreatedResources].Value.Should().Be(2); pool.Counter[ResourcePoolCounters.ReleasedResources].Value.Should().Be(1); return BoolResult.SuccessTask; }).ShouldBeSuccess(); }, configuration, clock)); }
/// <summary> /// Error logs a fatal error to indicate that the tool should stop processing resource /// operations immediately. /// </summary> Task ILogger.ErrorAsync(string message, Resource?resource, int?streamId, bool?ephemeral) => ErrorAsync(message, resource, streamId, ephemeral);
/// <summary> /// Warn logs a warning to indicate that something went wrong, but not catastrophically so. /// </summary> Task ILogger.WarnAsync(string message, Resource?resource, int?streamId, bool?ephemeral) { Serilog.Log.Warning(message); return(LogImplAsync(LogSeverity.Warning, message, resource, streamId, ephemeral)); }
/// <summary> /// Logs an informational message that is generally printed to stdout during resource /// operations. /// </summary> Task ILogger.InfoAsync(string message, Resource?resource, int?streamId, bool?ephemeral) { Serilog.Log.Information(message); return(LogImplAsync(LogSeverity.Info, message, resource, streamId, ephemeral)); }
/// <summary> /// Logs a fatal condition. Consider raising an exception /// after calling Error to stop the Pulumi program. /// </summary> public static void Error(string message, Resource?resource = null, int?streamId = null, bool?ephemeral = null) => Deployment.InternalInstance.Logger.ErrorAsync(message, resource, streamId, ephemeral);
/// <summary> /// Logs an exception. Consider raising the exception after /// calling this method to stop the Pulumi program. /// </summary> public static void Exception(Exception exception, Resource?resource = null, int?streamId = null, bool?ephemeral = null) => Error(exception.ToString(), resource, streamId, ephemeral);