/// <summary> /// Go through all of the implementations of type, as well as the interfaces /// that they implement. If any of those types include the provided field, /// suggest them, sorted by how often the type is referenced, starting /// with Interfaces. /// </summary> private IEnumerable <string> GetSuggestedTypeNames(IGraphType type, string fieldName) { if (type is IAbstractGraphType absType) { var suggestedObjectTypes = new List <string>(); var interfaceUsageCount = new LightweightCache <string, int>(key => 0); absType.PossibleTypes.Apply(possibleType => { if (!possibleType.HasField(fieldName)) { return; } // This object defines this field. suggestedObjectTypes.Add(possibleType.Name); possibleType.ResolvedInterfaces.Apply(possibleInterface => { if (possibleInterface.HasField(fieldName)) { // This interface type defines this field. interfaceUsageCount[possibleInterface.Name] = interfaceUsageCount[possibleInterface.Name] + 1; } }); }); var suggestedInterfaceTypes = interfaceUsageCount.Keys.OrderBy(x => interfaceUsageCount[x]); return(suggestedInterfaceTypes.Concat(suggestedObjectTypes)); } return(Enumerable.Empty <string>()); }
public RouteNode(string segment, int depth) { Segment = segment; Depth = depth; _children = new LightweightCache <string, RouteNode>(s => new RouteNode(s, Depth + 1)); }
public static string ToDisplayMessage(Exception ex, out ErrorDisplay errorDisplay) { if (ex is StorytellerFailureException) { var failure = ex.As <StorytellerFailureException>(); errorDisplay = failure.ErrorDisplay; return(failure.FormattedMessage()); } var exType = ex.GetType(); if (_textualErrors.Has(exType)) { errorDisplay = ErrorDisplay.text; return(_textualErrors[exType](ex)); } if (_markdownErrors.Has(exType)) { errorDisplay = ErrorDisplay.markdown; return(_markdownErrors[exType](ex)); } errorDisplay = ErrorDisplay.text; return(ex.ToString()); }
private void detectCycleRecursive( FragmentDefinition fragment, Stack <FragmentSpread> spreadPath, LightweightCache <string, bool> visitedFrags, LightweightCache <string, int> spreadPathIndexByName, ValidationContext context) { var fragmentName = fragment.Name; visitedFrags[fragmentName] = true; var spreadNodes = context.GetFragmentSpreads(fragment.SelectionSet); if (spreadNodes.Count == 0) { return; } spreadPathIndexByName[fragmentName] = spreadPath.Count; foreach (var spreadNode in spreadNodes) { var spreadName = spreadNode.Name; var cycleIndex = spreadPathIndexByName[spreadName]; if (cycleIndex == -1) { spreadPath.Push(spreadNode); if (!visitedFrags[spreadName]) { var spreadFragment = context.GetFragment(spreadName); if (spreadFragment != null) { detectCycleRecursive( spreadFragment, spreadPath, visitedFrags, spreadPathIndexByName, context); } } spreadPath.Pop(); } else { var cyclePath = spreadPath.Reverse().Skip(cycleIndex).ToArray(); var nodes = cyclePath.OfType <INode>().Concat(new[] { spreadNode }).ToArray(); context.ReportError(new ValidationError( context.OriginalQuery, "5.4", CycleErrorMessage(spreadName, cyclePath.Select(x => x.Name).ToArray()), nodes)); } } spreadPathIndexByName[fragmentName] = -1; }
public Conversions() { _convertors = new LightweightCache <Type, Func <string, object> >( type => { return(providers().FirstValue(x => x.ConverterFor(type))); }); RegisterConversion(bool.Parse); RegisterConversion(byte.Parse); RegisterConversion(sbyte.Parse); RegisterConversion(char.Parse); RegisterConversion(decimal.Parse); RegisterConversion(double.Parse); RegisterConversion(float.Parse); RegisterConversion(short.Parse); RegisterConversion(int.Parse); RegisterConversion(long.Parse); RegisterConversion(ushort.Parse); RegisterConversion(uint.Parse); RegisterConversion(ulong.Parse); RegisterConversion(DateTimeConverter.GetDateTime); RegisterConversion(Guid.Parse); RegisterConversion(x => { if (x == "EMPTY") { return(string.Empty); } return(x); }); }
static MimeType() { _fileExtensions.Each(pair => _mimeTypes[pair.Value].AddExtension(pair.Key)); _mappingFromExtension = new LightweightCache <string, MimeType>(extension => { return(_mimeTypes.GetAll().FirstOrDefault(x => x.HasExtension(extension))); }); }
public Fixture() { _grammars = new LightweightCache <string, IGrammar>(findGrammar); Key = GetType().Name.Replace("Fixture", ""); this["TODO"] = Do <string>("TODO: {message}", StoryTellerAssert.Fail); }
public PendingEventsStore() { _pending = new LightweightCache <Type, LightweightCache <object, List <IEvent> > >( type => new LightweightCache <object, List <IEvent> >( id => new List <IEvent>() ) ); }
public StatusBoard(Task completion) { _counts = new(name => new ProjectionStatus(name, completion)); _updater = new ActionBlock <UpdateMessage>(Update, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 1, EnsureOrdered = true }); }
private void detectCycleRecursive( FragmentDefinition fragment, Stack<FragmentSpread> spreadPath, LightweightCache<string, bool> visitedFrags, LightweightCache<string, int> spreadPathIndexByName, ValidationContext context) { var fragmentName = fragment.Name; visitedFrags[fragmentName] = true; var spreadNodes = context.GetFragmentSpreads(fragment.SelectionSet).ToArray(); if (!spreadNodes.Any()) { return; } spreadPathIndexByName[fragmentName] = spreadPath.Count; foreach (var spreadNode in spreadNodes) { var spreadName = spreadNode.Name; var cycleIndex = spreadPathIndexByName[spreadName]; if (cycleIndex == -1) { spreadPath.Push(spreadNode); if (!visitedFrags[spreadName]) { var spreadFragment = context.GetFragment(spreadName); if (spreadFragment != null) { detectCycleRecursive( spreadFragment, spreadPath, visitedFrags, spreadPathIndexByName, context); } } spreadPath.Pop(); } else { var cyclePath = spreadPath.Reverse().Skip(cycleIndex).ToArray(); var nodes = cyclePath.OfType<INode>().Concat(new[] {spreadNode}).ToArray(); context.ReportError(new ValidationError( context.OriginalQuery, "5.4", CycleErrorMessage(spreadName, cyclePath.Select(x => x.Name).ToArray()), nodes)); } } spreadPathIndexByName[fragmentName] = -1; }
public override void SetUp() { _busLogger = new StorytellerBusLogger(); _transportLogger = new StorytellerTransportLogger(); _busLogger.Start(Context); _transportLogger.Start(Context, _busLogger.Errors); _senderWatcher = new SenderLatchDetected(); _receiverStore = DocumentStore.For(_ => { _.PLV8Enabled = false; _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "receiver"; _.Storage.Add <PostgresqlEnvelopeStorage>(); _.Schema.For <TraceDoc>(); }); _receiverStore.Advanced.Clean.CompletelyRemoveAll(); _receiverStore.Schema.ApplyAllConfiguredChangesToDatabase(); _sendingStore = DocumentStore.For(_ => { _.PLV8Enabled = false; _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "sender"; _.Storage.Add <PostgresqlEnvelopeStorage>(); }); _sendingStore.Advanced.Clean.CompletelyRemoveAll(); _sendingStore.Schema.ApplyAllConfiguredChangesToDatabase(); _receivers = new LightweightCache <string, JasperRuntime>(key => { var registry = new ReceiverApp(); registry.Logging.LogBusEventsWith(_busLogger); registry.Logging.LogTransportEventsWith(_transportLogger); return(JasperRuntime.For(registry)); }); _senders = new LightweightCache <string, JasperRuntime>(key => { var registry = new SenderApp(); registry.Logging.LogBusEventsWith(_busLogger); registry.Logging.LogTransportEventsWith(_transportLogger); registry.Logging.LogTransportEventsWith(_senderWatcher); return(JasperRuntime.For(registry)); }); }
public override void SetUp() { _messageLogger = new StorytellerMessageLogger(new LoggerFactory(), new NulloMetrics(), new JasperOptions()); _messageLogger.Start(Context); _senderWatcher = new SenderLatchDetected(new LoggerFactory()); new SqlServerEnvelopeStorageAdmin(new SqlServerSettings { ConnectionString = Servers.SqlServerConnectionString, SchemaName = "receiver" }).RecreateAll(); new SqlServerEnvelopeStorageAdmin(new SqlServerSettings { ConnectionString = Servers.SqlServerConnectionString, SchemaName = "sender" }).RecreateAll(); using (var conn = new SqlConnection(Servers.SqlServerConnectionString)) { conn.Open(); conn.CreateCommand(@" IF OBJECT_ID('receiver.trace_doc', 'U') IS NOT NULL drop table receiver.trace_doc; ").ExecuteNonQuery(); conn.CreateCommand(@" create table receiver.trace_doc ( id uniqueidentifier not null primary key, name varchar(100) not null ); ").ExecuteNonQuery(); } _receivers = new LightweightCache <string, IHost>(key => { var registry = new ReceiverApp(); registry.Services.AddSingleton <IMessageLogger>(_messageLogger); return(JasperHost.For(registry)); }); _senders = new LightweightCache <string, IHost>(key => { var registry = new SenderApp(); registry.Services.AddSingleton <IMessageLogger>(_messageLogger); registry.Services.For <ITransportLogger>().Use(_senderWatcher); return(JasperHost.For(registry)); }); }
public StubTransport(IHandlerPipeline pipeline) { _pipeline = pipeline; LocalReplyUri = new Uri($"stub://replies"); Channels = new LightweightCache <Uri, StubChannel>(uri => new StubChannel(uri, pipeline, this)); }
private GeneratedMethod buildApplyEventMethod() { var method = _inlineGeneratedType.MethodFor(nameof(AggregationRuntime <string, string> .ApplyEvent)); // This gets you the EventSlice aggregate Id method.DerivedVariables.Add(new Variable(_aggregateMapping.IdType, $"slice.{nameof(EventSlice<string, string>.Id)}")); method.DerivedVariables.Add(Variable.For <Tenant>($"slice.{nameof(EventSlice<string, string>.Tenant)}")); method.DerivedVariables.Add(Variable.For <Tenant>($"slice.{nameof(EventSlice<string, string>.Tenant)}")); method.DerivedVariables.Add(Variable.For <IEvent>("@event")); method.DerivedVariables.Add( Variable.For <IMartenSession>($"({typeof(IMartenSession).FullNameInCode()})session")); method.DerivedVariables.Add(Variable.For <IQuerySession>("session")); method.DerivedVariables.Add( Variable.For <IAggregateProjection>(nameof(AggregationRuntime <string, string> .Projection))); var eventHandlers = new LightweightCache <Type, AggregateEventProcessingFrame>( eventType => new AggregateEventProcessingFrame(typeof(T), eventType)); foreach (var deleteEvent in DeleteEvents) { eventHandlers[deleteEvent].AlwaysDeletes = true; } foreach (var slot in _applyMethods.Methods) { eventHandlers[slot.EventType].Apply = new ApplyMethodCall(slot); } foreach (var slot in _createMethods.Methods) { eventHandlers[slot.EventType].CreationFrame = slot.Method is ConstructorInfo ? new AggregateConstructorFrame(slot) : new CreateAggregateFrame(slot); } foreach (var slot in _shouldDeleteMethods.Methods) { eventHandlers[slot.EventType].Deletion = new ShouldDeleteFrame(slot); } var frames = eventHandlers.OfType <EventProcessingFrame>().ToList(); frames.Sort(new EventTypeComparer()); var patternMatching = new EventTypePatternMatchFrame(frames); method.Frames.Add(patternMatching); method.Frames.Code("return aggregate;"); return(method); }
public StubTransport(string scheme = "stub") { _replyUri = new Uri($"{scheme}://replies"); Channels = new LightweightCache <Uri, StubChannel>(uri => new StubChannel(uri, _replyUri, _pipeline, null)); ReplyChannel = Channels[_replyUri]; Protocol = scheme; }
private PluginGraph() { Policies = new Policies(this); _profiles = new LightweightCache <string, PluginGraph>(name => new PluginGraph { ProfileName = name, Parent = this }); ProfileName = "DEFAULT"; }
public PluginGraph() { _profiles = new LightweightCache<string, PluginGraph>(name => new PluginGraph {ProfileName = name, Parent = this}); ProfileName = "DEFAULT"; _families = new Cache<Type, PluginFamily>( type => { return _policies.FirstValue(x => x.Build(type)) ?? new PluginFamily(type); }); _families.OnAddition = family => family.Owner = this; }
private LightweightCache <string, TemplateDef> buildTemplateCache(BehaviorGraph behaviors) { var cache = new LightweightCache <string, TemplateDef>(); behaviors.Behaviors.Where(x => x.InputType().CanBeCastTo <Template>()).Each(chain => { var def = new TemplateDef(this, chain); cache[def.Name] = def; }); return(cache); }
public override void SetUp() { _messageLogger = new StorytellerMessageLogger(new MessageHistory(), new LoggerFactory(), new NulloMetrics()); _messageLogger.Start(Context); _senderWatcher = new SenderLatchDetected(new LoggerFactory()); _receiverStore = DocumentStore.For(_ => { _.PLV8Enabled = false; _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "receiver"; _.Storage.Add <PostgresqlEnvelopeStorage>(); _.Schema.For <TraceDoc>(); }); _receiverStore.Advanced.Clean.CompletelyRemoveAll(); _receiverStore.Schema.ApplyAllConfiguredChangesToDatabase(); _sendingStore = DocumentStore.For(_ => { _.PLV8Enabled = false; _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "sender"; _.Storage.Add <PostgresqlEnvelopeStorage>(); }); _sendingStore.Advanced.Clean.CompletelyRemoveAll(); _sendingStore.Schema.ApplyAllConfiguredChangesToDatabase(); _receivers = new LightweightCache <string, JasperRuntime>(key => { var registry = new ReceiverApp(); registry.Services.AddSingleton <IMessageLogger>(_messageLogger); return(JasperRuntime.For(registry)); }); _senders = new LightweightCache <string, JasperRuntime>(key => { var registry = new SenderApp(); registry.Services.AddSingleton <IMessageLogger>(_messageLogger); registry.Services.For <ITransportLogger>().Use(_senderWatcher); return(JasperRuntime.For(registry)); }); }
public Topic ReadFile() { var cache = new LightweightCache <string, Topic>(); Topic top = null; new FileSystem().ReadTextFile(_file, line => { readTopic(line, cache); }); return(_top); }
public Topic ReadFile() { var cache = new LightweightCache<string, Topic>(); Topic top = null; new FileSystem().ReadTextFile(_file, line => { readTopic(line, cache); }); return _top; }
public AzureServiceBusTransport() : base(ProtocolName) { _endpoints = new LightweightCache <Uri, AzureServiceBusEndpoint>(uri => { var endpoint = new AzureServiceBusEndpoint(); endpoint.Parse(uri); endpoint.Parent = this; return(endpoint); }); }
private void readTopic(string line, LightweightCache<string, Topic> cache) { var parts = line.Split(':'); var key = parts[0]; var title = parts.Length > 1 ? parts[1] : key.Split('/').Last().Capitalize(); if (key.Contains("/")) { var parentKey = key.ParentUrl(); var parent = cache[parentKey]; key = key.Split('/').Last(); var urlSegment = parts.Length == 3 ? parts[2] : key; var topic = new Topic(key, "") { Title = title, UrlSegment = urlSegment }; parent.AddChild(topic); cache[topic.Key] = topic; } else if (_top == null) { _top = new Topic("index", "") { Title = title, UrlSegment = "" }; } else { var urlSegment = parts.Length == 3 ? parts[2] : key; var topic = new Topic(key, "") { Title = title, UrlSegment = urlSegment }; _top.AddChild(topic); cache[topic.Key] = topic; } }
private void readTopic(string line, LightweightCache <string, Topic> cache) { var parts = line.Split(':'); var key = parts[0]; var title = parts.Length > 1 ? parts[1] : key.Split('/').Last().Capitalize(); if (key.Contains("/")) { var parentKey = key.ParentUrl(); var parent = cache[parentKey]; key = key.Split('/').Last(); var urlSegment = parts.Length == 3 ? parts[2] : key; var topic = new Topic(key, "") { Title = title, UrlSegment = urlSegment }; parent.AddChild(topic); cache[topic.Key] = topic; } else if (_top == null) { _top = new Topic("index", "") { Title = title, UrlSegment = "" }; } else { var urlSegment = parts.Length == 3 ? parts[2] : key; var topic = new Topic(key, "") { Title = title, UrlSegment = urlSegment }; _top.AddChild(topic); cache[topic.Key] = topic; } }
public static StatsReport From(ISchema schema, Operation operation, PerfRecord[] records, DateTime start) { var operationStat = records.Single(x => string.Equals(x.Category, "operation")); var report = new StatsReport { Start = start, End = start.AddMilliseconds(operationStat.Duration), Duration = operationStat.Duration, Types = TypesFromSchema(schema) }; var perField = new LightweightCache <string, TypeStat>(type => new TypeStat { Name = type }); var typeInfo = new TypeInfo(schema); var fieldVisitor = new EnterLeaveListener(_ => { _.Match <AstField>(f => { var parent = typeInfo.GetParentType().GetNamedType(); var parentType = parent.Name; var fieldName = f.Name; perField[parentType][fieldName].ReturnType = SchemaPrinter.ResolveName(typeInfo.GetLastType()); }); }); new BasicVisitor(typeInfo, fieldVisitor).Visit(operation); var queryResolvers = records.Where(x => string.Equals(x.Category, "field")).ToList(); queryResolvers.Apply(resolver => { var typeName = resolver.MetaField <string>("typeName"); var fieldName = resolver.MetaField <string>("fieldName"); perField[typeName][fieldName].AddLatency(resolver.Duration); }); var operationName = operation.Name ?? "Anonymous"; report.PerSignature[operationName] = new StatsPerSignature { PerType = perField.GetAll() }; return(report); }
public PluginGraph() { _profiles = new LightweightCache <string, PluginGraph>(name => new PluginGraph { ProfileName = name, Parent = this }); ProfileName = "DEFAULT"; _families = new Cache <Type, PluginFamily>( type => { return(_policies.FirstValue(x => x.Build(type)) ?? new PluginFamily(type)); }); _families.OnAddition = family => family.Owner = this; }
public bool IsEqual(object expected, object actual) { if (expected == null) { return(actual == null); } if (actual == null) { return(false); } return(_comparisons[expected.GetType()](expected, actual)); }
public void StartListening(BusSettings settings, IWorkerQueue workers) { var pipeline = workers.As <WorkerQueue>().Pipeline; Channels = new LightweightCache <Uri, StubChannel>(uri => new StubChannel(uri, pipeline, this)); var incoming = settings.Listeners.Where(x => x.Scheme == "stub"); foreach (var uri in incoming) { Channels.FillDefault(uri); } }
public RabbitMqTransport() : base(ProtocolName) { _endpoints = new LightweightCache <Uri, RabbitMqEndpoint>(uri => { var endpoint = new RabbitMqEndpoint(); endpoint.Parse(uri); endpoint.Parent = this; return(endpoint); }); Exchanges = new LightweightCache <string, RabbitMqExchange>(name => new RabbitMqExchange(name, this)); }
public void StartListening(IMessagingRoot root) { var pipeline = root.Workers.As <WorkerQueue>().Pipeline; Channels = new LightweightCache <Uri, StubChannel>(uri => new StubChannel(uri, pipeline, this)); var incoming = root.Options.Listeners.Where(x => x.Scheme == "stub"); foreach (var uri in incoming) { Channels.FillDefault(uri); } }
public StorytellerDependencyFinder() { _isDependent = new LightweightCache <string, bool>(name => { var library = DependencyContext.Default.RuntimeLibraries.FirstOrDefault(x => x.Name.EqualsIgnoreCase(name)); if (library == null) { return(false); } if (library.Dependencies.Any(x => x.Name.EqualsIgnoreCase(assemblyName))) { return(true); } return(library.Dependencies.Any(x => _isDependent[x.Name])); }); }
/// <summary> /// Go through all of the implementations of type, as well as the interfaces /// that they implement. If any of those types include the provided field, /// suggest them, sorted by how often the type is referenced, starting /// with Interfaces. /// </summary> private IEnumerable <string> getSuggestedTypeNames( ISchema schema, GraphType type, string fieldName) { if (type is InterfaceGraphType || type is UnionGraphType) { var suggestedObjectTypes = new List <string>(); var interfaceUsageCount = new LightweightCache <string, int>(key => 0); var absType = type as GraphQLAbstractType; absType.PossibleTypes.Apply(possibleType => { if (!possibleType.HasField(fieldName)) { return; } // This object defines this field. suggestedObjectTypes.Add(possibleType.Name); possibleType.Interfaces.Apply(possibleInterfaceType => { var possibleInterface = schema.FindType(possibleInterfaceType); if (!possibleInterface.HasField(fieldName)) { return; } // This interface type defines this field. interfaceUsageCount[possibleInterface.Name] = interfaceUsageCount[possibleInterface.Name] + 1; }); }); var suggestedInterfaceTypes = interfaceUsageCount.Keys.OrderBy(x => interfaceUsageCount[x]); return(suggestedInterfaceTypes.Concat(suggestedObjectTypes)); } return(Enumerable.Empty <string>()); }
public static ICache <TKey, TValue> Get <TKey, TValue>(string name, CacheSettings cacheOptions) where TValue : class { name = name ?? string.Empty; bool isNamed = name != string.Empty; lock (_cacheCollection) { if (isNamed) { if (_cacheCollection.ContainsKey(name)) { return((ICache <TKey, TValue>)_cacheCollection[name]); } } ICache <TKey, TValue> result; switch (cacheOptions.CacheType) { case CacheType.Lightweight: result = new LightweightCache <TKey, TValue>(name, cacheOptions); break; case CacheType.Mixed: Verify.That(typeof(TKey) == typeof(string), "In mixed cache the key can only bee of type 'System.String'"); result = new MixedCache <TValue>(name, cacheOptions) as ICache <TKey, TValue>; break; case CacheType.Undefined: throw new InvalidOperationException("Cache type is undefined"); default: throw new NotImplementedException(); } Verify.That(result != null, "Failed to create a cache"); _cacheCollection.Add(name != string.Empty ? name : "unnamed cache", result); return(result); } }
public CommandUsageCache(DocSettings settings) { _settings = settings; _reports = new LightweightCache<string, CommandLineApplicationReport>(app => { var file = _settings.Root.AppendPath("content", app + ".usage.xml"); if (!File.Exists(file)) throw new FileNotFoundException("Cannot find a command usage file for {0} at {1}".ToFormat(app, file)); var serializer = new XmlSerializer(typeof(CommandLineApplicationReport)); using (var stream = new FileStream(file, FileMode.Open)) { using (var reader = new StreamReader(stream)) { return serializer.Deserialize(reader).As<CommandLineApplicationReport>(); } } }); }
public PluginGraph() { _profiles = new LightweightCache<string, PluginGraph>(name => new PluginGraph {ProfileName = name, Parent = this}); ProfileName = "DEFAULT"; _families = new Cache<Type, PluginFamily>(type => { return _policies.FirstValue(x => x.Build(type)) ?? new PluginFamily(type); }); _families.OnAddition = family => family.Owner = this; _setterRules = new SetterRules(); _builders = new Cache<Type, IInstanceBuilder>(type => { var plugin = new Plugin(type); _setterRules.Configure(plugin); return plugin.CreateBuilder(); }); }
public INodeVisitor Validate(ValidationContext context) { // Tracks already visited fragments to maintain O(N) and to ensure that cycles // are not redundantly reported. var visitedFrags = new LightweightCache<string, bool>(key => false); // Array of AST nodes used to produce meaningful errors var spreadPath = new Stack<FragmentSpread>(); // Position in the spread path var spreadPathIndexByName = new LightweightCache<string, int>(key => -1); return new EnterLeaveListener(_ => { _.Match<FragmentDefinition>(node => { if (!visitedFrags[node.Name]) { detectCycleRecursive(node, spreadPath, visitedFrags, spreadPathIndexByName, context); } }); }); }
public INodeVisitor Validate(ValidationContext context) { // Tracks already visited fragments to maintain O(N) and to ensure that cycles // are not redundantly reported. var visitedFrags = new LightweightCache <string, bool>(key => false); // Array of AST nodes used to produce meaningful errors var spreadPath = new Stack <FragmentSpread>(); // Position in the spread path var spreadPathIndexByName = new LightweightCache <string, int>(key => - 1); return(new EnterLeaveListener(_ => { _.Match <FragmentDefinition>(node => { if (!visitedFrags[node.Name]) { detectCycleRecursive(node, spreadPath, visitedFrags, spreadPathIndexByName, context); } }); })); }
/// <summary> /// Go through all of the implementations of type, as well as the interfaces /// that they implement. If any of those types include the provided field, /// suggest them, sorted by how often the type is referenced, starting /// with Interfaces. /// </summary> private IEnumerable<string> getSuggestedTypeNames( ISchema schema, IGraphType type, string fieldName) { if (type is IAbstractGraphType) { var suggestedObjectTypes = new List<string>(); var interfaceUsageCount = new LightweightCache<string, int>(key => 0); var absType = type as IAbstractGraphType; absType.PossibleTypes.Apply(possibleType => { if (!possibleType.HasField(fieldName)) { return; } // This object defines this field. suggestedObjectTypes.Add(possibleType.Name); possibleType.ResolvedInterfaces.Apply(possibleInterface => { if (possibleInterface.HasField(fieldName)) { // This interface type defines this field. interfaceUsageCount[possibleInterface.Name] = interfaceUsageCount[possibleInterface.Name] + 1; } }); }); var suggestedInterfaceTypes = interfaceUsageCount.Keys.OrderBy(x => interfaceUsageCount[x]); return suggestedInterfaceTypes.Concat(suggestedObjectTypes); } return Enumerable.Empty<string>(); }
public static XmlElement WithProperties(this XmlElement element, LightweightCache<string, string> properties) { properties.Each((k, v) => element.SetAttribute(k, v)); return element; }
public void can_create_it_without_the_clr_wigging_out() { var cache = new LightweightCache<string, string>(); }