Ejemplo n.º 1
0
        static void Main2(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: ./cwttest.exe [bytes to allocate] [number of iterations]");
            }


            int bytesToAllocate    = Int32.Parse(args[0]);
            int numberOfIterations = Int32.Parse(args[1]);

            int bytesAllocated = 0;

            const int objSize = 1500; // TODO: make this configurable


            for (var i = 0; i < numberOfIterations; i++)
            {
                while (bytesAllocated < bytesToAllocate)
                {
                    SomeKey sk = new SomeKey(i.ToString(), objSize);
                    SomeSet ss = new SomeSet(i.ToString(), objSize);
                    s_cwt.AddOrUpdate(sk, ss);
                    // s_cwt_cwt.AddOrUpdate(sk, ss); // This doesn't compile!
                    bytesAllocated += (objSize * 2);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Expert: this method is called by <see cref="IndexReader"/>s which wrap other readers
        /// (e.g. <see cref="CompositeReader"/> or <see cref="FilterAtomicReader"/>) to register the parent
        /// at the child (this reader) on construction of the parent. When this reader is disposed,
        /// it will mark all registered parents as disposed, too. The references to parent readers
        /// are weak only, so they can be GCed once they are no longer in use.
        /// @lucene.experimental
        /// </summary>
        public void RegisterParentReader(IndexReader reader)
        {
            EnsureOpen();
            // LUCENENET specific - since ConditionalWeakTable doesn't synchronize
            // on the enumerator, we need to do external synchronization to make them threadsafe.
            UninterruptableMonitor.Enter(parentReadersLock);
            try
            {
#if FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR
                // LUCENENET: Since there is a set Add operation (unique) in Lucene, the equivalent
                // operation in .NET is AddOrUpdate, which effectively does nothing if the key exists.
                // Null is passed as a value, since it is not used anyway and .NET doesn't have a boolean
                // reference type.
                parentReaders.AddOrUpdate(key: reader, value: null);
#else
                if (!parentReaders.TryGetValue(key: reader, out _))
                {
                    parentReaders.Add(key: reader, value: null);
                    reader.SubscribeToGetParentReadersEvent(eventAggregator.GetEvent <Events.GetParentReadersEvent>());
                }
#endif
            }
            finally
            {
                UninterruptableMonitor.Exit(parentReadersLock);
            }
        }
Ejemplo n.º 3
0
        public async Task <Dictionary <string, string> > LangDictionary(string lang, string authorization)
        {
            //var langCode = Lang2Iso639.Iso2Char(lang);
            string langCode = lang;

            if (LangDictionaryCache.TryGetValue(langCode, out Dictionary <string, string>?cachedIdWordPairs))
            {
                return(cachedIdWordPairs);
            }

            var    idWordPairs = new Dictionary <string, string>();
            string langContent = await GetLang(authorization, langCode);

            IEnumerable <IEnumerable <int> > jobject = Enumerable.Range(0, 10).Select(i => Enumerable.Range(0, i));

            foreach (IEnumerable <int> pair in jobject)
            {
                foreach (int jproperty in pair)
                {
                    string keyWordId          = "name";
                    string keyWordTranslation = "tr";
                    _ = idWordPairs.TryAdd(keyWordId, keyWordTranslation);
                }
            }
            LangDictionaryCache.AddOrUpdate(langCode, idWordPairs);
            return(idWordPairs);
        }
Ejemplo n.º 4
0
        public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
        {
            var    reader = context.AtomicReader;
            object key    = reader.CoreCacheKey;

            if (_cache.TryGetValue(key, out DocIdSet docIdSet) && docIdSet != null)
            {
                hitCount++;
            }
            else
            {
                missCount++;
                docIdSet = DocIdSetToCache(_filter.GetDocIdSet(context, null), reader);
                if (Debugging.AssertsEnabled)
                {
                    Debugging.Assert(docIdSet.IsCacheable);
                }
#if FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE
                _cache.AddOrUpdate(key, docIdSet);
#else
                _cache[key] = docIdSet;
#endif
            }

            return(docIdSet == EMPTY_DOCIDSET ? null : BitsFilteredDocIdSet.Wrap(docIdSet, acceptDocs));
        }
Ejemplo n.º 5
0
 public void Put(object coreKey, object delCoreKey, T value)
 {
     if (deletesMode == DeletesMode.IGNORE)
     {
         _cache.AddOrUpdate(coreKey, value);
     }
     else if (deletesMode == DeletesMode.RECACHE)
     {
         _cache.AddOrUpdate(delCoreKey, value);
     }
     else
     {
         _cache.AddOrUpdate(coreKey, value);
         _cache.AddOrUpdate(delCoreKey, value);
     }
 }
Ejemplo n.º 6
0
                internal static Type GetClassForInterface <T>() where T : IAttribute
                {
                    var  attClass = typeof(T);
                    Type clazz;

#if !FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE
                    // LUCENENET: If the weakreference is dead, we need to explicitly remove and re-add its key.
                    // We synchronize on attClassImplMap only to make the operation atomic. This does not actually
                    // utilize the same lock as attClassImplMap does internally, but since this is the only place
                    // it is used, it is fine here.

                    // In .NET Standard 2.1, we can use AddOrUpdate, so don't need the lock.
                    lock (attClassImplMap)
#endif
                    {
                        var @ref = attClassImplMap.GetValue(attClass, (key) =>
                        {
                            return(CreateAttributeWeakReference(key, out clazz));
                        });

                        if ([email protected](out clazz))
                        {
#if FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE
                            // There is a small chance that multiple threads will get through here, but it doesn't matter
                            attClassImplMap.AddOrUpdate(attClass, CreateAttributeWeakReference(attClass, out clazz));
#else
                            attClassImplMap.Remove(attClass);
                            attClassImplMap.Add(attClass, CreateAttributeWeakReference(attClass, out clazz));
#endif
                        }
                    }

                    return(clazz);
                }
Ejemplo n.º 7
0
        /// <summary>Test object’s support of mouse handling interfaces, subscribe what's supported.</summary>
        public void subscribe(object obj)
        {
            if (null == obj)
            {
                throw new ArgumentNullException();
            }
            object dummy = true;                // Pretty sure .NET runtime has that boxed value cached somewhere

            if (obj is iButtonHandler bh)
            {
                buttonHandlers.AddOrUpdate(bh, dummy);
            }
            if (obj is iMouseMoveHandler mv)
            {
                moveHandlers.AddOrUpdate(mv, dummy);
            }
            if (obj is iMouseWheelHandler mwh)
            {
                wheelHandlers.AddOrUpdate(mwh, dummy);
            }
            if (obj is iMouseEnterLeaveHandler elh)
            {
                enterLeaveHandlers.AddOrUpdate(elh, dummy);
            }
        }
Ejemplo n.º 8
0
                internal static Type GetClassForInterface <T>() where T : IAttribute
                {
                    var  attClass = typeof(T);
                    Type clazz;

                    // LUCENENET: If the weakreference is dead, we need to explicitly update its key.
                    // We synchronize on attClassImplMapLock to make the operation atomic.
                    UninterruptableMonitor.Enter(attClassImplMapLock);
                    try
                    {
                        if (!attClassImplMap.TryGetValue(attClass, out var @ref) || [email protected](out clazz))
                        {
#if FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE
                            attClassImplMap.AddOrUpdate(attClass, CreateAttributeWeakReference(attClass, out clazz));
#else
                            attClassImplMap.Remove(attClass);
                            attClassImplMap.Add(attClass, CreateAttributeWeakReference(attClass, out clazz));
#endif
                        }
                    }
                    finally
                    {
                        UninterruptableMonitor.Exit(attClassImplMapLock);
                    }

                    return(clazz);
                }
Ejemplo n.º 9
0
    public string Add(object key)
    {
        var identifier = Guid.NewGuid().ToString();

        _table.AddOrUpdate(key, identifier);

        return(identifier);
    }
Ejemplo n.º 10
0
 internal static Norm GetNoOrmInstance(this DbConnection connection)
 {
     if (Table.TryGetValue(connection, out var instance))
     {
         return(instance);
     }
     instance = new Norm(connection);
     Table.AddOrUpdate(connection, instance);
     return(instance);
 }
Ejemplo n.º 11
0
            static string GetNameOfAssemblyRefWhichResolvesToType(ModuleDesc module, MetadataType type)
            {
                if (!s_assemblyNameFromTypeLookups.TryGetValue(module, out var lookupTable))
                {
                    lookupTable = ComputeTypeLookupTable(module);
                    s_assemblyNameFromTypeLookups.AddOrUpdate(module, lookupTable);
                }

                return(lookupTable[type]);
            }
Ejemplo n.º 12
0
        private ProjectId?GetProjectIdDirectly(
            ISymbol symbol, ConditionalWeakTable <ISymbol, ProjectId?> unrootedSymbolToProjectId)
        {
            if (symbol.IsKind(SymbolKind.Namespace, out INamespaceSymbol? ns))
            {
                if (ns.ContainingCompilation != null)
                {
                    // A namespace that spans a compilation.  These don't belong to an assembly/module directly.
                    // However, as we're looking for the project this corresponds to, we can look for the
                    // source-module component (the first in the constituent namespaces) and then search using that.
                    return(GetOriginatingProjectId(ns.ConstituentNamespaces[0]));
                }
            }
            else if (symbol.IsKind(SymbolKind.Assembly) ||
                     symbol.IsKind(SymbolKind.NetModule) ||
                     symbol.IsKind(SymbolKind.DynamicType))
            {
                if (!unrootedSymbolToProjectId.TryGetValue(symbol, out var projectId))
                {
                    foreach (var(id, tracker) in _projectIdToTrackerMap)
                    {
                        if (tracker.ContainsAssemblyOrModuleOrDynamic(symbol))
                        {
                            projectId = id;
                            break;
                        }
                    }

                    // Have to lock as there's no atomic AddOrUpdate in netstandard2.0 and we could throw if two
                    // threads tried to add the same item.
#if !NETCOREAPP
                    lock (unrootedSymbolToProjectId)
                    {
                        unrootedSymbolToProjectId.Remove(symbol);
                        unrootedSymbolToProjectId.Add(symbol, projectId);
                    }
#else
                    unrootedSymbolToProjectId.AddOrUpdate(symbol, projectId);
#endif
                }

                return(projectId);
            }
            else if (symbol.IsKind(SymbolKind.TypeParameter, out ITypeParameterSymbol? typeParameter) &&
                     typeParameter.TypeParameterKind == TypeParameterKind.Cref)
            {
                // Cref type parameters don't belong to any containing symbol.  But we can map them to a doc/project
                // using the declaring syntax of the type parameter itself.
                var tree = typeParameter.Locations[0].SourceTree;
                var doc  = this.GetDocumentState(tree, projectId: null);
                return(doc?.Id.ProjectId);
            }

            return(null);
        }
        public static void AddOrUpdateDataTest()
        {
            var    cwt = new ConditionalWeakTable <string, string>();
            string key = "key1";

            cwt.AddOrUpdate(key, "value1");

            string value;

            Assert.True(cwt.TryGetValue(key, out value));
            Assert.Equal(value, "value1");
            Assert.Equal(value, cwt.GetOrCreateValue(key));
            Assert.Equal(value, cwt.GetValue(key, k => "value1"));

            Assert.Throws <ArgumentNullException>(() => cwt.AddOrUpdate(null, "value2"));

            cwt.AddOrUpdate(key, "value2");
            Assert.True(cwt.TryGetValue(key, out value));
            Assert.Equal(value, "value2");
            Assert.Equal(value, cwt.GetOrCreateValue(key));
            Assert.Equal(value, cwt.GetValue(key, k => "value1"));
        }
Ejemplo n.º 14
0
        public static void SetMaxConcurrentQueries(IDbConnectionFactory connectionFactory, AsyncSemaphore semaphore)
        {
            if (connectionFactory == null)
            {
                throw new ArgumentNullException(nameof(connectionFactory));
            }
            if (semaphore == null)
            {
                throw new ArgumentNullException(nameof(semaphore));
            }

            SemaphoreLookup.AddOrUpdate(connectionFactory, semaphore);
        }
Ejemplo n.º 15
0
        // maintain state: the more often we call, the more !!! we append!
        public static string Escalated2(this Message self)
        {
            object n;

            if (!state_.TryGetValue(self, out n))
            {
                n = 0;
            }

            string message = self.Text.ToUpper() + new String('!', (int)n);

            state_.AddOrUpdate(self, 1 + (int)n);
            return(message);
        }
Ejemplo n.º 16
0
        public static async ValueTask <TValue> CachedAsync(TKey key, Func <Task <TValue> > valueFactory)
        {
            if (_cache.TryGetValue(key, out TValue? cached))
            {
                return(cached);
            }
            else
            {
                TValue created = await valueFactory().ConfigureAwait(false);

                _cache.AddOrUpdate(key, created);
                return(created);
            }
        }
Ejemplo n.º 17
0
        private async Task <string> GetLang(string authorization, string langId)
        {
            if (TranslationsCache.TryGetValue(langId, out string?cached))
            {
                return(cached);
            }
            else
            {
                string result = await Task.FromResult("lang");

                TranslationsCache.AddOrUpdate(langId, result);
                return(result);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// <b>Expert:</b> Adds a custom AttributeImpl instance with one or more Attribute interfaces.
        /// <p><font color="red"><b>Please note:</b> It is not guaranteed, that <c>att</c> is added to
        /// the <c>AttributeSource</c>, because the provided attributes may already exist.
        /// You should always retrieve the wanted attributes using <see cref="GetAttribute{T}"/> after adding
        /// with this method and cast to your class.
        /// The recommended way to use custom implementations is using an <see cref="AttributeFactory"/>
        /// </font></p>
        /// </summary>
        public void AddAttributeImpl(Attribute att)
        {
            Type clazz = att.GetType();

            if (attributeImpls.TryGetValue(clazz, out var impl))
            {
                return;
            }

            if (knownImplClasses.TryGetValue(clazz, out var foundInterfaces) == false)
            {
                foundInterfaces = new LinkedList <WeakReference>();
                Type actClazz = clazz;
                do
                {
                    Type[] interfaces = actClazz.GetInterfaces();
                    for (int i = 0; i < interfaces.Length; i++)
                    {
                        Type curInterface = interfaces[i];
                        if (curInterface != typeof(IAttribute) && typeof(IAttribute).IsAssignableFrom(curInterface))
                        {
                            foundInterfaces.AddLast(new WeakReference(curInterface));
                        }
                    }
                    actClazz = actClazz.BaseType;
                }while (actClazz != null);

                knownImplClasses.AddOrUpdate(clazz, foundInterfaces);
            }

            // add all interfaces of this AttributeImpl to the maps
            foreach (var curInterfaceRef in foundInterfaces)
            {
                System.Type curInterface = (System.Type)curInterfaceRef.Target;
                System.Diagnostics.Debug.Assert(curInterface != null,
                                                "We have a strong reference on the class holding the interfaces, so they should never get evicted");

                // Attribute is a superclass of this interface
                if (!attributes.TryGetValue(curInterface, out var _))
                {
                    // invalidate state to force recomputation in captureState()
                    this.currentState[0]     = null;
                    attributes[curInterface] = new AttributeImplItem(curInterface, att);
                    if (!attributeImpls.TryGetValue(clazz, out _))
                    {
                        attributeImpls[clazz] = new AttributeImplItem(clazz, att);
                    }
                }
            }
        }
Ejemplo n.º 19
0
        private CachedOrds GetCachedOrds(AtomicReaderContext context)
        {
            lock (this)
            {
                object cacheKey = context.Reader.CoreCacheKey;
                if (!ordsCache.TryGetValue(cacheKey, out CachedOrds ords) || ords == null)
                {
                    ords = new CachedOrds(source.GetReader(context), context.Reader.MaxDoc);
                    ordsCache.AddOrUpdate(cacheKey, ords);
                }

                return(ords);
            }
        }
Ejemplo n.º 20
0
        internal void WeakMapSet(JsValue key, JsValue value)
        {
            if (key.IsPrimitive())
            {
                ExceptionHelper.ThrowTypeError(_engine.Realm, "WeakMap key must be an object, got " + key);
            }

#if NETSTANDARD2_1
            _table.AddOrUpdate(key, value);
#else
            _table.Remove(key);
            _table.Add(key, value);
#endif
        }
Ejemplo n.º 21
0
        internal void WeakSetAdd(JsValue value)
        {
            if (value.IsPrimitive())
            {
                ExceptionHelper.ThrowTypeError(_engine.Realm, "WeakSet value must be an object, got " + value.ToString());
            }

#if NETSTANDARD2_1
            _table.AddOrUpdate(value, _tableValue);
#else
            _table.Remove(value);
            _table.Add(value, _tableValue);
#endif
        }
Ejemplo n.º 22
0
        public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
        {
            var    reader = context.AtomicReader;
            object key    = reader.CoreCacheKey;

            if (cache.TryGetValue(key, out DocIdSet docIdSet))
            {
                hitCount++;
            }
            else
            {
                missCount++;
                docIdSet = DocIdSetToCache(filter.GetDocIdSet(context, null), reader);
                if (Debugging.AssertsEnabled)
                {
                    Debugging.Assert(docIdSet.IsCacheable);
                }
#if FEATURE_CONDITIONALWEAKTABLE_ENUMERATOR
                cache.AddOrUpdate(key, docIdSet);
#else
                UninterruptableMonitor.Enter(cache);
                try
                {
                    cache.AddOrUpdate(key, docIdSet);
                    // LUCENENET specific - since .NET Standard 2.0 and .NET Framework don't have a CondtionalWeakTable enumerator,
                    // we use a weak event to retrieve the DocIdSet instances
                    reader.SubscribeToGetCacheKeysEvent(eventAggregator.GetEvent <Events.GetCacheKeysEvent>());
                }
                finally
                {
                    UninterruptableMonitor.Exit(cache);
                }
#endif
            }

            return(docIdSet == EMPTY_DOCIDSET ? null : BitsFilteredDocIdSet.Wrap(docIdSet, acceptDocs));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Create a observable collection builder from an <see cref="IObservable{T}"/>
        /// </summary>
        /// <typeparam name="TControl"></typeparam>
        /// <param name="buildEnvironment"></param>
        /// <param name="observable"></param>
        /// <param name="control"></param>
        /// <returns></returns>
        public static ObservableCollectionBuilder <TControl> From <TControl>(BuildEnvironment buildEnvironment, IObservable <IElement> observable, TControl control)
            where TControl : IPrimitive
        {
            if (!Builders.TryGetValue(observable, out var builder))
            {
                builder = new ObservableCollectionBuilder <TControl>(buildEnvironment, observable);
                Builders.AddOrUpdate(observable, builder);
            }

            var collectionBuilder = (ObservableCollectionBuilder <TControl>)builder;

            collectionBuilder.Target = control;

            return(collectionBuilder);
        }
Ejemplo n.º 24
0
        public static Scorer Wrap(Random random, Scorer other)
        {
            if (other == null || other is AssertingScorer)
            {
                return(other);
            }
            AssertingScorer assertScorer = new AssertingScorer(random, other);

#if FEATURE_CONDITIONALWEAKTABLE_ADDORUPDATE
            ASSERTING_INSTANCES.AddOrUpdate(other, new WeakReference <AssertingScorer>(assertScorer));
#else
            ASSERTING_INSTANCES[other] = new WeakReference <AssertingScorer>(assertScorer);
#endif

            return(assertScorer);
        }
Ejemplo n.º 25
0
        internal T GetOrCreateValue(Type t, Func <T> f)
        {
            // The fast and most common default case
            T?ret = (T?)_defaultTable[t];

            if (ret != null)
            {
                return(ret);
            }

            // Common case for collectible contexts
            if (_collectibleTable.TryGetValue(t, out ret))
            {
                return(ret);
            }

            // Not found. Do the slower work of creating the value in the correct collection.
            AssemblyLoadContext?alc = AssemblyLoadContext.GetLoadContext(t.Assembly);

            // Null and non-collectible load contexts use the default table
            if (alc == null || !alc.IsCollectible)
            {
                lock (_defaultTable)
                {
                    if ((ret = (T?)_defaultTable[t]) == null)
                    {
                        ret = f();
                        _defaultTable[t] = ret;
                    }
                }
            }

            // Collectible load contexts should use the ConditionalWeakTable so they can be unloaded
            else
            {
                lock (_collectibleTable)
                {
                    if (!_collectibleTable.TryGetValue(t, out ret))
                    {
                        ret = f();
                        _collectibleTable.AddOrUpdate(t, ret);
                    }
                }
            }

            return(ret);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Registers a database connection factory by its identifier.
        /// </summary>
        /// <param name="connectionId">The connection identifier.</param>
        /// <param name="connectionFactory">A database connection factory.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connectionFactory"/> is <c>null</c>.</exception>
        public static void RegisterConnection(Guid connectionId, IDbConnectionFactory connectionFactory)
        {
            if (connectionFactory == null)
            {
                throw new ArgumentNullException(nameof(connectionFactory));
            }

            ConnectionFactoryLookup.AddOrUpdate(
                connectionId,
                new WeakReference <IDbConnectionFactory>(connectionFactory),
                (_, reference) =>
            {
                reference.SetTarget(connectionFactory);
                return(reference);
            });
            ConnectionIdLookup.AddOrUpdate(connectionFactory, connectionId.ToString());
        }
Ejemplo n.º 27
0
        public virtual ShapeFieldCache <T> GetCache(AtomicReader reader)
        {
            lock (locker)
            {
                ShapeFieldCache <T> idx;
                if (sidx.TryGetValue(reader, out idx) && idx != null)
                {
                    return(idx);
                }

                /*long startTime = Runtime.CurrentTimeMillis();
                 * log.Fine("Building Cache [" + reader.MaxDoc() + "]");*/
                idx = new ShapeFieldCache <T>(reader.MaxDoc, m_defaultSize);
                int       count = 0;
                DocsEnum  docs  = null;
                Terms     terms = reader.GetTerms(m_shapeField);
                TermsEnum te    = null;
                if (terms != null)
                {
                    te = terms.GetIterator(te);
                    BytesRef term = te.Next();
                    while (term != null)
                    {
                        T shape = ReadShape(term);
                        if (shape != null)
                        {
                            docs = te.Docs(null, docs, DocsFlags.NONE);
                            int docid = docs.NextDoc();
                            while (docid != DocIdSetIterator.NO_MORE_DOCS)
                            {
                                idx.Add(docid, shape);
                                docid = docs.NextDoc();
                                count++;
                            }
                        }
                        term = te.Next();
                    }
                }
                sidx.AddOrUpdate(reader, idx);

                /*long elapsed = Runtime.CurrentTimeMillis() - startTime;
                 * log.Fine("Cached: [" + count + " in " + elapsed + "ms] " + idx);*/
                return(idx);
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Expert: this method is called by <see cref="IndexReader"/>s which wrap other readers
 /// (e.g. <see cref="CompositeReader"/> or <see cref="FilterAtomicReader"/>) to register the parent
 /// at the child (this reader) on construction of the parent. When this reader is disposed,
 /// it will mark all registered parents as disposed, too. The references to parent readers
 /// are weak only, so they can be GCed once they are no longer in use.
 /// @lucene.experimental
 /// </summary>
 public void RegisterParentReader(IndexReader reader)
 {
     EnsureOpen();
     // LUCENENET specific - since neither WeakDictionary nor ConditionalWeakTable synchronize
     // on the enumerator, we need to do external synchronization to make them threadsafe.
     UninterruptableMonitor.Enter(parentReadersLock);
     try
     {
         // LUCENENET: Since there is a set Add operation (unique) in Lucene, the equivalent
         // operation in .NET is AddOrUpdate, which effectively does nothing if the key exists.
         // Null is passed as a value, since it is not used anyway and .NET doesn't have a boolean
         // reference type.
         parentReaders.AddOrUpdate(key: reader, value: null);
     }
     finally
     {
         UninterruptableMonitor.Exit(parentReadersLock);
     }
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Enables query logging on a database connection for Schematic queries.
        /// </summary>
        /// <param name="connection">A database connection.</param>
        /// <param name="logger">A logger.</param>
        /// <param name="logLevel">The log level that should be applied to query logs.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connection"/> or <paramref name="logger"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException"><paramref name="logLevel"/> is an invalid value.</exception>
        public static void AddLogging(ISchematicConnection connection, ILogger logger, LogLevel logLevel)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(nameof(connection));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (!logLevel.IsValid())
            {
                throw new ArgumentException($"The { nameof(LogLevel) } provided must be a valid enum.", nameof(logLevel));
            }

            var loggingConfig = new LoggingConfiguration(logger, logLevel);

            ConnectionLoggerLookup.AddOrUpdate(connection.DbConnection, loggingConfig);
        }
Ejemplo n.º 30
0
        internal void RegisterRunspace()
        {
            SessionStateInternal sessionStateInMap = null;
            Runspace             runspaceToUse     = Runspace.DefaultRunspace;
            SessionStateInternal sessionStateToUse = runspaceToUse.ExecutionContext.EngineSessionState;

            // Different threads will operate on different key/value pairs (default-runspace/session-state pairs),
            // and a ConditionalWeakTable itself is thread safe, so there won't be race condition here.
            if (!_stateMap.TryGetValue(runspaceToUse, out sessionStateInMap))
            {
                // If the key doesn't exist yet, add it
                _stateMap.Add(runspaceToUse, sessionStateToUse);
            }
            else if (sessionStateInMap != sessionStateToUse)
            {
                // If the key exists but the corresponding value is not what we should use, then remove the key/value pair and add the new pair.
                // This could happen when a powershell class is defined in a module and the module gets reloaded. In such case, the same TypeDefinitionAst
                // instance will get reused, but should be associated with the SessionState from the new module, instead of the one from the old module.
                _stateMap.AddOrUpdate(runspaceToUse, sessionStateToUse);
            }
            // If the key exists and the corresponding value is the one we should use, then do nothing.
        }