System.Collections.Concurrent.ConcurrentDictionary.GetOrAdd(System.Type, System.Func, TArg)

Here are the examples of the csharp api System.Collections.Concurrent.ConcurrentDictionary.GetOrAdd(System.Type, System.Func, TArg) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

811 Examples 7

19 View Source File : AuthorizeModule.cs
License : GNU General Public License v3.0
Project Creator : bonarr

public override Func<HubDescriptor, IRequest, bool> BuildAuthorizeConnect(Func<HubDescriptor, IRequest, bool> authorizeConnect)
        {
            return base.BuildAuthorizeConnect((hubDescriptor, request) =>
            {
                // Execute custom modules first and short circuit if any deny authorization.
                if (!authorizeConnect(hubDescriptor, request))
                {
                    return false;
                }

                // Execute the global hub connection authorizer if there is one next and short circuit if it denies authorization.
                if (_globalConnectionAuthorizer != null && !_globalConnectionAuthorizer.AuthorizeHubConnection(hubDescriptor, request))
                {
                    return false;
                }

                // Get hub attributes implementing IAuthorizeHubConnection from the cache
                // If the attributes do not exist in the cache, retrieve them using reflection and add them to the cache
                var attributeAuthorizers = _connectionAuthorizersCache.GetOrAdd(hubDescriptor.HubType,
                    hubType => hubType.GetCustomAttributes(typeof(IAuthorizeHubConnection), inherit: true).Cast<IAuthorizeHubConnection>());

                // Every attribute (if any) implementing IAuthorizeHubConnection attached to the relevant hub MUST allow the connection
                return attributeAuthorizers.All(a => a.AuthorizeHubConnection(hubDescriptor, request));
            });
        }

19 View Source File : SchemaBuilder.cs
License : MIT License
Project Creator : ch-robinson

public override ISchemaBuildResult BuildSchema(TypeResolution resolution, ConcurrentDictionary<Type, Schema> cache)
        {
            var result = new SchemaBuildResult();

            if (resolution is EnumResolution @enum)
            {
                result.Schema = cache.GetOrAdd(@enum.Type.GetUnderlyingType(), _ =>
                {
                    if (@enum.IsFlagEnum)
                    {
                        return SchemaBuilder.BuildSchema(@enum.UnderlyingType, cache);
                    }
                    else
                    {
                        var name = @enum.Namespace == null
                            ? @enum.Name.Value
                            : $"{@enum.Namespace.Value}.{@enum.Name.Value}";

                        var schema = new EnumSchema(name);

                        foreach (var symbol in @enum.Symbols)
                        {
                            schema.Symbols.Add(symbol.Name.Value);
                        }

                        return schema;
                    }
                });
            }
            else
            {
                result.Exceptions.Add(new UnsupportedTypeException(resolution.Type));
            }

            return result;
        }

19 View Source File : NegotiateMatcherPolicy.cs
License : MIT License
Project Creator : Azure

public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
        {
            for (var i = 0; i < candidates.Count; i++)
            {
                ref var candidate = ref candidates[i];
                // Only apply to RouteEndpoint
                if (candidate.Endpoint is RouteEndpoint routeEndpoint)
                {
                    var hubMetadata = routeEndpoint.Metadata.GetMetadata<HubMetadata>();
                    // skip endpoint not apply hub.
                    if (hubMetadata != null)
                    {
                        var newEndpoint = _negotiateEndpointCache.GetOrAdd(hubMetadata.HubType, CreateNegotiateEndpoint(hubMetadata.HubType, routeEndpoint));

                        candidates.ReplaceEndpoint(i, newEndpoint, candidate.Values);
                    }
                }
            }

            return Task.CompletedTask;
        }

19 View Source File : OutboundLoggerFactory.cs
License : MIT License
Project Creator : BEagle1984

public OutboundLogger GetOutboundLogger(IEndpoint endpoint)
        {
            return _outboundLoggers.GetOrAdd(
                endpoint.GetType(),
                _ => new OutboundLogger(_enricherFactory.GetLogEnricher(endpoint)));
        }

19 View Source File : MockServiceSideConnection.cs
License : MIT License
Project Creator : Azure

private void EnqueueMessage(ServiceMessage m) =>
            _messagesFromSDK.GetOrAdd(m.GetType(), _ => CreateChannel<ServiceMessage>()).Writer.TryWrite(m);

19 View Source File : CustomSerializationTests.cs
License : MIT License
Project Creator : Azure

public override void BindToName(Type serializedType, out string replacedemblyName, out string typeName)
            {
                replacedemblyName = null;
                typeName = this._typeToNameMapping.GetOrAdd(serializedType, _ =>
                {
                    return string.Format(CultureInfo.InvariantCulture, "{0}|{1}", _.FullName, _.Getreplacedembly().GetName().Name);
                });

                this._nameToTypeMapping.TryAdd(typeName, serializedType);
            }

19 View Source File : SchemaBuilder.cs
License : MIT License
Project Creator : ch-robinson

public override ISchemaBuildResult BuildSchema(TypeResolution resolution, ConcurrentDictionary<Type, Schema> cache)
        {
            var result = new SchemaBuildResult();

            if (resolution is ByteArrayResolution bytes)
            {
                result.Schema = cache.GetOrAdd(bytes.Type.GetUnderlyingType(), _ => new BytesSchema());
            }
            else
            {
                result.Exceptions.Add(new UnsupportedTypeException(resolution.Type));
            }

            return result;
        }

19 View Source File : DefaultDdbConverterFactory.cs
License : MIT License
Project Creator : AllocZero

public static DdbConverter? CreateFromType(Type sourceType)
        {
            return ConvertersFromTypeCache.GetOrAdd(sourceType, st =>
            {
                var type = Nullable.GetUnderlyingType(st) ?? st;

                // TODO: Add DateTimeOffset converters
                var converter = type switch
                {
                    _ when type == typeof(string) => Create<StringDdbConverter>(),
                    _ when type == typeof(DateTime) => ConvertersCache.GetOrAdd(typeof(DateTime),
                        x => new DateTimeDdbConverter("O", 28) {DateTimeStyles = DateTimeStyles.RoundtripKind}),
                    _ when type == typeof(int) => Create<IntDdbConverter>(),
                    _ when type == typeof(double) => Create<DoubleDdbConverter>(),
                    _ when type == typeof(long) => Create<LongDdbConverter>(),
                    _ when type == typeof(decimal) => Create<DecimalDdbConverter>(),
                    _ when type == typeof(bool) => Create<BoolDdbConverter>(),
                    _ when type == typeof(Guid) => Create<GuidDdbConverter>(),
                    _ when type.IsEnum => CreateEnumConverter(type),
                    _ when type == typeof(byte) => Create<ByteDdbConverter>(),
                    _ when type == typeof(short) => Create<ShortDdbConverter>(),
                    _ when type == typeof(ushort) => Create<UShortDdbConverter>(),
                    _ when type == typeof(uint) => Create<UIntDdbConverter>(),
                    _ when type == typeof(ulong) => Create<ULongDdbConverter>(),
                    _ when type == typeof(float) => Create<FloatDdbConverter>(),
                    _ when type == typeof(byte[]) => Create<BinaryDdbConverter>(),
                    _ when type == typeof(List<byte[]>) => Create<ListBinarySetDdbConverter>(),
                    _ when type == typeof(IList<byte[]>) => Create<IListBinarySetDdbConverter>(),
                    _ => null
                };

                return converter;
            }

19 View Source File : SchemaBuilder.cs
License : MIT License
Project Creator : ch-robinson

public override ISchemaBuildResult BuildSchema(TypeResolution resolution, ConcurrentDictionary<Type, Schema> cache)
        {
            var result = new SchemaBuildResult();

            if (resolution is UriResolution uri)
            {
                result.Schema = cache.GetOrAdd(uri.Type.GetUnderlyingType(), _ => new StringSchema());
            }
            else
            {
                result.Exceptions.Add(new UnsupportedTypeException(resolution.Type));
            }

            return result;
        }

19 View Source File : RavenDbAggregateEventProcessor.cs
License : MIT License
Project Creator : ARKlab

private async Task _exec(SubscriptionBatch<AggregateEventStore> batch)
		{
			_logger.Trace($"Got a batch of {batch.NumberOfItemsInBatch} items");

			var tasks = batch.Items.GroupBy(x => x.Result.AggregateId)
				.Select(async g =>
				{
					foreach (var e in g)
					{
						AggregateEventEnvelope<TAggregate> envelope = e.Result.FromStore<TAggregate>();
						var evtType = envelope.Event.GetType();
						var methodToInvoke = _dispatchMethods
							.GetOrAdd(evtType, type => _getDispatchMethod(evtType));

						await (Task)methodToInvoke.Invoke(this, new object[] { envelope.Event, envelope.Metadata });
					}
				});


			await Task.WhenAll(tasks);
		}

19 View Source File : ActivityEnricherFactory.cs
License : MIT License
Project Creator : BEagle1984

public IBrokerActivityEnricher GetActivityEnricher(IEndpoint endpoint)
        {
            var enricherType = _enricherTypeCache.GetOrAdd(
                endpoint.GetType(),
                type => typeof(IBrokerActivityEnricher<>)
                    .MakeGenericType(type));

            var activityEnricher = (IBrokerActivityEnricher?)_serviceProvider.GetService(enricherType);

            return activityEnricher ?? NullEnricherInstance;
        }

19 View Source File : MockServiceSideConnection.cs
License : MIT License
Project Creator : Azure

public ValueTask<bool> WaitToDequeueMessageAsync<TServiceMessage>() where TServiceMessage : ServiceMessage =>
            _messagesFromSDK.GetOrAdd(typeof(TServiceMessage), _ => CreateChannel<ServiceMessage>()).Reader.WaitToReadAsync();

19 View Source File : EntityReflector.cs
License : MIT License
Project Creator : Avanade

public EnreplacedyReflector<TEnreplacedy> GetReflector<TEnreplacedy>() where TEnreplacedy : clreplaced, new()
        {
            return (EnreplacedyReflector<TEnreplacedy>)Cache.GetOrAdd(typeof(TEnreplacedy), (type) =>
            {
                var er = new EnreplacedyReflector<TEnreplacedy>(this);
                EnreplacedyBuilder?.Invoke(er);
                return er;
            });
        }

19 View Source File : DelegateServiceProvdier.cs
License : GNU General Public License v3.0
Project Creator : blqw

public object GetService(Type serviceType)
        {
            if (typeof(IServiceProvider) == serviceType)
            {
                return this;
            }
            // 从 _provider 中获取服务
            var service = _provider.GetService(serviceType);


            if (service == null)
            {
                // 当常规方式没有获取到服务,且服务是委托类型时,尝试获取MethodInfo服务,并返回最后一个签名相同的MethodInfo并转换为指定类型的委托
                return typeof(Delegate).IsreplacedignableFrom(serviceType)
                        ? _services.GetOrAdd(serviceType, x => ConvertDelegate(x, _provider.GetServices<MethodInfo>()))
                        : null;
            }

            if (service is Delegate delegateService)
            {
                // 当获取的服务是委托,但与要求的类型不符时,尝试转换委托类型
                if (serviceType is IServiceProvider tp
                    && tp.GetService(typeof(Type)) is Type delegateType
                    && typeof(Delegate).IsreplacedignableFrom(delegateType)
                    && !delegateType.IsInstanceOfType(service))
                {
                    return _services.GetOrAdd(serviceType, x => ConvertDelegate(delegateType, new[] { delegateService.Method }));
                }
                return service;
            }

            if (service is IEnumerable enumerable && serviceType.IsGenericType && serviceType.GetGenericArguments().Length == 1)
            {
                // 当获取的服务是泛型集合时
                var type = serviceType.GetGenericArguments()[0];
                if (type is IServiceProvider tp && tp.GetService(typeof(Type)) is Type delegateType)
                {
                    return _services.GetOrAdd(serviceType, x => ConvertDelegates(delegateType, enumerable));
                }
                else
                {
                    return _services.GetOrAdd(serviceType, x => ConvertDelegates(type, _provider.GetServices<MethodInfo>()));
                }
            }
            return service;
        }

19 View Source File : ExtensionManager.cs
License : MIT License
Project Creator : actions

public List<T> GetExtensions<T>() where T : clreplaced, IExtension
        {
            Trace.Info("Getting extensions for interface: '{0}'", typeof(T).FullName);
            List<IExtension> extensions = _cache.GetOrAdd(
                key: typeof(T),
                valueFactory: (Type key) =>
                {
                    return LoadExtensions<T>();
                });
            return extensions.Select(x => x as T).ToList();
        }

19 View Source File : StorageBus.cs
License : MIT License
Project Creator : BookBeat

private IStorageQueueClient GetClient<T>() where T : clreplaced, ICommand
        {
            return _queueClients.GetOrAdd(typeof(T), type =>
            {
                var serializer = _options.MessageSerializer;
                var mapping = AutoMessageMapper.GetMapping<T>();
                if (mapping is ICustomMessageSerializer customSerializer) serializer = customSerializer.MessageSerializer;
                return new StorageQueueClient(_options, serializer, _attachmentProvider, AutoMessageMapper.GetQueueName<T>());
            });
        }

19 View Source File : DurableEntityProxyHelpers.cs
License : MIT License
Project Creator : Azure

internal static string ResolveEnreplacedyName<TEnreplacedyInterface>()
        {
            var type = EnreplacedyNameMappings.GetOrAdd(typeof(TEnreplacedyInterface), CreateTypeMapping);

            return type.Name;
        }

19 View Source File : SchemaBuilder.cs
License : MIT License
Project Creator : ch-robinson

public override ISchemaBuildResult BuildSchema(TypeResolution resolution, ConcurrentDictionary<Type, Schema> cache)
        {
            var result = new SchemaBuildResult();

            if (resolution is FloatingPointResolution @double && @double.Size == 16)
            {
                result.Schema = cache.GetOrAdd(@double.Type.GetUnderlyingType(), _ => new DoubleSchema());
            }
            else
            {
                result.Exceptions.Add(new UnsupportedTypeException(resolution.Type));
            }

            return result;
        }

19 View Source File : DbContext.cs
License : MIT License
Project Creator : 2881099

internal void InitPropSets() {
			var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp => 
				tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
					.Where(a => a.PropertyType.IsGenericType &&
						a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());

			foreach (var prop in props) {
				var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);

				prop.SetValue(this, set);
				AllSets.Add(prop.Name, set);
			}
		}

19 View Source File : SchemaBuilder.cs
License : MIT License
Project Creator : ch-robinson

public override ISchemaBuildResult BuildSchema(TypeResolution resolution, ConcurrentDictionary<Type, Schema> cache)
        {
            var result = new SchemaBuildResult();

            if (resolution is TimestampResolution timestamp)
            {
                result.Schema = cache.GetOrAdd(timestamp.Type.GetUnderlyingType(), _ => TemporalBehavior switch
                {
                    TemporalBehavior.EpochMicroseconds => new LongSchema()
                    {
                        LogicalType = new MicrosecondTimestampLogicalType()
                    },
                    TemporalBehavior.EpochMilliseconds => new LongSchema()
                    {
                        LogicalType = new MillisecondTimestampLogicalType()
                    },
                    TemporalBehavior.Iso8601 => new StringSchema(),
                    _ => throw new ArgumentOutOfRangeException(nameof(TemporalBehavior))
                });
            }

19 View Source File : MockServiceSideClientConnection.cs
License : MIT License
Project Creator : Azure

public async Task<TServiceMessage> DequeueMessageAsync<TServiceMessage>() where TServiceMessage : HubMessage =>
            await _hubMessagesFromSDK.GetOrAdd(typeof(TServiceMessage), _ => CreateChannel<HubMessage>()).Reader.ReadAsync() as TServiceMessage;

19 View Source File : MockServiceSideClientConnection.cs
License : MIT License
Project Creator : Azure

public ValueTask<bool> WaitToDequeueMessageAsync<TServiceMessage>() where TServiceMessage : ServiceMessage =>
            _hubMessagesFromSDK.GetOrAdd(typeof(TServiceMessage), _ => CreateChannel<HubMessage>()).Reader.WaitToReadAsync();

19 View Source File : DbSetSync.cs
License : MIT License
Project Creator : 2881099

void AddOrUpdateNavigateList(TEnreplacedy item) {
			Type itemType = null;
			foreach (var prop in _table.Properties) {
				if (_table.ColumnsByCsIgnore.ContainsKey(prop.Key)) continue;
				if (_table.ColumnsByCs.ContainsKey(prop.Key)) continue;

				object propVal = null;

				if (itemType == null) itemType = item.GetType();
				if (_table.TypeLazy != null && itemType == _table.TypeLazy) {
					var lazyField = _dicLazyIsSetField.GetOrAdd(_table.TypeLazy, tl => new ConcurrentDictionary<string, FieldInfo>()).GetOrAdd(prop.Key, propName =>
						_table.TypeLazy.GetField($"__lazy__{propName}", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance));
					if (lazyField != null) {
						var lazyFieldValue = (bool)lazyField.GetValue(item);
						if (lazyFieldValue == false) continue;
					}
					propVal = prop.Value.GetValue(item);
				} else {
					propVal = prop.Value.GetValue(item);
					if (propVal == null) continue;
				}

				var tref = _table.GetTableRef(prop.Key, true);
				if (tref == null) continue;

				switch(tref.RefType) {
					case Internal.Model.TableRefType.OneToOne:
					case Internal.Model.TableRefType.ManyToOne:
					case Internal.Model.TableRefType.ManyToMany:
						continue;
					case Internal.Model.TableRefType.OneToMany:
						var propValEach = propVal as IEnumerable;
						if (propValEach == null) continue;
						object dbset = null;
						MethodInfo dbsetAddOrUpdate = null;
						foreach (var propValItem in propValEach) {
							if (dbset == null) {
								dbset = _ctx.Set(tref.RefEnreplacedyType);
								dbsetAddOrUpdate = dbset.GetType().GetMethod("AddOrUpdate", new Type[] { tref.RefEnreplacedyType });
							}
							for (var colidx = 0; colidx < tref.Columns.Count; colidx++) {
								tref.RefColumns[colidx].Table.Properties[tref.RefColumns[colidx].CsName]
									.SetValue(propValItem, tref.Columns[colidx].Table.Properties[tref.Columns[colidx].CsName].GetValue(item));
							}
							dbsetAddOrUpdate.Invoke(dbset, new object[] { propValItem });
						}
						break;
				}
			}
		}

19 View Source File : MockServiceSideConnection.cs
License : MIT License
Project Creator : Azure

public async Task<TServiceMessage> DequeueMessageAsync<TServiceMessage>() where TServiceMessage : ServiceMessage =>
            await _messagesFromSDK.GetOrAdd(typeof(TServiceMessage), _ => CreateChannel<ServiceMessage>()).Reader.ReadAsync() as TServiceMessage;

protected virtual string BuildXPath(ISearchContext scope, ComponentScopeLocateOptions options)
        {
            List<ColumnInfo> columns = TableColumnsInfoCache.GetOrAdd(
                options.Metadata.ParentComponentType,
                _ => GetColumnInfoItems((IWebElement)scope));

            ColumnInfo column = columns.
                Where(x => options.Match.IsMatch(x.HeaderName, options.Terms)).
                ElementAtOrDefault(options.Index ?? 0);

            return column != null ? BuildXPathForCell(column, columns) : null;
        }

19 View Source File : InboundLoggerFactory.cs
License : MIT License
Project Creator : BEagle1984

public InboundLogger GetInboundLogger(IEndpoint endpoint) =>
            _inboundLoggers.GetOrAdd(
                endpoint.GetType(),
                _ => new InboundLogger(_enricherFactory.GetLogEnricher(endpoint)));

19 View Source File : ServiceConnectionProxy.cs
License : MIT License
Project Creator : Azure

public Task<ServiceMessage> WaitForApplicationMessageAsync(Type type)
        {
            return _waitForApplicationMessage.GetOrAdd(type, key => new TaskCompletionSource<ServiceMessage>()).Task;
        }

19 View Source File : RequestAuthorizationBehavior.cs
License : MIT License
Project Creator : AustinDavies

private Type FindHandlerType(IAuthorizationRequirement requirement)
        {

            var requirementType = requirement.GetType();
            var handlerType = _requirementHandlers.GetOrAdd(requirementType,
                requirementTypeKey =>
                {
                    var wrapperType = typeof(IAuthorizationHandler<>).MakeGenericType(requirementTypeKey);

                    return wrapperType;
                });

            if (handlerType == null)
                return null;

            return handlerType;
        }

19 View Source File : BrokerLogEnricherFactory.cs
License : MIT License
Project Creator : BEagle1984

public IBrokerLogEnricher GetLogEnricher(IEndpoint endpoint)
        {
            var enricherType = _enricherTypeCache.GetOrAdd(
                endpoint.GetType(),
                type => typeof(IBrokerLogEnricher<>)
                    .MakeGenericType(type));

            var logEnricher = (IBrokerLogEnricher?)_serviceProvider.GetService(enricherType);

            return logEnricher ?? NullEnricherInstance;
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static object FromObject(this Type targetType, object value, Encoding encoding = null)
    {
        if (targetType == typeof(object)) return value;
        if (encoding == null) encoding = Encoding.UTF8;
        var valueIsNull = value == null;
        var valueType = valueIsNull ? typeof(string) : value.GetType();
        if (valueType == targetType) return value;
        if (valueType == typeof(byte[])) //byte[] -> guid
        {
            if (targetType == typeof(Guid))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
            }
            if (targetType == typeof(Guid?))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
            }
        }
        if (targetType == typeof(byte[])) //guid -> byte[]
        {
            if (valueIsNull) return null;
            if (valueType == typeof(Guid) || valueType == typeof(Guid?))
            {
                var bytes = new byte[16];
                var guidN = ((Guid)value).ToString("N");
                for (var a = 0; a < guidN.Length; a += 2)
                    bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
                return bytes;
            }
            return encoding.GetBytes(value.ToInvariantCultureToString());
        }
        else if (targetType.IsArray)
        {
            if (value is Array valueArr)
            {
                var targetElementType = targetType.GetElementType();
                var sourceArrLen = valueArr.Length;
                var target = Array.CreateInstance(targetElementType, sourceArrLen);
                for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
                return target;
            }
            //if (value is IList valueList)
            //{
            //    var targetElementType = targetType.GetElementType();
            //    var sourceArrLen = valueList.Count;
            //    var target = Array.CreateInstance(targetElementType, sourceArrLen);
            //    for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
            //    return target;
            //}
        }
        var func = _dicFromObject.GetOrAdd(targetType, tt =>
        {
            if (tt == typeof(object)) return vs => vs;
            if (tt == typeof(string)) return vs => vs;
            if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
            if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
            if (tt == typeof(bool)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                }
                return false;
            };
            if (tt == typeof(bool?)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                    case "false":
                    case "0":
                        return false;
                }
                return null;
            };
            if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
            if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
            if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
            if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
            if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
            if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
            if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
            if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
            if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
            if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
            if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
            if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
            if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
            if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
            if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
            if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
            if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
            if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
            if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
            if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
            if (tt.NullableTypeOrThis().IsEnum)
            {
                var tttype = tt.NullableTypeOrThis();
                var ttdefval = tt.CreateInstanceGetDefaultValue();
                return vs =>
                {
                    if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
                    return Enum.Parse(tttype, vs, true);
                };
            }
            var localTargetType = targetType;
            var localValueType = valueType;
            return vs =>
            {
                if (vs == null) return null;
                throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
            };
        });
        var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
        return func(valueStr);
    }

19 View Source File : ClayInteceptor.cs
License : MIT License
Project Creator : bleroy

private static void AdjustReturnValue(IInvocation invocation) {
            var methodReturnType = invocation.Method.ReturnType;
            if (methodReturnType == typeof(void))
                return;

            if (invocation.ReturnValue == null)
                return;

            var returnValueType = invocation.ReturnValue.GetType();
            if (methodReturnType.IsreplacedignableFrom(returnValueType))
                return;

            var callSite = _convertSites.GetOrAdd(
                methodReturnType,
                x => CallSite<Func<CallSite, object, object>>.Create(
                    Binder.Convert(CSharpBinderFlags.None, x, null)));

            invocation.ReturnValue = callSite.Target(callSite, invocation.ReturnValue);
        }

19 View Source File : InstrumentationDaemon.cs
License : MIT License
Project Creator : azist

public void Record(Datum datum)
    {
      if (Status != DaemonStatus.Active) return;
      if (datum == null) return;

      datum.InitDefaultFields(App);

      if (Overflown) return;

      var t = datum.GetType();

      var srcBucketed = m_TypeBucketed.GetOrAdd(t, (tp) => new SrcBucketedData());

      if (srcBucketed.DefaultDatum == null)
        srcBucketed.DefaultDatum = datum;

      var bag = srcBucketed.GetOrAdd(datum.Source, (src) => new DatumBag());

      bag.Add(datum);
      Interlocked.Increment(ref m_RecordCount);
    }

19 View Source File : AuthorizeModule.cs
License : GNU General Public License v3.0
Project Creator : bonarr

public override Func<IHubIncomingInvokerContext, Task<object>> BuildIncoming(Func<IHubIncomingInvokerContext, Task<object>> invoke)
        {
            return base.BuildIncoming(context =>
            {
                // Execute the global method invocation authorizer if there is one and short circuit if it denies authorization.
                if (_globalInvocationAuthorizer == null || _globalInvocationAuthorizer.AuthorizeHubMethodInvocation(context, appliesToMethod: false))
                {
                    // Get hub attributes implementing IAuthorizeHubMethodInvocation from the cache
                    // If the attributes do not exist in the cache, retrieve them using reflection and add them to the cache
                    var clreplacedLevelAuthorizers = _clreplacedInvocationAuthorizersCache.GetOrAdd(context.Hub.GetType(),
                        hubType => hubType.GetCustomAttributes(typeof(IAuthorizeHubMethodInvocation), inherit: true).Cast<IAuthorizeHubMethodInvocation>());

                    // Execute all hub level authorizers and short circuit if ANY deny authorization.
                    if (clreplacedLevelAuthorizers.All(a => a.AuthorizeHubMethodInvocation(context, appliesToMethod: false)))
                    {
                        // If the MethodDescriptor is a NullMethodDescriptor, we don't want to cache it since a new one is created
                        // for each invocation with an invalid method name. #1801
                        if (context.MethodDescriptor is NullMethodDescriptor)
                        {
                            return invoke(context);
                        }

                        // Get method attributes implementing IAuthorizeHubMethodInvocation from the cache
                        // If the attributes do not exist in the cache, retrieve them from the MethodDescriptor and add them to the cache
                        var methodLevelAuthorizers = _methodInvocationAuthorizersCache.GetOrAdd(context.MethodDescriptor,
                            methodDescriptor => methodDescriptor.Attributes.OfType<IAuthorizeHubMethodInvocation>());
                        
                        // Execute all method level authorizers. If ALL provide authorization, continue executing the invocation pipeline.
                        if (methodLevelAuthorizers.All(a => a.AuthorizeHubMethodInvocation(context, appliesToMethod: true)))
                        {
                            return invoke(context);
                        }
                    }
                }
                
                // Send error back to the client
                return TaskAsyncHelper.FromError<object>(
                    new NotAuthorizedException(String.Format(CultureInfo.CurrentCulture, Resources.Error_CallerNotAuthorizedToInvokeMethodOn,
                                                             context.MethodDescriptor.Name,
                                                             context.MethodDescriptor.Hub.Name)));
            });
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static Dictionary<string, FieldInfo> GetFieldsDictIgnoreCase(this Type that) => that == null ? null : _dicGetFieldsDictIgnoreCase.GetOrAdd(that, tp =>
    {
        var fields = that.GetFields().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
        var dict = new Dictionary<string, FieldInfo>(StringComparer.CurrentCultureIgnoreCase);
        foreach (var field in fields)
        {
            if (dict.ContainsKey(field.Name)) dict[field.Name] = field;
            else dict.Add(field.Name, field);
        }
        return dict;
    });

19 View Source File : ServiceBus.cs
License : MIT License
Project Creator : BookBeat

private IMessageSerializer GetSerializer<T>() where T : IMessage
        {
            return _serializers.GetOrAdd(typeof(T), type =>
            {
                var mapper = AutoMessageMapper.GetMapping<T>();
                if (mapper is ICustomMessageSerializer serializer) return serializer.MessageSerializer;
                return _configuration.MessageSerializer;
            });
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : Azure

public static string ToCSTypeName(this Type type)
        {
            return typeNames.GetOrAdd(type, GetPrettyName);
        }

19 View Source File : SelfReferenceEquivalencyAssertionOptions.cs
License : Apache License 2.0
Project Creator : BoundfoxStudios

EqualityStrategy IEquivalencyreplacedertionOptions.GetEqualityStrategy(Type type)
        {
            EqualityStrategy strategy;

            if (referenceTypes.Any(type.IsSameOrInherits))
            {
                strategy = EqualityStrategy.ForceMembers;
            }
            else if (valueTypes.Any(type.IsSameOrInherits))
            {
                strategy = EqualityStrategy.ForceEquals;
            }
            else
            {
                if (getDefaultEqualityStrategy != null)
                {
                    strategy = getDefaultEqualityStrategy(type);
                }
                else
                {
                    bool hasValueSemantics = hasValueSemanticsMap.GetOrAdd(type, t => t.HasValueSemantics());

                    if (hasValueSemantics)
                    {
                        strategy = EqualityStrategy.Equals;
                    }
                    else
                    {
                        strategy = EqualityStrategy.Members;
                    }
                }
            }

            return strategy;
        }

19 View Source File : AssociatedAssemblyNameAttribute.cs
License : MIT License
Project Creator : adams85

public static replacedociatedreplacedemblyNameAttribute? GetCachedFor(Type type) => s_attributeCache.GetOrAdd(type, type => type.GetCustomAttribute<replacedociatedreplacedemblyNameAttribute>());

19 View Source File : SchemaBuilder.cs
License : MIT License
Project Creator : ch-robinson

public override ISchemaBuildResult BuildSchema(TypeResolution resolution, ConcurrentDictionary<Type, Schema> cache)
        {
            var result = new SchemaBuildResult();

            if (resolution is DecimalResolution @decimal)
            {
                result.Schema = cache.GetOrAdd(@decimal.Type.GetUnderlyingType(), _ => new BytesSchema()
                {
                    LogicalType = new DecimalLogicalType(@decimal.Precision, @decimal.Scale)
                });
            }
            else
            {
                result.Exceptions.Add(new UnsupportedTypeException(resolution.Type));
            }

            return result;
        }

19 View Source File : EntityProxyFactory.cs
License : MIT License
Project Creator : Azure

internal static TEnreplacedyInterface Create<TEnreplacedyInterface>(IEnreplacedyProxyContext context, EnreplacedyId enreplacedyId)
        {
            var type = TypeMappings.GetOrAdd(typeof(TEnreplacedyInterface), CreateProxyType);

            return (TEnreplacedyInterface)Activator.CreateInstance(type, context, enreplacedyId);
        }

19 View Source File : SchemaBuilder.cs
License : MIT License
Project Creator : ch-robinson

public override ISchemaBuildResult BuildSchema(TypeResolution resolution, ConcurrentDictionary<Type, Schema> cache)
        {
            var result = new SchemaBuildResult();

            if (resolution is DurationResolution duration)
            {
                result.Schema = cache.GetOrAdd(duration.Type.GetUnderlyingType(), _ => new StringSchema());
            }
            else
            {
                result.Exceptions.Add(new UnsupportedTypeException(resolution.Type));
            }

            return result;
        }

19 View Source File : DbMetaInfoProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public List<DbColumnMetaInfo> GetColumns(Type type)
        {
            return _columns.GetOrAdd(type, t =>
            {
                var list = new List<DbColumnMetaInfo>();
                var properties = type.GetProperties();
                foreach (var item in properties)
                {
                    var columnName = item.Name;
                    var isPrimaryKey = false;
                    var isDefault = false;
                    var isIdenreplacedy = false;
                    var isNotMapped = false;
                    var isConcurrencyCheck = false;
                    var isComplexType = false;
                    if (item.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault() != null)
                    {
                        var attribute = item.GetCustomAttributes(typeof(ColumnAttribute), true)
                            .FirstOrDefault() as ColumnAttribute;
                        columnName = attribute.Name;
                    }
                    if (item.GetCustomAttributes(typeof(PrimaryKeyAttribute), true).FirstOrDefault() != null)
                    {
                        isPrimaryKey = true;
                    }
                    if (item.GetCustomAttributes(typeof(IdenreplacedyAttribute), true).FirstOrDefault() != null)
                    {
                        isIdenreplacedy = true;
                    }
                    if (item.GetCustomAttributes(typeof(DefaultAttribute), true).FirstOrDefault() != null)
                    {
                        isDefault = true;
                    }
                    if (item.GetCustomAttributes(typeof(ConcurrencyCheckAttribute), true).FirstOrDefault() != null)
                    {
                        isConcurrencyCheck = true;
                    }
                    if (item.GetCustomAttributes(typeof(NotMappedAttribute), true).FirstOrDefault() != null)
                    {
                        isNotMapped = true;
                    }
                    if (item.GetCustomAttributes(typeof(ComplexTypeAttribute), true).FirstOrDefault() != null)
                    {
                        isComplexType = true;
                    }
                    list.Add(new DbColumnMetaInfo()
                    {
                        CsharpType = item.PropertyType,
                        IsDefault = isDefault,
                        ColumnName = columnName,
                        CsharpName = item.Name,
                        IsPrimaryKey = isPrimaryKey,
                        IsIdenreplacedy = isIdenreplacedy,
                        IsNotMapped = isNotMapped,
                        IsConcurrencyCheck = isConcurrencyCheck,
                        IsComplexType = isComplexType
                    });
                }
                return list;
            });
        }

19 View Source File : SchemaBuilder.cs
License : MIT License
Project Creator : ch-robinson

public override ISchemaBuildResult BuildSchema(TypeResolution resolution, ConcurrentDictionary<Type, Schema> cache)
        {
            var result = new SchemaBuildResult();

            if (resolution is StringResolution @string)
            {
                result.Schema = cache.GetOrAdd(@string.Type.GetUnderlyingType(), _ => new StringSchema());
            }
            else
            {
                result.Exceptions.Add(new UnsupportedTypeException(resolution.Type));
            }

            return result;
        }

19 View Source File : MockServiceSideClientConnection.cs
License : MIT License
Project Creator : Azure

public void EnqueueMessage(HubMessage m) =>
            _hubMessagesFromSDK.GetOrAdd(m.GetType(), _ => CreateChannel<HubMessage>()).Writer.TryWrite(m);

19 View Source File : DynamoDbContextMetadata.cs
License : MIT License
Project Creator : AllocZero

private DdbConverter GetOrAddNestedObjectConverter(Type propertyType)
        {
            var converterType = typeof(ObjectDdbConverter<>).MakeGenericType(propertyType);

            return _factoryConvertersCache.GetOrAdd(propertyType, (x, metadata) => (DdbConverter) Activator.CreateInstance(converterType, metadata)!, this)!;
        }

19 View Source File : DbMetaInfoProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public DbTableMetaInfo GetTable(Type type)
        {
            return _tables.GetOrAdd(type, t =>
            {
                var name = t.Name;
                if (t.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault() != null)
                {
                    var attribute = t.GetCustomAttributes(typeof(TableAttribute), true)
                        .FirstOrDefault() as TableAttribute;
                    name = attribute.Name;
                }
                var table = new DbTableMetaInfo()
                {
                    TableName = name,
                    CsharpName = t.Name
                };
                return table;
            });
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static Dictionary<string, PropertyInfo> GetPropertiesDictIgnoreCase(this Type that) => that == null ? null : _dicGetPropertiesDictIgnoreCase.GetOrAdd(that, tp =>
    {
        var props = that.GetProperties().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
        var dict = new Dictionary<string, PropertyInfo>(StringComparer.CurrentCultureIgnoreCase);
        foreach (var prop in props)
        {
            if (dict.TryGetValue(prop.Name, out var existsProp))
            {
                if (existsProp.DeclaringType != prop) dict[prop.Name] = prop;
                continue;
            }
            dict.Add(prop.Name, prop);
        }
        return dict;
    });

19 View Source File : RepositoryDbContext.cs
License : MIT License
Project Creator : 2881099

static FieldInfo GetRepositoryDbField(Type type) => _dicGetRepositoryDbField.GetOrAdd(type, tp => typeof(BaseRepository<,>).MakeGenericType(tp, typeof(int)).GetField("_dbPriv", BindingFlags.Instance | BindingFlags.NonPublic));

19 View Source File : RequestAuthorizationBehavior.cs
License : MIT License
Project Creator : AustinDavies

private Task<AuthorizationResult> ExecuteAuthorizationHandler(IAuthorizationRequirement requirement, CancellationToken cancellationToken)
        {
            var requirementType = requirement.GetType();
            var handlerType = FindHandlerType(requirement);

            if (handlerType == null)
                throw new InvalidOperationException($"Could not find an authorization handler type for requirement type \"{requirementType.Name}\"");

            var handlers = _serviceProvider.GetService(typeof(IEnumerable<>).MakeGenericType(handlerType)) as IEnumerable<object>;

            if (handlers == null || handlers.Count() == 0)
                throw new InvalidOperationException($"Could not find an authorization handler implementation for requirement type \"{requirementType.Name}\"");

            if (handlers.Count() > 1)
                throw new InvalidOperationException($"Multiple authorization handler implementations were found for requirement type \"{requirementType.Name}\"");

            var serviceHandler = handlers.First();
            var serviceHandlerType = serviceHandler.GetType();

            var methodInfo = _handlerMethodInfo.GetOrAdd(serviceHandlerType,
                    handlerMethodKey =>
                    {
                        return serviceHandlerType.GetMethods()
                            .Where(x => x.Name == nameof(IAuthorizationHandler<IAuthorizationRequirement>.Handle))
                            .FirstOrDefault();
                    });

            return (Task<AuthorizationResult>)methodInfo.Invoke(serviceHandler, new object[] { requirement, cancellationToken });
        }

19 View Source File : ChromeSession.cs
License : MIT License
Project Creator : BaristaLabs

public void Subscribe<TEvent>(Action<TEvent> eventCallback)
            where TEvent : IEvent
        {
            if (eventCallback == null)
                throw new ArgumentNullException(nameof(eventCallback));

            var eventName = m_eventTypeMap.GetOrAdd(
                typeof(TEvent),
                (type) =>
                {
                    if (!EventTypeMap.TryGetMethodNameForType<TEvent>(out string methodName))
                        throw new InvalidOperationException($"Type {typeof(TEvent)} does not correspond to a known event type.");

                    return methodName;
                });

            var callbackWrapper = new Action<object>(obj => eventCallback((TEvent)obj));
            m_eventHandlers.AddOrUpdate(eventName,
                (m) => new ConcurrentBag<Action<object>>(new[] { callbackWrapper }),
                (m, currentBag) =>
                {
                    currentBag.Add(callbackWrapper);
                    return currentBag;
                });
        }

See More Examples