Ejemplo n.º 1
0
        public CompilationDocument(TextSourceInfo textSourceInfo, IEnumerable <ITextLine> initialTextLines, TypeCobolOptions compilerOptions, IProcessedTokensDocumentProvider processedTokensDocumentProvider,
                                   [CanBeNull] MultilineScanState scanState, List <RemarksDirective.TextNameVariation> copyTextNameVariations)
        {
            TextSourceInfo          = textSourceInfo;
            CompilerOptions         = compilerOptions;
            CopyTextNamesVariations = copyTextNameVariations ?? new List <RemarksDirective.TextNameVariation>();
            MissingCopies           = new List <CopyDirective>();

            this.processedTokensDocumentProvider = processedTokensDocumentProvider;

            // Initialize the compilation document lines
            compilationDocumentLines = ImmutableList <CodeElementsLine> .Empty.ToBuilder();

            // ... with the initial list of text lines received as a parameter
            if (initialTextLines != null)
            {
                // Insert Cobol text lines in the internal tree structure
                compilationDocumentLines.AddRange(initialTextLines.Select(textLine => CreateNewDocumentLine(textLine, textSourceInfo.ColumnsLayout)));
            }

            // Initialize document views versions
            currentTextLinesVersion   = new DocumentVersion <ICobolTextLine>(this);
            currentTokensLinesVersion = new DocumentVersion <ITokensLine>(this);

            // Initialize performance stats
            PerfStatsForText         = new PerfStatsForCompilationStep(CompilationStep.Text);
            PerfStatsForScanner      = new PerfStatsForCompilationStep(CompilationStep.Scanner);
            PerfStatsForPreprocessor = new PerfStatsForParsingStep(CompilationStep.Preprocessor);

            initialScanStateForCopy = scanState;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates an asynchronous computation that executes all the given asynchronous computations, initially queueing each as work items and using a fork/join pattern.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ms"></param>
        /// <returns></returns>
        public static Async <ImmutableList <T> > Parallel <T>(this ImmutableList <Async <T> > ms)
        {
            var empty = new ImmutableList <T>();

            return(() =>
            {
                var num = (uint)Math.Min(8, ms.Count);  // 64 is maximum here
                if (num == 0)
                {
                    return empty;
                }

                var xs = ms.Take(num);
                var rest = ms.RemoveRange(0, (int)num);
                var asyncs = xs.Map(x =>
                {
                    var handle = new AsyncEventHandle <T>();
                    x.Bind <T, Unit>(v => () => handle.Complete(v)).Start();
                    return handle;
                });
                WaitHandle.WaitAll(asyncs.Map(ah => (WaitHandle)ah.DoneEvent).ToArray());
                var ps = asyncs.Map(x => x.Result());
                return empty.AddRange(rest.Count > 0 ? ps.AddRange(rest.Parallel().RunSynchronously()) : ps);
            });
        }
 public IImmutableDictionary <TKey, TValue> AddRange(IEnumerable <KeyValuePair <TKey, TValue> > pairs)
 {
     return(new ImmutableDictionaryKeepOrder <TKey, TValue>(
                _dictionary.AddRange(pairs),
                _items.AddRange(pairs)
                ));
 }
Ejemplo n.º 4
0
 IImmutableList <Task> IImmutableList <Task> .AddRange(IEnumerable <Task> items)
 {
     return(AttachContinuationTasks(new TaskGroup(this)
     {
         _Tasks = _Tasks.AddRange(items)
     }));
 }
Ejemplo n.º 5
0
        public Task <ImmutableList <Fact> > Save(FactGraph graph, CancellationToken cancellationToken)
        {
            var newFacts = graph.FactReferences
                           .Where(reference => !factsByReference.ContainsKey(reference))
                           .Select(reference => graph.GetFact(reference))
                           .ToImmutableList();

            factsByReference = factsByReference.AddRange(newFacts
                                                         .Select(fact => new KeyValuePair <FactReference, Fact>(fact.Reference, fact))
                                                         );
            var newPredecessors = newFacts
                                  .Select(fact => (
                                              factReference: fact.Reference,
                                              edges: fact.Predecessors
                                              .SelectMany(predecessor => CreateEdges(fact, predecessor))
                                              .ToImmutableList()
                                              ))
                                  .ToImmutableList();

            edges = edges.AddRange(newPredecessors
                                   .SelectMany(pair => pair.edges)
                                   );
            foreach (var(factReference, edges) in newPredecessors)
            {
                ancestors = ancestors.Add(
                    factReference,
                    edges
                    .SelectMany(edge => ancestors[edge.Predecessor])
                    .Append(factReference)
                    .Distinct()
                    .ToImmutableList()
                    );
            }
            return(Task.FromResult(newFacts));
        }
Ejemplo n.º 6
0
        private static ImmutableList <string> GetCategoryEntries(ImmutableList <string> urlsToFollow, ImmutableList <string> noFollow = null, ImmutableList <string> entries = null)
        {
            if (noFollow == null)
            {
                return(GetCategoryEntries(urlsToFollow, ImmutableList.Create <string>()));
            }
            if (urlsToFollow.IsEmpty)
            {
                return(entries);
            }
            var url           = urlsToFollow.First();
            var remainingUrls = urlsToFollow.Skip(1).ToImmutableList();
            var noFollowMore  = noFollow.Add(url);
            var links         = LinksFromCategoryPage(url).Except(noFollowMore);

            if (entries == null)
            {
                return(GetCategoryEntries(urlsToFollow, noFollow, ImmutableList.Create <string>()));
            }

            var pageEntries  = EntriesFromCategory(url);
            var newEntries   = pageEntries.Except(entries);
            var totalEntries = entries.AddRange(pageEntries);

            Console.WriteLine("{0} \tpage entries:{1} new:{2} total:{3} new pages:{4} remaining pages:{5}", url, pageEntries.Count(), newEntries.Count(), totalEntries.Count(), links.Count(), remainingUrls.Count());

            //if (pageEntries.Where(e => e.Contains(":")).Select(e => { Console.WriteLine(e); return e; }).Count() > 1)
            //{
            //    throw new Exception(url + " contains a bad entry");
            //}
            //else Console.WriteLine();

            return(GetCategoryEntries(remainingUrls.AddRange(links).Distinct().ToImmutableList(), noFollowMore, totalEntries));
        }
        // --- Initialization ---
        /// <summary>
        /// Initializes a new compilation document from a list of text lines.
        /// This method does not scan the inserted text lines to produce tokens.
        /// You must explicitely call UpdateTokensLines() to start an initial scan of the document.
        /// </summary>
        public CompilationDocument(TextSourceInfo textSourceInfo, IEnumerable<ITextLine> initialTextLines, TypeCobolOptions compilerOptions, IProcessedTokensDocumentProvider processedTokensDocumentProvider)
        {
            TextSourceInfo = textSourceInfo;
            CompilerOptions = compilerOptions;
            this.processedTokensDocumentProvider = processedTokensDocumentProvider;

            // Initialize the compilation document lines
            compilationDocumentLines = ImmutableList<CodeElementsLine>.Empty.ToBuilder();

            // ... with the initial list of text lines received as a parameter
            if (initialTextLines != null)
            {
                // Insert Cobol text lines in the internal tree structure
                compilationDocumentLines.AddRange(initialTextLines.Select(textLine => CreateNewDocumentLine(textLine, textSourceInfo.ColumnsLayout)));
            }

            // Initialize document views versions
            currentTextLinesVersion = new DocumentVersion<ICobolTextLine>(this);
            currentTokensLinesVersion = new DocumentVersion<ITokensLine>(this);

            // Initialize performance stats
            PerfStatsForText = new PerfStatsForCompilationStep(CompilationStep.Text);
            PerfStatsForScanner = new PerfStatsForCompilationStep(CompilationStep.Scanner);
            PerfStatsForPreprocessor = new PerfStatsForCompilationStep(CompilationStep.Preprocessor);
        }
 /// <summary>
 /// Adds a range of items to the end of the collection. Quicker than adding them individually,
 /// but the view doesn't update until the last item has been added.
 /// </summary>
 public virtual void AddRange(IList <T> items)
 {
     DoReadWriteNotify(
         () => ImmutableList.Count,
         (index) => ImmutableList.AddRange(items),
         (index) => new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, (IList)items, index)
         );
 }
Ejemplo n.º 9
0
 public ZipArchiveProblems AddRange(IEnumerable <FileProblem> problems)
 {
     if (problems == null)
     {
         throw new ArgumentNullException(nameof(problems));
     }
     return(new ZipArchiveProblems(_problems.AddRange(problems)));
 }
Ejemplo n.º 10
0
        public void AddRange_ReturnsNewListWithNewItemsAppended()
        {
            var subject = new ImmutableList<int>();
            var result = subject.AddRange(Enumerable.Range(1, 10));

            Assert.AreEqual(0, subject.Count);
            Assert.AreEqual(10, result.Count);
        }
Ejemplo n.º 11
0
        public void AddRange_ReturnsNewListWithNewItemsAppended()
        {
            var subject = new ImmutableList <int>();
            var result  = subject.AddRange(Enumerable.Range(1, 10));

            Assert.AreEqual(0, subject.Count);
            Assert.AreEqual(10, result.Count);
        }
                public IFileWarningBuilder WithParameters(params ProblemParameter[] parameters)
                {
                    if (parameters == null)
                    {
                        throw new ArgumentNullException(nameof(parameters));
                    }

                    return(new FileWarningBuilder(_file, _reason, _parameters.AddRange(parameters)));
                }
Ejemplo n.º 13
0
            private TargetsToPropagate(ImmutableList <string> outerBuildTargets, ImmutableList <string> nonOuterBuildTargets)
            {
                _outerBuildTargets = outerBuildTargets;

                // This is used as the list of entry targets for both inner builds and non-multitargeting projects
                // It represents the concatenation of outer build targets and non outer build targets, in this order.
                // Non-multitargeting projects use these targets because they act as both outer and inner builds.
                _allTargets = outerBuildTargets.AddRange(nonOuterBuildTargets);
            }
Ejemplo n.º 14
0
            private IPath <V, E> ComputeNext(IPath <V, E> lastPath)
            {
                // Start searching for the next path.
                for (int i = 0; i < lastPath.Edges.Count; ++i)
                {
                    V        spurNode         = lastPath.Edges[i].Src;
                    List <E> rootPathEdgeList = lastPath.Edges.Take(i).ToList();

                    foreach (IPath <V, E> path in resultPaths)
                    {
                        if (path.Edges.Count >= i && rootPathEdgeList.SequenceEqual(path.Edges.Take(i)))
                        {
                            maskingWeigher.Excluded.Add(path.Edges[i]);
                        }
                    }

                    // Effectively remove all root path nodes other than the spur node.
                    foreach (E edge in rootPathEdgeList)
                    {
                        foreach (E e in graph.GetEdgesFrom(edge.Src))
                        {
                            maskingWeigher.Excluded.Add(e);
                        }
                        foreach (E e in graph.GetEdgesTo(edge.Src))
                        {
                            maskingWeigher.Excluded.Add(e);
                        }
                    }

                    IPath <V, E> spurPath = search.Search(graph, spurNode, dst, maskingWeigher, 1).Paths.FirstOrDefault();
                    if (spurPath != null)
                    {
                        ImmutableList <E> .Builder builder = ImmutableList.CreateBuilder <E>();
                        builder.AddRange(rootPathEdgeList);
                        builder.AddRange(spurPath.Edges);
                        potentialPaths.Add(Path(builder.ToImmutable()));
                    }

                    // Restore all removed paths and nodes.
                    maskingWeigher.Excluded.Clear();
                }

                return(potentialPaths.IsEmpty ? null : potentialPaths.DeleteMax());
            }
Ejemplo n.º 15
0
        public static ulong Part2(string input)
        {
            ImmutableList <int> clock = input.Select(x => Convert.ToInt32(x.ToString())).ToImmutableList();

            clock = clock.AddRange(Enumerable.Range(10, 1000001 - 10));
            var cups = new LinkedList <int>(clock);
            var res  = Run2(cups, 10000000);

            return(1UL * (ulong)res.NextOrFirst().Value *(ulong)res.NextOrFirst().NextOrFirst().Value);
        }
Ejemplo n.º 16
0
 private void Tokenize()
 {
     // get rid of trimmers first
     string[] firstpass = file.Split(trimers.ToArray(), StringSplitOptions.RemoveEmptyEntries);
     // split the text based on list of keywords into tokens
     foreach (string s in firstpass)
     {
         tokens = tokens.AddRange(s.SplitAndKeep(keywords));
     }
 }
Ejemplo n.º 17
0
        protected TInvariant Apply(params object[] evts)
        {
            var invariant = this;

            foreach (var evt in evts)
            {
                invariant = Arrange(evt);
            }

            invariant._scheduled = _scheduled.AddRange(evts);

            return((TInvariant)invariant);
        }
Ejemplo n.º 18
0
        public void Setup()
        {
            var range = Enumerable.Range(0, N);

            immutableList = ImmutableList <int> .Empty;
            immutableList = immutableList.AddRange(range);

            trieList = ImmutableTrieList <int> .Empty;
            trieList = trieList.AddRange(range);

            list = new List <int>();
            list.AddRange(range);
        }
Ejemplo n.º 19
0
        private static void AddMemberAndAttributes(ImmutableList<SyntaxNode>.Builder elements, SyntaxNode member)
        {
            switch (member.Kind())
            {
            case SyntaxKind.ClassDeclaration:
            case SyntaxKind.StructDeclaration:
            case SyntaxKind.InterfaceDeclaration:
            case SyntaxKind.EnumDeclaration:
            case SyntaxKindEx.RecordDeclaration:
            case SyntaxKindEx.RecordStructDeclaration:
                elements.AddRange(((BaseTypeDeclarationSyntax)member).AttributeLists);
                break;

            case SyntaxKind.FieldDeclaration:
            case SyntaxKind.EventFieldDeclaration:
                elements.AddRange(((BaseFieldDeclarationSyntax)member).AttributeLists);
                break;

            case SyntaxKind.PropertyDeclaration:
            case SyntaxKind.EventDeclaration:
            case SyntaxKind.IndexerDeclaration:
                elements.AddRange(((BasePropertyDeclarationSyntax)member).AttributeLists);
                break;

            case SyntaxKind.MethodDeclaration:
            case SyntaxKind.ConstructorDeclaration:
            case SyntaxKind.DestructorDeclaration:
            case SyntaxKind.OperatorDeclaration:
            case SyntaxKind.ConversionOperatorDeclaration:
                elements.AddRange(((BaseMethodDeclarationSyntax)member).AttributeLists);
                break;

            case SyntaxKind.GetAccessorDeclaration:
            case SyntaxKind.SetAccessorDeclaration:
            case SyntaxKind.AddAccessorDeclaration:
            case SyntaxKind.RemoveAccessorDeclaration:
            case SyntaxKind.UnknownAccessorDeclaration:
                elements.AddRange(((AccessorDeclarationSyntax)member).AttributeLists);
                break;

            case SyntaxKind.TypeParameter:
                elements.AddRange(((TypeParameterSyntax)member).AttributeLists);
                break;

            case SyntaxKind.Parameter:
                elements.AddRange(((ParameterSyntax)member).AttributeLists);
                break;

            default:
                break;
            }

            elements.Add(member);
        }
            private async Task AddDefinitionEntriesAsync(DefinitionItem definition)
            {
                CancellationToken.ThrowIfCancellationRequested();

                // Don't do anything if we already have entries for this definition
                // (i.e. another thread beat us to this).
                if (HasEntriesForDefinition(definition))
                {
                    return;
                }

                // First find the bucket corresponding to our definition. If we can't find/create
                // one, then don't do anything for this reference.
                var definitionBucket = GetOrCreateDefinitionBucket(definition);

                if (definitionBucket == null)
                {
                    return;
                }

                // We could do this inside the lock.  but that would mean async activity in a
                // lock, and i'd like to avoid that.  That does mean that we might do extra
                // work if multiple threads end up down htis path.  But only one of them will
                // win when we access the lock below.
                var builder = ImmutableArray.CreateBuilder <Entry>();

                foreach (var definitionLocation in definition.SourceSpans)
                {
                    var definitionEntry = await CreateDocumentLocationEntryAsync(
                        definitionBucket, definitionLocation, isDefinitionLocation : true).ConfigureAwait(false);

                    if (definitionEntry != null)
                    {
                        builder.Add(definitionEntry);
                    }
                }

                lock (_gate)
                {
                    // Do one final check to ensure that no other thread beat us here.
                    if (!HasEntriesForDefinition(definition))
                    {
                        _entries = _entries.AddRange(builder);
                        CurrentVersionNumber++;
                    }
                }

                // Let all our subscriptions know that we've updated.
                _tableDataSink.FactorySnapshotChanged(this);
            }
Ejemplo n.º 21
0
        static ImmutableDictionary <Int32, ImmutableList <Int32> > ToImmutableDictionary(this RepeatedField <PBIntToMultipleIntMap> value)
        {
            //# Tested
            ImmutableDictionary <Int32, ImmutableList <Int32> > .Builder bldr = ImmutableDictionary <Int32, ImmutableList <Int32> > .Empty.ToBuilder();

            foreach (PBIntToMultipleIntMap item in value)
            {
                ImmutableList <Int32> .Builder l = ImmutableList <int> .Empty.ToBuilder();

                l.AddRange(item.Target);
                bldr.Add(item.Source, l.ToImmutableList());
            }
            return(bldr.ToImmutableDictionary());
        }
Ejemplo n.º 22
0
        public void AddState(object?value, string hash, ImmutableSortedSet <string> predecessors)
        {
            if (!_predecessors.Contains(hash))
            {
                _candidates = _candidates.Add(new Candidate(hash, value));
                _property.SetValue(_object, value);
            }

            var newPredecessors = predecessors.Except(_predecessors);

            _candidates = _candidates.RemoveAll(c => newPredecessors.Contains(c.MessageSignature));

            _predecessors = _predecessors.AddRange(predecessors);
        }
Ejemplo n.º 23
0
        public static ImmutableList <T> AddRange <T>([NotNull] this ImmutableList <T> source, [NotNull] params T[] values)
        {
            if (source is null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (values is null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            return(values.Length > 0 ? source.AddRange(values) : source);
        }
Ejemplo n.º 24
0
        async Task FindTasks(Solution solution, bool raiseTasksChangedEvent = true)
        {
            var locator = new TaskRunnerConfigurationLocator(taskRunnerProvider, solution);
            await locator.FindTasks();

            if (locator.GroupedTasks.Any())
            {
                groupedTasks = groupedTasks.AddRange(locator.GroupedTasks);

                if (raiseTasksChangedEvent)
                {
                    OnTasksChanged();
                }
            }
        }
Ejemplo n.º 25
0
        public static ImmutableList <IPropertySymbol> GetPropertySymbolsBaseLevels(this INamedTypeSymbol namedTypeSymbol, bool includeOnlyLowerLevelPropertiesFromInterfaces)
        {
            if (includeOnlyLowerLevelPropertiesFromInterfaces)
            {
                return(namedTypeSymbol.AllInterfaces.SelectMany(x => x.GetPropertySymbols()).ToImmutableList());
            }
            var baseType = namedTypeSymbol.BaseType;
            ImmutableList <IPropertySymbol> result = ImmutableList.Create <IPropertySymbol>();

            while (baseType != null && baseType.Name != "Object")
            {
                result   = result.AddRange(baseType.GetPropertySymbols());
                baseType = baseType.BaseType;
            }
            return(result);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// A new contact has come in from one of the underlying stores. Update our local database of contacts
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        private void UpdateLocalStore(UpdateInfo c)
        {
            switch (c._reason)
            {
            case UpdateReason.Add:
                _localContactStore = _localContactStore.AddRange(c._contacts);
                break;

            case UpdateReason.Remove:
                _localContactStore = _localContactStore.RemoveRange(c._contacts);
                break;

            default:
                throw new NotImplementedException();
            }
        }
Ejemplo n.º 27
0
            private async Task AddDeclarationEntriesAsync(DefinitionItem definition)
            {
                CancellationToken.ThrowIfCancellationRequested();

                // Don't do anything if we already have declaration entries for this definition
                // (i.e. another thread beat us to this).
                if (HasDeclarationEntries(definition))
                {
                    return;
                }

                var definitionBucket = GetOrCreateDefinitionBucket(definition);

                // We could do this inside the lock.  but that would mean async activity in a
                // lock, and i'd like to avoid that.  That does mean that we might do extra
                // work if multiple threads end up down htis path.  But only one of them will
                // win when we access the lock below.
                var declarations = ArrayBuilder <Entry> .GetInstance();

                foreach (var declarationLocation in definition.SourceSpans)
                {
                    var definitionEntry = await CreateDocumentLocationEntryAsync(
                        definitionBucket, declarationLocation, isDefinitionLocation : true).ConfigureAwait(false);

                    if (definitionEntry != null)
                    {
                        declarations.Add(definitionEntry);
                    }
                }

                lock (_gate)
                {
                    // Do one final check to ensure that no other thread beat us here.
                    if (!HasDeclarationEntries(definition))
                    {
                        // We only include declaration entries in the entries we show when
                        // not grouping by definition.
                        _entriesWithDeclarations = _entriesWithDeclarations.AddRange(declarations);
                        CurrentVersionNumber++;
                    }
                }

                declarations.Free();

                // Let all our subscriptions know that we've updated.
                _tableDataSink.FactorySnapshotChanged(this);
            }
Ejemplo n.º 28
0
        public async Task Load()
        {
            using (await locker.LockAsync())
            {
                var dbApiItems = await db.ApiItems
                                 .Include(x => x.Headers)
                                 .Include(x => x.Inputs)
                                 .Include(x => x.Outputs)
                                 .Include(x => x.Outputs)
                                 .Include(x => x.Items)
                                 .ToArrayAsync();

                var dbApiItemsByParentId = dbApiItems.ToLookup(x => x.CollectionId ?? 0);

                items = items.AddRange(MapFromDb(dbApiItemsByParentId[0], dbApiItemsByParentId));
            }
        }
Ejemplo n.º 29
0
        public static string ScanLines(TokensLine[] tokensLines)
        {
            ImmutableList <TokensLine> .Builder tokensLinesList = ImmutableList <TokensLine> .Empty.ToBuilder();

            tokensLinesList.AddRange(tokensLines);

            ScannerStep.ScanDocument(TextSourceInfo, tokensLinesList, CompilerOptions, CopyTextNameVariations);

            StringBuilder sbResult = new StringBuilder();

            for (int i = 0; i < tokensLines.Length; i++)
            {
                sbResult.AppendLine("-- Line " + (i + 1) + " --");
                sbResult.AppendLine(BuildResultString(tokensLines[i]));
            }

            return(sbResult.ToString());
        }
Ejemplo n.º 30
0
        /// <inheritdoc />
        public void ReleaseWrite(ImmutableList <T> producedItems)
        {
            lock (syncRoot) {
                if (!writeLocked.HasValue)
                {
                    throw new InvalidOperationException("Can't release write lock if it is not held");
                }
                else if (producedItems.Count > writeLocked.Value)
                {
                    throw new InvalidOperationException("Can't write more items than space was locked for");
                }
                else
                {
                    writeLocked = null;
                    items       = items.AddRange(producedItems);

                    CheckWaitingReads();
                    CheckWaitingWrites();
                }
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Creates a new instance of the <see cref="PlayerManagerBuilder"/>
        /// type.
        /// </summary>
        /// <param name="userId">
        /// The user ID to perform all connections as.
        /// </param>
        /// <param name="services">
        /// The service provider to locate any existing services from.
        /// </param>
        public PlayerManagerBuilder(ulong userId, IServiceProvider services)
        {
            _userId        = userId;
            _loggerFactory = services.GetRequiredService <ILoggerFactory>();
            _decoders      = ImmutableList.CreateBuilder <IAudioDecoderFactory>();
            _providers     = ImmutableList.CreateBuilder <IAudioProviderFactory>();
            _sources       = ImmutableList.CreateBuilder <ITrackSource>();
            _transcoders   = ImmutableList
                             .CreateBuilder <IAudioTranscoderFactory>();

            _socketCount = 20;

            _decoders.AddRange(
                services.GetServices <IAudioDecoderFactory>());
            _providers.AddRange(
                services.GetServices <IAudioProviderFactory>());
            _sources.AddRange(
                services.GetServices <ITrackSource>());
            _transcoders.AddRange(
                services.GetServices <IAudioTranscoderFactory>());
        }
Ejemplo n.º 32
0
        public void RegisterAction <T>() where T : IIndexable, new()
        {
            _actions.Add(new T());

            var actionType = typeof(T);

            ImmutableList <ActionMapping> actionTypesOne = actionType.GetInterfaces()
                                                           .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IAction <>))
                                                           .Select(x => new ActionMapping(actionType, x.GenericTypeArguments[0]))
                                                           .ToImmutableList();

            _actionMappings = _actionMappings.AddRange(actionTypesOne);

            ImmutableList <ConvertMapping> convertTypes = actionType.GetInterfaces()
                                                          .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IConvert <,>))
                                                          .Select(x => new ConvertMapping(actionType, x.GenericTypeArguments[0], x.GenericTypeArguments[1]))
                                                          .ToImmutableList();

            _convertMappings = _convertMappings.AddRange(convertTypes);

            _updateCounter += 1;
        }
        static CachedOperatorTypeLoader()
        {
            var allOperatorTypeLoader = new OperatorTypeLoader();
            var types = allOperatorTypeLoader.LoadOperatorTypes();
            var operators = types.Select(allOperatorTypeLoader.LoadOperator);

            _cachedTypes = _cachedTypes.AddRange(types);
            _cachedOperators = _cachedOperators.AddRange(operators);

            AppDomain.CurrentDomain.AssemblyLoad += (sender, args) => {
                try {
                    var operatorTypeLoader = new OperatorTypeLoader();
                    var newAssemblyTypes = operatorTypeLoader.LoadOperatorTypes(args.LoadedAssembly);
                    var newOperators = newAssemblyTypes.Select(operatorTypeLoader.LoadOperator);

                    _cachedTypes = _cachedTypes.AddRange(newAssemblyTypes);
                    _cachedOperators = _cachedOperators.AddRange(newOperators);
                } catch (Exception e) {
                    NLog.LogManager.GetCurrentClassLogger().Error(e, "Loading operators from a new assembly failed");
                }
            };
        }