public void RecordCall <T>(Expression <Action <T> > expr) { if (_stopped) { throw new InvalidOperationException("{0} was not expecting any more calls!".FormatWith((typeof(MethodCallCounter).Name))); } var methodCallExpression = (MethodCallExpression)expr.Body; var method = methodCallExpression.Method; // http://stackoverflow.com/questions/2616638/access-the-value-of-a-member-expression var args = new List <object>(); foreach (var argExpr in methodCallExpression.Arguments) { var messageExpression = argExpr; var objectMember = Expression.Convert(messageExpression, typeof(object)); var getterLambda = Expression.Lambda <Func <object> >(objectMember); var getter = getterLambda.Compile(); var arg = getter(); args.Add(arg); } var key = GetMethodKey(typeof(T), method); var methodCallBag = _allReceivedCalls.GetOrAdd(key, k => new ConcurrentBag <object[]>()); methodCallBag.Add(args.ToArray()); var callCount = Interlocked.Increment(ref _callCount); Log.Information("Observed call {CallCount} to {HandlerMethod}", callCount, key); }
public TValue GetOrAdd(TKey key, Func <TKey, TValue> valueFactory) { // key could be null if (key == null) { // ConcurrentDictionary hates null throw new ArgumentNullException(nameof(key)); } // valueFactory is checked for null inside the call return(_wrapped.GetOrAdd(key, valueFactory)); }
public object InvokeGeneric(object instance, string name, Type[] types, params object[] arguments) { Type instanceType = instance.GetType(); string key = instanceType.FullName + ":" + name + ":" + string.Join(":", types.Select(t => t.FullName)); Func <object, object[], object> result = CachedMethods.GetOrAdd(key, a => { return(CreateMethod(instanceType, name, types)); }); return(result(instance, arguments)); }
internal static void Merge(object storeEntity, object entity) { Type t = entity.GetType(); Action <object, object> cloner = Cache.GetOrAdd(t, CreateCloner); cloner(storeEntity, entity); }
public static IEnumerable <AtomPropertyInfo> GetEntityProperties(this Type type, bool keyOnly = false) { ThreadSafeDictionary <Type, IEnumerable <AtomPropertyInfo> > cache = keyOnly ? _keyList : _allList; return(cache.GetOrAdd(type, t => { List <AtomPropertyInfo> list = new List <AtomPropertyInfo>(); foreach (PropertyInfo p in type.GetCachedProperties()) { KeyAttribute a = p.GetCustomAttribute <KeyAttribute>(); if (a == null) { continue; } NotMappedAttribute notMapped = p.GetCustomAttribute <NotMappedAttribute>(); if (notMapped != null) { continue; } if (keyOnly) { list.Add(new AtomPropertyInfo(type, p, true)); } else { list.Add(new AtomPropertyInfo(type, p, false)); } } return list; })); }
public IServiceProvider CreateContainer(string tenantId) { return(_providers.GetOrAdd(tenantId, key => { var services = _provider.CreateChildContainer(_services); return services.BuildServiceProvider(); })); }
internal object GetProperty(object obj, PropertyDescriptor pd) { if (obj == null) { return(null); } Type objType = obj.GetType(); string key = objType.FullName + ":" + pd.Name; Func <object, object> f = CachedProperties.GetOrAdd(key, k => { ParameterExpression pe = Expression.Parameter(typeof(object), "x"); Expression me = Expression.Property(Expression.TypeAs(pe, objType), objType.GetProperty(pd.Name)); me = Expression.Convert(me, typeof(object)); return(Expression.Lambda <Func <object, object> >(me, pe).Compile()); }); return(f(obj)); }
public static ConstructorInfo GetCachedConstructor(this Type type) { return(_constructors.GetOrAdd(type, t => { return t.GetConstructors().Where(x => x.GetParameters() != null && ( x.GetParameters().Length == 0 || x.GetParameters().All(p => p.HasDefaultValue) )).FirstOrDefault(); })); }
private object Resolve(Type type) { try { return(_components.GetOrAdd(type, ConstructObject)); } catch (Exception exc) { throw new DependencyResolutionException("Could not resolve type: {0}".FormatWith(type.FullName), exc); } }
public async Task Invoke(HttpContext context) { var tenant = context.Tenant(); if (tenant == null) { throw new InvalidOperationException( "TenantResolutionMiddleware must be register before TenantPipelineMiddleware"); } var tenantPipeline = _pipelines.GetOrAdd(tenant, BuildTenantPipeline); await tenantPipeline(context); }
public void GetOrAdd() { var dict = new ThreadSafeDictionary <int, int>(Enumerable.Range(0, 100).Select(x => new KeyValuePair <int, int>(x, 2 * x))); int val; Assert.IsTrue(dict.GetOrAdd(200, 400, out val)); Assert.AreEqual(400, val); Assert.AreEqual(400, dict[200]); Assert.IsFalse(dict.GetOrAdd(200, 300, out val)); Assert.AreEqual(400, val); Assert.AreEqual(400, dict[200]); Assert.AreEqual(400, dict.GetOrAdd(200, 10)); Assert.AreEqual(400, dict[200]); Assert.AreEqual(600, dict.GetOrAdd(300, 600)); Assert.AreEqual(600, dict[300]); bool called = false; Assert.IsFalse(dict.GetOrAdd(200, x => { called = true; return(50); }, out val)); Assert.AreEqual(400, val); Assert.AreEqual(400, dict[200]); Assert.IsFalse(called); Assert.IsTrue(dict.GetOrAdd(400, x => { called = true; return(800); }, out val)); Assert.AreEqual(800, val); Assert.AreEqual(800, dict[400]); Assert.IsTrue(called); called = false; Assert.AreEqual(400, dict.GetOrAdd(200, x => { called = true; return(50); })); Assert.AreEqual(400, dict[200]); Assert.IsFalse(called); Assert.AreEqual(-2, dict.GetOrAdd(-1, x => { called = true; return(-2); })); Assert.AreEqual(-2, dict[-1]); Assert.IsTrue(called); }
private static string GetTypeKey(IEnumerable <LinqField> fields, Type baseType = null) { //TODO: optimize the type caching -- if fields are simply reordered, that doesn't mean that they're actually different types, so this needs to be smarter string key = baseType == null ? string.Empty : baseType.FullName + "_"; foreach (var field in fields.OrderBy(x => x.Name)) { key += field.Name + "_" + field.Type.FullName + "_"; } return(typeNames.GetOrAdd(key, k => { int c = Interlocked.Increment(ref TypeCount); var a = "SelectType" + c; return a; })); }
public override async Task <AuthorizationPolicy> GetPolicyAsync(string policyName) { if (!policyName.StartsWith(PermissionConstant.PolicyPrefix, StringComparison.OrdinalIgnoreCase)) { return(await base.GetPolicyAsync(policyName)); } var policy = _policies.GetOrAdd(policyName, name => { var permissions = policyName.Substring(PermissionConstant.PolicyPrefix.Length) .UnpackFromString(PermissionConstant.PolicyNameSplitSymbol); return(new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .AddRequirements(new PermissionAuthorizationRequirement(permissions)) .Build()); }); return(policy); }
/// <summary> /// Returns the list of all of the controllers and action methods of an MVC application which have AuthorizeAttribute and the specified policyName. /// </summary> public ICollection <ControllerMetadata> FindSecuredControllersWithPolicy(string policyName) { var result = _actionsWithPolicy.GetOrAdd(policyName, y => { var controllers = new List <ControllerMetadata>(Controllers); foreach (var controller in controllers) { controller.Actions = controller.Actions.Where( model => model.Secured && ( model.Attributes.OfType <AuthorizeAttribute>().FirstOrDefault() ?.Policy == policyName || controller.Attributes.OfType <AuthorizeAttribute>() .FirstOrDefault()?.Policy == policyName )).ToList(); } return(controllers.Where(model => model.Actions.Any()).ToList()); }); return(result); }
public INimbusMessageReceiver GetTopicReceiver(string topicPath, string subscriptionName, IFilterCondition filter) { var key = "{0}/{1}".FormatWith(topicPath, subscriptionName); return(_topicMessageReceivers.GetOrAdd(key, k => CreateTopicReceiver(topicPath, subscriptionName, filter))); }
public INimbusMessageSender GetTopicSender(string topicPath) { return(_topicMessageSenders.GetOrAdd(topicPath, CreateTopicSender)); }
public INimbusMessageReceiver GetQueueReceiver(string queuePath) { return(_queueMessageReceivers.GetOrAdd(queuePath, CreateQueueReceiver)); }
private object LockFor(string path) { return(_locks.GetOrAdd(path, p => new object())); }
/// <summary> /// Stores a given object and associates it with the specified name. /// </summary> /// <param name="name">The name with which to associate the new item in the call context.</param> /// <param name="data">The object to store in the call context.</param> public static void LogicalSetData(string name, [AllowNull] object data) => state.GetOrAdd(name, _ => new AsyncLocal <object>()).Value = data;
/// <summary> /// Gets a <see cref="ConstructionInfo"/> instance for the given <paramref name="registration"/>. /// </summary> /// <param name="registration">The <see cref="Registration"/> for which to get a <see cref="ConstructionInfo"/> instance.</param> /// <returns>The <see cref="ConstructionInfo"/> instance that describes how to create an instance of the given <paramref name="registration"/>.</returns> public ConstructionInfo GetConstructionInfo(Registration registration) { return(cache.GetOrAdd(registration, constructionInfoBuilder.Execute)); }
public AsyncBlockingCollection <NimbusMessage> GetOrCreateMessageQueue(string path) { return(_messageQueues.GetOrAdd(path, p => new AsyncBlockingCollection <NimbusMessage>())); }
internal static Type GetDynamicType(Type pt, IEnumerable <LinqField> fields = null) { string className = pt.Name + "Wrapper"; return(builtTypes.GetOrAdd(className, x => { TypeBuilder typeBuilder = moduleBuilder.DefineType(className, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable); typeBuilder.SetParent(pt); typeBuilder.AddInterfaceImplementation(typeof(IEntityWrapper)); var cm = pt.GetConstructors().FirstOrDefault(); var constructor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, fields.Select(p => p.Type).ToArray()); var il = constructor.GetILGenerator(); // call base class constructor... il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, cm); int i = 1; // add constructor foreach (var field in fields) { PropertyInfo prop = pt.GetProperty(field.Name); var sm = prop.GetSetMethod(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, i++); il.Emit(OpCodes.Call, sm); } il.Emit(OpCodes.Ret); constructor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); constructor.GetILGenerator().Emit(OpCodes.Ret); if (fields != null) { foreach (var field in fields) { PropertyInfo pbase = pt.GetProperty(field.Name); var gm = typeBuilder.DefineMethod("get_" + field.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual, field.Type, Type.EmptyTypes); il = gm.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, pbase.GetGetMethod()); il.Emit(OpCodes.Ret); var p = typeBuilder.DefineProperty(field.Name, PropertyAttributes.HasDefault, field.Type, Type.EmptyTypes); p.SetGetMethod(gm); if (field.Protected) { var c = typeof(XmlIgnoreAttribute).GetConstructors().FirstOrDefault(); p.SetCustomAttribute(new CustomAttributeBuilder(c, new object[] { })); c = typeof(ScriptIgnoreAttribute).GetConstructors().FirstOrDefault(); p.SetCustomAttribute(new CustomAttributeBuilder(c, new object[] { })); } } } return typeBuilder.CreateType(); })); }
/// <inheritdoc/> public object GetInstance(Func <object> createInstance, Scope scope) { return(instances.GetOrAdd(rootScope, s => CreateScopedInstance(createInstance))); }
public Queue GetQueue(string queuePath) { return(_queues.GetOrAdd(queuePath, p => new Queue(queuePath))); }
/// <summary> /// Gets a <see cref="ChannelFactory{TChannel}"/> that is used to /// create a <typeparamref name="TService"/> channel. /// </summary> /// <typeparam name="TService">The service type for which to get a <see cref="ChannelFactory{TChannel}"/>.</typeparam> /// <returns>a <see cref="ChannelFactory{TChannel}"/> that is used to create a <typeparamref name="TService"/> channel.</returns> public ChannelFactory <TService> GetChannelFactory <TService>() { return((ChannelFactory <TService>)cache.GetOrAdd(typeof(TService), type => CreateChannelFactory <TService>())); }
public Topic GetTopic(string topicPath) { return(_topics.GetOrAdd(topicPath, p => new Topic(topicPath))); }