Here are the examples of the csharp api System.Type.GetTypeInfo() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4949 Examples
19
Source : TypeExtend.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static Func<TRes> CreateFunc<TRes>(TypeInfo callInfo, string methodName, TypeInfo resInfo)
{
var typeConstructor = resInfo.GetConstructor(Type.EmptyTypes);
if (typeConstructor == null)
throw new ArgumentException($"类型{callInfo.FullName}没有无参构造函数");
var innerMethod = callInfo.GetMethod(methodName);
if (innerMethod == null)
throw new ArgumentException($"类型{callInfo.FullName}没有名称为{methodName}的方法");
if (innerMethod.ReturnType != resInfo)
throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}返回值不为{resInfo.FullName}");
var args = innerMethod.GetParameters();
if (args.Length > 0)
throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}参数不为空");
//构造匿名方法
var callMethod = new DynamicMethod(methodName, typeof(TRes), null);
//构造动态IL(方法内部实现)
var il = callMethod.GetILGenerator();
il.Emit(OpCodes.Nop);
//1 调用对象构造
il.Emit(OpCodes.Newobj, typeConstructor);
var call = il.DeclareLocal(callInfo);
il.Emit(OpCodes.Stloc, call);
//3 方法调用
il.Emit(OpCodes.Ldloc, call);
il.Emit(OpCodes.Callvirt, innerMethod);
var ret = il.DeclareLocal(innerMethod.ReturnType);
//4 返回值转换
il.Emit(OpCodes.Stloc, ret);
il.Emit(OpCodes.Ldloc, ret);
il.Emit(OpCodes.Castclreplaced, typeof(TRes).GetTypeInfo());
var res = il.DeclareLocal(resInfo);
//5 返回
il.Emit(OpCodes.Stloc, res);
il.Emit(OpCodes.Ldloc, res);
il.Emit(OpCodes.Ret);
//返回动态委托
return callMethod.CreateDelegate(typeof(Func<TRes>)) as Func<TRes>;
}
19
Source : TypeExtend.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static Func<TArg, TRes> CreateFunc<TArg, TRes>(TypeInfo callInfo, string methodName, TypeInfo argInfo, TypeInfo resInfo)
{
var typeConstructor = resInfo.GetConstructor(Type.EmptyTypes);
if (typeConstructor == null)
throw new ArgumentException($"类型{callInfo.FullName}没有无参构造函数");
var innerMethod = callInfo.GetMethod(methodName);
if (innerMethod == null)
throw new ArgumentException($"类型{callInfo.FullName}没有名称为{methodName}的方法");
if (innerMethod.ReturnType != resInfo)
throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}返回值不为{resInfo.FullName}");
var args = innerMethod.GetParameters();
if (args.Length != 1)
throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}参数不是一个");
if (args[0].ParameterType != argInfo)
throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}唯一参数不为{argInfo.FullName}");
//构造匿名方法
var callMethod = new DynamicMethod(methodName, typeof(TRes), new[] { typeof(TArg) });
//构造动态IL(方法内部实现)
var il = callMethod.GetILGenerator();
il.Emit(OpCodes.Nop);
//1 参数类型转换
il.Emit(OpCodes.Ldarg, 0);
il.Emit(OpCodes.Castclreplaced, argInfo);
var arg = il.DeclareLocal(argInfo);
il.Emit(OpCodes.Stloc, arg);
//2 调用对象构造
il.Emit(OpCodes.Newobj, typeConstructor);
var call = il.DeclareLocal(callInfo);
il.Emit(OpCodes.Stloc, call);
//3 方法调用
il.Emit(OpCodes.Ldloc, call);
il.Emit(OpCodes.Ldloc, arg);
il.Emit(OpCodes.Callvirt, innerMethod);
var ret = il.DeclareLocal(innerMethod.ReturnType);
//4 返回值转换
il.Emit(OpCodes.Stloc, ret);
il.Emit(OpCodes.Ldloc, ret);
il.Emit(OpCodes.Castclreplaced, typeof(TRes).GetTypeInfo());
var res = il.DeclareLocal(resInfo);
//5 返回
il.Emit(OpCodes.Stloc, res);
il.Emit(OpCodes.Ldloc, res);
il.Emit(OpCodes.Ret);
//返回动态委托
return callMethod.CreateDelegate(typeof(Func<TArg, TRes>)) as Func<TArg, TRes>;
}
19
Source : ZeroDiscover.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private void FindApi(Type type, bool onlyDoc)
{
if (type.IsAbstract)
return;
StationDoreplacedent station;
var sa = type.GetCustomAttribute<StationAttribute>();
if (sa != null)
{
if (!StationInfo.TryGetValue(sa.Name, out station))
{
StationInfo.Add(sa.Name, station = new StationDoreplacedent
{
Name = sa.Name
});
}
}
else
{
station = _defStation;
}
//station.Copy(XmlMember.Find(type));
string routeHead = null;
var attrib = type.GetCustomAttribute<RouteAttribute>();
if (attrib != null)
{
routeHead = attrib.Name;
}
else
{
var attrib2 = type.GetCustomAttribute<RoutePrefixAttribute>();
if (attrib2 != null)
{
routeHead = attrib2.Name;
}
}
if (string.IsNullOrWhiteSpace(routeHead))
routeHead = null;
else
routeHead = routeHead.Trim(' ', '\t', '\r', '\n', '/') + "/";
var methods = type.GetMethods(BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic);
var xdoc = XmlMember.Find(type);
foreach (var method in methods)
{
var route = method.GetCustomAttribute<RouteAttribute>();
if (route == null)
{
//ZeroTrace.WriteError("ApiDiscover", "exclude", station.Name, type.Name, method.Name);
continue;
}
if (method.Name.Length > 4 && (method.Name.IndexOf("get_") == 0 || method.Name.IndexOf("set_") == 0))
continue;
if (method.GetParameters().Length > 1)
{
//ZeroTrace.WriteError("ApiDiscover", "argument size must 0 or 1", station.Name, type.Name, method.Name);
continue;
}
var name = route?.Name == null
? $"{routeHead}{method.Name}"
: $"{routeHead}{route.Name.Trim(' ', '\t', '\r', '\n', '/')}";
var accessOption = method.GetCustomAttribute<ApiAccessOptionFilterAttribute>();
var ca = method.GetAttribute<CategoryAttribute>();
var api = new ApiActionInfo
{
Name = method.Name,
ApiName= route?.Name ?? method.Name,
RouteName = name,
Category = ca?.Category ?? xdoc?.Caption,
AccessOption = accessOption?.Option ?? ApiAccessOption.Public | ApiAccessOption.ArgumentCanNil,
ResultInfo = ReadEnreplacedy(method.ReturnType, "result")
};
var doc = XmlMember.Find(type, method.Name, "M");
api.Copy(doc);
var arg = method.GetParameters().FirstOrDefault();
api.HaseArgument = arg != null;
//动态生成并编译
if (api.HaseArgument)
{
api.ArgumentInfo = ReadEnreplacedy(arg.ParameterType, "argument") ?? new TypeDoreplacedent();
api.ArgumentInfo.Name = arg.Name;
if (doc != null)
api.ArgumentInfo.Caption = doc.Arguments.Values.FirstOrDefault();
if (!onlyDoc)
{
api.ArgumenType = arg.ParameterType;
api.ArgumentAction = CreateFunc<IApiArgument, IApiResult>(type.GetTypeInfo(),
method.Name,
arg.ParameterType.GetTypeInfo(),
method.ReturnType.GetTypeInfo());
}
}
else if (!onlyDoc)
{
api.Action = CreateFunc<IApiResult>(type.GetTypeInfo(), method.Name, method.ReturnType.GetTypeInfo());
}
station.Aips.Add(api.RouteName, api);
}
}
19
Source : ZeroDiscover.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static Func<TArg, TRes> CreateFunc<TArg, TRes>(TypeInfo callInfo, string methodName, TypeInfo argInfo, TypeInfo resInfo)
{
ConstructorInfo constructor = callInfo.GetConstructor(Type.EmptyTypes);
if (constructor == (ConstructorInfo)null)
throw new ArgumentException("类型" + callInfo.FullName + "没有无参构造函数");
MethodInfo method = callInfo.GetMethod(methodName);
if (method == (MethodInfo)null)
throw new ArgumentException("类型" + callInfo.FullName + "没有名称为" + methodName + "的方法");
if (method.ReturnType != (Type)resInfo)
throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "返回值不为" + resInfo.FullName);
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 1)
throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "参数不是一个");
if (parameters[0].ParameterType != (Type)argInfo)
throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "唯一参数不为" + argInfo.FullName);
DynamicMethod dynamicMethod = new DynamicMethod(methodName, typeof(TRes), new Type[1]
{
typeof (TArg)
});
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Nop);
ilGenerator.Emit(OpCodes.Ldarg, 0);
ilGenerator.Emit(OpCodes.Castclreplaced, (Type)argInfo);
LocalBuilder local1 = ilGenerator.DeclareLocal((Type)argInfo);
ilGenerator.Emit(OpCodes.Stloc, local1);
ilGenerator.Emit(OpCodes.Newobj, constructor);
LocalBuilder local2 = ilGenerator.DeclareLocal((Type)callInfo);
ilGenerator.Emit(OpCodes.Stloc, local2);
ilGenerator.Emit(OpCodes.Ldloc, local2);
ilGenerator.Emit(OpCodes.Ldloc, local1);
ilGenerator.Emit(OpCodes.Callvirt, method);
LocalBuilder local3 = ilGenerator.DeclareLocal(method.ReturnType);
ilGenerator.Emit(OpCodes.Stloc, local3);
ilGenerator.Emit(OpCodes.Ldloc, local3);
ilGenerator.Emit(OpCodes.Castclreplaced, (Type)typeof(TRes).GetTypeInfo());
LocalBuilder local4 = ilGenerator.DeclareLocal((Type)resInfo);
ilGenerator.Emit(OpCodes.Stloc, local4);
ilGenerator.Emit(OpCodes.Ldloc, local4);
ilGenerator.Emit(OpCodes.Ret);
return dynamicMethod.CreateDelegate(typeof(Func<TArg, TRes>)) as Func<TArg, TRes>;
}
19
Source : ZeroDiscover.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static Func<TRes> CreateFunc<TRes>(TypeInfo callInfo, string methodName, TypeInfo resInfo)
{
ConstructorInfo constructor = callInfo.GetConstructor(Type.EmptyTypes);
if (constructor == (ConstructorInfo)null)
throw new ArgumentException("类型" + callInfo.FullName + "没有无参构造函数");
MethodInfo method = callInfo.GetMethod(methodName);
if (method == (MethodInfo)null)
throw new ArgumentException("类型" + callInfo.FullName + "没有名称为" + methodName + "的方法");
if (method.ReturnType != (Type)resInfo)
throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "返回值不为" + resInfo.FullName);
if ((uint)method.GetParameters().Length > 0U)
throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "参数不为空");
DynamicMethod dynamicMethod = new DynamicMethod(methodName, typeof(TRes), (Type[])null);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Nop);
ilGenerator.Emit(OpCodes.Newobj, constructor);
LocalBuilder local1 = ilGenerator.DeclareLocal((Type)callInfo);
ilGenerator.Emit(OpCodes.Stloc, local1);
ilGenerator.Emit(OpCodes.Ldloc, local1);
ilGenerator.Emit(OpCodes.Callvirt, method);
LocalBuilder local2 = ilGenerator.DeclareLocal(method.ReturnType);
ilGenerator.Emit(OpCodes.Stloc, local2);
ilGenerator.Emit(OpCodes.Ldloc, local2);
ilGenerator.Emit(OpCodes.Castclreplaced, (Type)typeof(TRes).GetTypeInfo());
LocalBuilder local3 = ilGenerator.DeclareLocal((Type)resInfo);
ilGenerator.Emit(OpCodes.Stloc, local3);
ilGenerator.Emit(OpCodes.Ldloc, local3);
ilGenerator.Emit(OpCodes.Ret);
return dynamicMethod.CreateDelegate(typeof(Func<TRes>)) as Func<TRes>;
}
19
Source : IdentityBuilderExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static TypeInfo FindGenericBaseType(Type currentType, Type genericBaseType)
{
var type = currentType;
while (type != null)
{
var typeInfo = type.GetTypeInfo();
var genericType = type.IsGenericType ? type: null;
if (genericType != null && genericType == genericBaseType)
{
return typeInfo;
}
type = type.BaseType;
}
return null;
}
19
Source : IdentityBuilderExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static TypeInfo FindGenericBaseType(Type currentType, Type genericBaseType)
{
var type = currentType;
while (type != null)
{
var typeInfo = type.GetTypeInfo();
var genericType = type.IsGenericType ? type.GetGenericTypeDefinition() : null;
if (genericType != null && genericType == genericBaseType)
{
return typeInfo;
}
type = type.BaseType;
}
return null;
}
19
Source : Startup.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public void ConfigureServices(IServiceCollection services)
{
var migrationsreplacedembly = typeof(Startup).GetTypeInfo().replacedembly.GetName().Name;
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString))
.AddTheIdServerAdminEnreplacedyFrameworkStores(options =>
options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)))
.AddConfigurationEnreplacedyFrameworkStores(options =>
options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)))
.AddOperationalEnreplacedyFrameworkStores(options =>
options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)));
var signalRBuilder = services.AddSignalR(options => Configuration.GetSection("SignalR:HubOptions").Bind(options));
if (Configuration.GetValue<bool>("SignalR:UseMessagePack"))
{
signalRBuilder.AddMessagePackProtocol();
}
services.Configure<SendGridOptions>(Configuration)
.AddControllersWithViews(options =>
{
options.AddIdenreplacedyServerAdminFilters();
})
.AddNewtonsoftJson(options =>
{
var settings = options.SerializerSettings;
settings.NullValueHandling = NullValueHandling.Ignore;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
})
.AddIdenreplacedyServerAdmin<ApplicationUser, SchemeDefinition>();
services.AddAuthorization(options =>
{
options.AddPolicy(SharedConstants.WRITERPOLICY, policy =>
{
policy.Requirereplacedertion(context =>
context.User.IsInRole(SharedConstants.WRITERPOLICY));
});
options.AddPolicy(SharedConstants.READERPOLICY, policy =>
{
policy.Requirereplacedertion(context =>
context.User.IsInRole(SharedConstants.READERPOLICY));
});
})
.AddAuthentication("Bearer")
.AddIdenreplacedyServerAuthentication("Bearer", options =>
{
options.Authority = "https://localhost:7443";
options.RequireHttpsMetadata = false;
options.SupportedTokens = IdenreplacedyServer4.AccessTokenValidation.SupportedTokens.Both;
options.ApiName = "theidserveradminapi";
options.ApiSecret = "5b556f7c-b3bc-4b5b-85ab-45eed0cb962d";
options.EnableCaching = true;
options.CacheDuration = TimeSpan.FromMinutes(10);
options.LegacyAudienceValidation = true;
})
.AddDynamic<SchemeDefinition>()
.AddGoogle()
.AddFacebook()
.AddOpenIdConnect()
.AddTwitter()
.AddMicrosoftAccount()
.AddOAuth("OAuth", options =>
{
});
services.AddDatabaseDeveloperPageExceptionFilter()
.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
19
Source : Startup.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public void ConfigureServices(IServiceCollection services)
{
var migrationsreplacedembly = typeof(Startup).GetTypeInfo().replacedembly.GetName().Name;
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString))
.AddTheIdServerAdminEnreplacedyFrameworkStores(options =>
options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)))
.AddConfigurationEnreplacedyFrameworkStores(options =>
options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)))
.AddOperationalEnreplacedyFrameworkStores(options =>
options.UseSqlServer(connectionString, sql => sql.Migrationsreplacedembly(migrationsreplacedembly)))
.AddIdenreplacedyProviderStore();
services.AddIdenreplacedy<ApplicationUser, IdenreplacedyRole>(
options => options.SignIn.RequireConfirmedAccount = Configuration.GetValue<bool>("SignInOptions:RequireConfirmedAccount"))
.AddEnreplacedyFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
var idenreplacedyBuilder = services.AddClaimsProviders(Configuration)
.Configure<ForwardedHeadersOptions>(Configuration.GetSection(nameof(ForwardedHeadersOptions)))
.Configure<AccountOptions>(Configuration.GetSection(nameof(AccountOptions)))
.Configure<DynamicClientRegistrationOptions>(Configuration.GetSection(nameof(DynamicClientRegistrationOptions)))
.Configure<TokenValidationParameters>(Configuration.GetSection(nameof(TokenValidationParameters)))
.ConfigureNonBreakingSameSiteCookies()
.AddOidcStateDataFormatterCache()
.AddIdenreplacedyServer(Configuration.GetSection(nameof(IdenreplacedyServerOptions)))
.AddAspNetIdenreplacedy<ApplicationUser>()
.AddSigningCredentials()
.AddDynamicClientRegistration();
idenreplacedyBuilder.AddJwtRequestUriHttpClient();
idenreplacedyBuilder.AddProfileService<ProfileService<ApplicationUser>>();
if (!Configuration.GetValue<bool>("DisableTokenCleanup"))
{
idenreplacedyBuilder.AddTokenCleaner(Configuration.GetValue<TimeSpan?>("TokenCleanupInterval") ?? TimeSpan.FromMinutes(1));
}
services.AddAuthorization(options =>
options.AddIdenreplacedyServerPolicies())
.AddAuthentication()
.AddIdenreplacedyServerAuthentication(JwtBearerDefaults.AuthenticationScheme, ConfigureIdenreplacedyServerAuthenticationOptions());
services.Configure<SendGridOptions>(Configuration)
.AddLocalization()
.AddControllersWithViews(options =>
options.AddIdenreplacedyServerAdminFilters())
.AddViewLocalization()
.AddDataAnnotationsLocalization()
.AddNewtonsoftJson(options =>
{
var settings = options.SerializerSettings;
settings.NullValueHandling = NullValueHandling.Ignore;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
})
.AddIdenreplacedyServerAdmin<ApplicationUser, SchemeDefinition>();
services.AddDatabaseDeveloperPageExceptionFilter()
.AddRazorPages(options => options.Conventions.AuthorizeAreaFolder("Idenreplacedy", "/Account"));
}
19
Source : UniqueValidator.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public override bool IsValid(ValidationContext<T> context, string value)
{
var editedItem = context.InstanceToValidate;
var propertyName = context.PropertyName;
propertyName = propertyName.Substring(propertyName.LastIndexOf('.') + 1);
var property = typeof(T).GetTypeInfo().GetProperty(propertyName);
return _items.All(item =>
item.Equals(editedItem) || property.GetValue(item) as string != value);
}
19
Source : ServiceCollectionExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static object CreateStore(Func<IServiceProvider, Task<HttpClient>> getHttpClient, IServiceProvider provider, Type enreplacedyType)
{
var adminStoreType = typeof(AdminStore<>)
.MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();
var loggerType = typeof(ILogger<>).MakeGenericType(adminStoreType);
return adminStoreType.GetConstructors()[0]
.Invoke(new object[] { getHttpClient.Invoke(provider), provider.GetRequiredService(loggerType) });
}
19
Source : ServiceCollectionExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static void AddTheIdServerMongoDbStores(IServiceCollection services, Type enreplacedyType, Func<IServiceProvider, IMongoDatabase> getDatabase)
{
services.AddScoped(typeof(IMongoCollection<>).MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo(), provider =>
{
return GetCollection(getDatabase, provider, enreplacedyType);
});
var adminStoreType = typeof(AdminStore<>)
.MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(adminStoreType);
var cacheAdminStoreType = typeof(CacheAdminStore<,>)
.MakeGenericType(adminStoreType.GetTypeInfo(), enreplacedyType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(cacheAdminStoreType);
var iAdminStoreType = typeof(IAdminStore<>)
.MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(iAdminStoreType, cacheAdminStoreType);
}
19
Source : Utils.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public static IEnumerable<Type> GetEnreplacedyTypeList()
{
var replacedembly = typeof(IEnreplacedyId).GetTypeInfo().replacedembly;
var entyTypeList = replacedembly.GetTypes().Where(t => t.IsClreplaced &&
!t.IsAbstract &&
t.Name != nameof(Key) &&
t.GetInterface("IEnreplacedyId") != null);
return entyTypeList;
}
19
Source : ServiceCollectionExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static void AddHttpAdminStore(IServiceCollection services,
Type enreplacedyType,
Func<IServiceProvider, Task<HttpClient>> getHttpClient)
{
var iAdminStoreType = typeof(IAdminStore<>)
.MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(iAdminStoreType, provider =>
{
return CreateStore(getHttpClient, provider, enreplacedyType);
});
}
19
Source : ServiceCollectionExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static IEnumerable<Type> GetEnreplacedyTypes()
{
var replacedembly = typeof(IEnreplacedyId).GetTypeInfo().replacedembly;
var enreplacedyTypeList = replacedembly.GetTypes().Where(t => t.IsClreplaced &&
!t.IsAbstract &&
t.GetInterface("IEnreplacedyId") != null);
return enreplacedyTypeList;
}
19
Source : GenericControllerFeatureProvider.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
{
var entyTypeList = Utils.GetEnreplacedyTypeList()
.Where(e => e != typeof(User) || e!= typeof(Role));
// This is designed to run after the default ControllerTypeProvider,
// so the list of 'real' controllers has already been populated.
foreach (var enreplacedyType in entyTypeList)
{
var typeName = enreplacedyType.Name + "Controller";
if (!feature.Controllers.Any(t => t.Name == typeName))
{
// There's no controller for this enreplacedy, so add the generic version.
var controllerType = typeof(GenericApiController<>)
.MakeGenericType(enreplacedyType.GetTypeInfo())
.GetTypeInfo();
feature.Controllers.Add(controllerType);
}
}
var keyTypeList = new[]
{
typeof(IAuthenticatedEncryptorDescriptor),
typeof(RsaEncryptorDescriptor)
};
// This is designed to run after the default ControllerTypeProvider,
// so the list of 'real' controllers has already been populated.
foreach (var keyType in keyTypeList)
{
var typeName = keyType.Name + "Controller";
if (!feature.Controllers.Any(t => t.Name == typeName))
{
// There's no controller for this key, so add the generic version.
var controllerType = typeof(GenericKeyController<>)
.MakeGenericType(keyType.GetTypeInfo())
.GetTypeInfo();
feature.Controllers.Add(controllerType);
}
}
}
19
Source : ServiceCollectionExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static void AddStoresForContext(IServiceCollection services, Type dbContextType)
{
foreach (var property in dbContextType.GetProperties().Where(p => p.PropertyType.ImplementsGenericInterface(typeof(IQueryable<>)) &&
p.PropertyType.GetGenericArguments()[0].IsreplacedignableTo(typeof(IEnreplacedyId))))
{
var enreplacedyType = property.PropertyType.GetGenericArguments()[0];
var adminStoreType = typeof(AdminStore<,>)
.MakeGenericType(enreplacedyType.GetTypeInfo(), dbContextType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(adminStoreType);
var cacheAdminStoreType = typeof(CacheAdminStore<,>)
.MakeGenericType(adminStoreType.GetTypeInfo(), enreplacedyType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(cacheAdminStoreType);
var iAdminStoreType = typeof(IAdminStore<>)
.MakeGenericType(enreplacedyType.GetTypeInfo()).GetTypeInfo();
services.AddTransient(iAdminStoreType, cacheAdminStoreType);
}
}
19
Source : ExceptionFilterTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void OnException_should_not_set_context_result_for_unkown_controller()
{
var errorContext = CreateExceptionContext(new DbUpdateException());
((ControllerActionDescriptor)errorContext.ActionDescriptor).ControllerTypeInfo = typeof(object).GetTypeInfo();
var loggerMock = new Mock<ILogger<ExceptionFilter>>();
var sut = new ExceptionFilter(loggerMock.Object);
sut.OnException(errorContext);
replacedert.Null(errorContext.Result);
errorContext.ActionDescriptor = new ActionDescriptor();
sut.OnException(errorContext);
replacedert.Null(errorContext.Result);
}
19
Source : ExceptionFilterTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static ExceptionContext CreateExceptionContext(Exception e)
{
var httpContextMock = new Mock<HttpContext>();
var errorContext = new ExceptionContext(new ActionContext
{
HttpContext = httpContextMock.Object,
RouteData = new Microsoft.AspNetCore.Routing.RouteData(),
ActionDescriptor = new ActionDescriptor()
}, new List<IFilterMetadata>())
{
ActionDescriptor = new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(ExternalProviderKindController).GetTypeInfo()
},
Exception = e,
};
return errorContext;
}
19
Source : ServiceCollectionExtensionsTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void AddIdenreplacedyServer4AdminMongoDbkStores_with_connectionString_should_add_ravendb_stores_for_each_enreplacedy()
{
var services = new ServiceCollection().AddLogging();
services.AddTheIdServerMongoDbStores("mongodb://localhost/test")
.AddLogging()
.Configure<MemoryCacheOptions>(options => { })
.Configure<ISConfiguration.IdenreplacedyServerOptions>(options => { })
.AddTransient(p => p.GetRequiredService<IOptions<ISConfiguration.IdenreplacedyServerOptions>>().Value)
.AddScoped(typeof(IFlushableCache<>), typeof(FlushableCache<>))
.AddSingleton<HubConnectionFactory>()
.AddTransient(p => new Mock<IConfiguration>().Object)
.AddTransient<IProviderClient, ProviderClient>();
services.AddIdenreplacedy<ApplicationUser, IdenreplacedyRole>()
.AddTheIdServerStores();
services.AddAuthentication()
.AddDynamic<SchemeDefinition>()
.AddTheIdServerEnreplacedyMongoDbStore()
.AddGoogle();
var replacedembly = typeof(Enreplacedy.IEnreplacedyId).GetTypeInfo().replacedembly;
var enreplacedyTypeList = replacedembly.GetTypes().Where(t =>
t.IsClreplaced &&
!t.IsAbstract &&
!t.IsGenericType &&
t.GetInterface(nameof(Enreplacedy.IEnreplacedyId)) != null);
var provider = services.BuildServiceProvider();
foreach (var enreplacedyType in enreplacedyTypeList)
{
var storeType = typeof(IAdminStore<>).MakeGenericType(enreplacedyType);
replacedert.NotNull(provider.GetService(storeType));
}
}
19
Source : ServiceCollectionExtensionsTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void AddIdenreplacedyServer4AdminRavenDbkStores_should_add_ravendb_stores_for_each_enreplacedy()
{
var services = new ServiceCollection().AddLogging();
var wrapper = new RavenDbTestDriverWrapper();
services.AddTheIdServerRavenDbStores()
.AddLogging()
.Configure<MemoryCacheOptions>(options => { })
.Configure<ISConfiguration.IdenreplacedyServerOptions>(options => { })
.AddTransient(p => p.GetRequiredService<IOptions<ISConfiguration.IdenreplacedyServerOptions>>().Value)
.AddScoped(typeof(IFlushableCache<>), typeof(FlushableCache<>))
.AddSingleton<HubConnectionFactory>()
.AddTransient(p => new Mock<IConfiguration>().Object)
.AddTransient<IProviderClient, ProviderClient>()
.AddTransient(p => wrapper.GetDoreplacedentStore());
services.AddIdenreplacedy<ApplicationUser, IdenreplacedyRole>()
.AddTheIdServerStores();
services.AddAuthentication()
.AddDynamic<SchemeDefinition>()
.AddTheIdServerStoreRavenDbStore()
.AddGoogle();
var replacedembly = typeof(Enreplacedy.IEnreplacedyId).GetTypeInfo().replacedembly;
var enreplacedyTypeList = replacedembly.GetTypes().Where(t =>
t.IsClreplaced &&
!t.IsAbstract &&
!t.IsGenericType &&
t.GetInterface(nameof(Enreplacedy.IEnreplacedyId)) != null);
var provider = services.BuildServiceProvider();
foreach(var enreplacedyType in enreplacedyTypeList)
{
var storeType = typeof(IAdminStore<>).MakeGenericType(enreplacedyType);
replacedert.NotNull(provider.GetService(storeType));
}
}
19
Source : ServiceCollectionExtensionsTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void AddIdenreplacedyServer4AdminRavenDbkStores_should_add_ravendb_stores_for_each_enreplacedy_using_getDoreplacedentStore_function()
{
var services = new ServiceCollection().AddLogging();
var wrapper = new RavenDbTestDriverWrapper();
services.AddTheIdServerRavenDbStores(p => new RavenDbTestDriverWrapper().GetDoreplacedentStore())
.AddLogging()
.Configure<MemoryCacheOptions>(options => { })
.Configure<ISConfiguration.IdenreplacedyServerOptions>(options => { })
.AddTransient(p => p.GetRequiredService<IOptions<ISConfiguration.IdenreplacedyServerOptions>>().Value)
.AddScoped(typeof(IFlushableCache<>), typeof(FlushableCache<>))
.AddSingleton<HubConnectionFactory>()
.AddTransient(p => new Mock<IConfiguration>().Object)
.AddTransient<IProviderClient, ProviderClient>()
.AddTransient(p => wrapper.GetDoreplacedentStore());
services.AddIdenreplacedy<ApplicationUser, IdenreplacedyRole>()
.AddTheIdServerStores();
services.AddAuthentication()
.AddDynamic<SchemeDefinition>()
.AddTheIdServerStoreRavenDbStore()
.AddGoogle();
var replacedembly = typeof(Enreplacedy.IEnreplacedyId).GetTypeInfo().replacedembly;
var enreplacedyTypeList = replacedembly.GetTypes().Where(t => t.IsClreplaced &&
!t.IsAbstract &&
!t.IsGenericType &&
t.GetInterface(nameof(Enreplacedy.IEnreplacedyId)) != null);
var provider = services.BuildServiceProvider();
foreach (var enreplacedyType in enreplacedyTypeList)
{
var storeType = typeof(IAdminStore<>).MakeGenericType(enreplacedyType);
replacedert.NotNull(provider.GetService(storeType));
}
}
19
Source : ServiceCollectionExtensionsTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void AddIdenreplacedyServer4AdminMongoDbkStores_with_getDatabase_should_add_ravendb_stores_for_each_enreplacedy()
{
var services = new ServiceCollection().AddLogging();
var connectionString = "mongodb://localhost/test";
var uri = new Uri(connectionString);
services.AddTheIdServerMongoDbStores(p => p.GetRequiredService<IMongoDatabase>())
.AddLogging()
.Configure<MemoryCacheOptions>(options => { })
.Configure<ISConfiguration.IdenreplacedyServerOptions>(options => { })
.AddTransient(p => p.GetRequiredService<IOptions<ISConfiguration.IdenreplacedyServerOptions>>().Value)
.AddScoped(typeof(IFlushableCache<>), typeof(FlushableCache<>))
.AddScoped<IMongoClient>(p => new MongoClient(connectionString))
.AddScoped(p => p.GetRequiredService<IMongoClient>().GetDatabase(uri.Segments[1]))
.AddSingleton<HubConnectionFactory>()
.AddTransient(p => new Mock<IConfiguration>().Object)
.AddTransient<IProviderClient, ProviderClient>();
services.AddIdenreplacedy<ApplicationUser, IdenreplacedyRole>()
.AddTheIdServerStores();
services.AddAuthentication()
.AddDynamic<SchemeDefinition>()
.AddTheIdServerEnreplacedyMongoDbStore()
.AddGoogle();
var replacedembly = typeof(Enreplacedy.IEnreplacedyId).GetTypeInfo().replacedembly;
var enreplacedyTypeList = replacedembly.GetTypes().Where(t =>
t.IsClreplaced &&
!t.IsAbstract &&
!t.IsGenericType &&
t.GetInterface(nameof(Enreplacedy.IEnreplacedyId)) != null);
var provider = services.BuildServiceProvider();
foreach (var enreplacedyType in enreplacedyTypeList)
{
var storeType = typeof(IAdminStore<>).MakeGenericType(enreplacedyType);
replacedert.NotNull(provider.GetService(storeType));
}
}
19
Source : RestClient.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public RateLimitBucket GetBucket(RestRequestMethod method, string route, object route_params, out string url)
{
var rparams_props = route_params.GetType()
.GetTypeInfo()
.DeclaredProperties;
var rparams = new Dictionary<string, string>();
foreach (var xp in rparams_props)
{
var val = xp.GetValue(route_params);
rparams[xp.Name] = val is string xs
? xs
: val is DateTime dt
? dt.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)
: val is DateTimeOffset dto
? dto.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture)
: val is IFormattable xf ? xf.ToString(null, CultureInfo.InvariantCulture) : val.ToString();
}
var guild_id = rparams.ContainsKey("guild_id") ? rparams["guild_id"] : "";
var channel_id = rparams.ContainsKey("channel_id") ? rparams["channel_id"] : "";
var webhook_id = rparams.ContainsKey("webhook_id") ? rparams["webhook_id"] : "";
// Create a generic route (minus major params) key
// ex: POST:/channels/channel_id/messages
var hashKey = RateLimitBucket.GenerateHashKey(method, route);
// We check if the hash is present, using our generic route (without major params)
// ex: in POST:/channels/channel_id/messages, out 80c17d2f203122d936070c88c8d10f33
// If it doesn't exist, we create an unlimited hash as our initial key in the form of the hash key + the unlimited constant
// and replacedign this to the route to hash cache
// ex: this.RoutesToHashes[POST:/channels/channel_id/messages] = POST:/channels/channel_id/messages:unlimited
var hash = this.RoutesToHashes.GetOrAdd(hashKey, RateLimitBucket.GenerateUnlimitedHash(method, route));
// Next we use the hash to generate the key to obtain the bucket.
// ex: 80c17d2f203122d936070c88c8d10f33:guild_id:506128773926879242:webhook_id
// or if unlimited: POST:/channels/channel_id/messages:unlimited:guild_id:506128773926879242:webhook_id
var bucketId = RateLimitBucket.GenerateBucketId(hash, guild_id, channel_id, webhook_id);
// If it's not in cache, create a new bucket and index it by its bucket id.
var bucket = this.HashesToBuckets.GetOrAdd(bucketId, new RateLimitBucket(hash, guild_id, channel_id, webhook_id));
bucket.LastAttemptAt = DateTimeOffset.UtcNow;
// Cache the routes for each bucket so it can be used for GC later.
if (!bucket.RouteHashes.Contains(bucketId))
bucket.RouteHashes.Add(bucketId);
// Add the current route to the request queue, which indexes the amount
// of requests occurring to the bucket id.
_ = this.RequestQueue.TryGetValue(bucketId, out var count);
// Increment by one atomically due to concurrency
this.RequestQueue[bucketId] = Interlocked.Increment(ref count);
// Start bucket cleaner if not already running.
if (!this._cleanerRunning)
{
this._cleanerRunning = true;
this._bucketCleanerTokenSource = new CancellationTokenSource();
this._cleanerTask = Task.Run(this.CleanupBucketsAsync, this._bucketCleanerTokenSource.Token);
this.Logger.LogDebug(LoggerEvents.RestCleaner, "Bucket cleaner task started.");
}
url = RouteArgumentRegex.Replace(route, xm => rparams[xm.Groups[1].Value]);
return bucket;
}
19
Source : SnowflakeArrayAsDictionaryJsonConverter.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
}
else
{
var type = value.GetType().GetTypeInfo();
JToken.FromObject(type.GetDeclaredProperty("Values").GetValue(value)).WriteTo(writer);
}
}
19
Source : SnowflakeArrayAsDictionaryJsonConverter.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var constructor = objectType.GetTypeInfo().DeclaredConstructors
.FirstOrDefault(e => !e.IsStatic && e.GetParameters().Length == 0);
var dict = constructor.Invoke(new object[] {});
// the default name of an indexer is "Item"
var properties = objectType.GetTypeInfo().GetDeclaredProperty("Item");
var entries = (IEnumerable) serializer.Deserialize(reader, objectType.GenericTypeArguments[1].MakeArrayType());
foreach (var entry in entries)
{
properties.SetValue(dict, entry, new object[]
{
(entry as SnowflakeObject)?.Id
?? (entry as DiscordVoiceState)?.UserId
?? throw new InvalidOperationException($"Type {entry?.GetType()} is not deserializable")
});
}
return dict;
}
19
Source : SnowflakeArrayAsDictionaryJsonConverter.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public override bool CanConvert(Type objectType)
{
var genericTypedef = objectType.GetGenericTypeDefinition();
if (genericTypedef != typeof(Dictionary<,>) && genericTypedef != typeof(ConcurrentDictionary<,>)) return false;
if (objectType.GenericTypeArguments[0] != typeof(ulong)) return false;
var valueParam = objectType.GenericTypeArguments[1];
return typeof(SnowflakeObject).GetTypeInfo().IsreplacedignableFrom(valueParam.GetTypeInfo()) ||
valueParam == typeof(DiscordVoiceState);
}
19
Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public void RegisterConverter<T>(IArgumentConverter<T> converter)
{
if (converter == null)
throw new ArgumentNullException(nameof(converter), "Converter cannot be null.");
var t = typeof(T);
var ti = t.GetTypeInfo();
this.ArgumentConverters[t] = converter;
if (!ti.IsValueType)
return;
var nullableConverterType = typeof(NullableConverter<>).MakeGenericType(t);
var nullableType = typeof(Nullable<>).MakeGenericType(t);
if (this.ArgumentConverters.ContainsKey(nullableType))
return;
var nullableConverter = Activator.CreateInstance(nullableConverterType) as IArgumentConverter;
this.ArgumentConverters[nullableType] = nullableConverter;
}
19
Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public void UnregisterConverter<T>()
{
var t = typeof(T);
var ti = t.GetTypeInfo();
if (this.ArgumentConverters.ContainsKey(t))
this.ArgumentConverters.Remove(t);
if (this.UserFriendlyTypeNames.ContainsKey(t))
this.UserFriendlyTypeNames.Remove(t);
if (!ti.IsValueType)
return;
var nullableType = typeof(Nullable<>).MakeGenericType(t);
if (!this.ArgumentConverters.ContainsKey(nullableType))
return;
this.ArgumentConverters.Remove(nullableType);
this.UserFriendlyTypeNames.Remove(nullableType);
}
19
Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public void RegisterUserFriendlyTypeName<T>(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException(nameof(value), "Name cannot be null or empty.");
var t = typeof(T);
var ti = t.GetTypeInfo();
if (!this.ArgumentConverters.ContainsKey(t))
throw new InvalidOperationException("Cannot register a friendly name for a type which has no replacedociated converter.");
this.UserFriendlyTypeNames[t] = value;
if (!ti.IsValueType)
return;
var nullableType = typeof(Nullable<>).MakeGenericType(t);
this.UserFriendlyTypeNames[nullableType] = value;
}
19
Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public string GetUserFriendlyTypeName(Type t)
{
if (this.UserFriendlyTypeNames.ContainsKey(t))
return this.UserFriendlyTypeNames[t];
var ti = t.GetTypeInfo();
if (ti.IsGenericTypeDefinition && t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var tn = ti.GenericTypeArguments[0];
return this.UserFriendlyTypeNames.ContainsKey(tn) ? this.UserFriendlyTypeNames[tn] : tn.Name;
}
return t.Name;
}
19
Source : Optional.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var genericType = objectType.GenericTypeArguments[0];
var constructor = objectType.GetTypeInfo().DeclaredConstructors
.FirstOrDefault(e => e.GetParameters()[0].ParameterType == genericType);
return constructor.Invoke(new[] { serializer.Deserialize(reader, genericType) });
}
19
Source : Optional.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public override bool CanConvert(Type objectType) => objectType.GetTypeInfo().ImplementedInterfaces.Contains(typeof(IOptional));
19
Source : CommandsNextUtilities.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
internal static bool IsModuleCandidateType(this TypeInfo ti)
{
// check if compiler-generated
if (ti.GetCustomAttribute<CompilerGeneratedAttribute>(false) != null)
return false;
// check if derives from the required base clreplaced
var tmodule = typeof(BaseCommandModule);
var timodule = tmodule.GetTypeInfo();
if (!timodule.IsreplacedignableFrom(ti))
return false;
// check if anonymous
if (ti.IsGenericType && ti.Name.Contains("AnonymousType") && (ti.Name.StartsWith("<>") || ti.Name.StartsWith("VB$")) && (ti.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic)
return false;
// check if abstract, static, or not a clreplaced
if (!ti.IsClreplaced || ti.IsAbstract)
return false;
// check if delegate type
var tdelegate = typeof(Delegate).GetTypeInfo();
if (tdelegate.IsreplacedignableFrom(ti))
return false;
// qualifies if any method or type qualifies
return ti.DeclaredMethods.Any(xmi => xmi.IsCommandCandidate(out _)) || ti.DeclaredNestedTypes.Any(xti => xti.IsModuleCandidateType());
}
19
Source : Pulse.cs
with MIT License
from aimore
with MIT License
from aimore
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == nameof(Speed))
{
cycleTime /= Speed;
}
if (propertyName == nameof(AutoStart))
{
if (AutoStart)
start();
}
if (propertyName == nameof(Source))
{
string resourceID = Source;
replacedembly replacedembly = GetType().GetTypeInfo().replacedembly;
using (Stream stream = replacedembly.GetManifestResourceStream(resourceID))
{
if (stream != null)
resourceBitmap = SKBitmap.Decode(stream);
}
resourceBitmap = resourceBitmap?.Resize(new SKImageInfo(100, 100), SKFilterQuality.Medium);
}
}
19
Source : ImageResourceExtension.cs
with MIT License
from aimore
with MIT License
from aimore
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
{
return null;
}
// Do your translation lookup here, using whatever method you require
var imageSource = ImageSource.FromResource(Source, typeof(ImageResourceExtension).GetTypeInfo().replacedembly);
return imageSource;
}
19
Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public void RegisterCommands(replacedembly replacedembly)
{
var types = replacedembly.ExportedTypes.Where(xt =>
{
var xti = xt.GetTypeInfo();
return xti.IsModuleCandidateType() && !xti.IsNested;
});
foreach (var xt in types)
this.RegisterCommands(xt);
}
19
Source : CommandsNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
private void RegisterCommands(Type t, CommandGroupBuilder currentParent, IEnumerable<CheckBaseAttribute> inheritedChecks, out List<CommandBuilder> foundCommands)
{
var ti = t.GetTypeInfo();
var lifespan = ti.GetCustomAttribute<ModuleLifespanAttribute>();
var moduleLifespan = lifespan != null ? lifespan.Lifespan : ModuleLifespan.Singleton;
var module = new CommandModuleBuilder()
.WithType(t)
.WithLifespan(moduleLifespan)
.Build(this.Services);
// restrict parent lifespan to more or equally restrictive
if (currentParent?.Module is TransientCommandModule && moduleLifespan != ModuleLifespan.Transient)
throw new InvalidOperationException("In a transient module, child modules can only be transient.");
// check if we are anything
var groupBuilder = new CommandGroupBuilder(module);
var isModule = false;
var moduleAttributes = ti.GetCustomAttributes();
var moduleHidden = false;
var moduleChecks = new List<CheckBaseAttribute>();
foreach (var xa in moduleAttributes)
{
switch (xa)
{
case GroupAttribute g:
isModule = true;
var moduleName = g.Name;
if (moduleName == null)
{
moduleName = ti.Name;
if (moduleName.EndsWith("Group") && moduleName != "Group")
moduleName = moduleName.Substring(0, moduleName.Length - 5);
else if (moduleName.EndsWith("Module") && moduleName != "Module")
moduleName = moduleName.Substring(0, moduleName.Length - 6);
else if (moduleName.EndsWith("Commands") && moduleName != "Commands")
moduleName = moduleName.Substring(0, moduleName.Length - 8);
}
if (!this.Config.CaseSensitive)
moduleName = moduleName.ToLowerInvariant();
groupBuilder.WithName(moduleName);
if (inheritedChecks != null)
foreach (var chk in inheritedChecks)
groupBuilder.WithExecutionCheck(chk);
foreach (var mi in ti.DeclaredMethods.Where(x => x.IsCommandCandidate(out _) && x.GetCustomAttribute<GroupCommandAttribute>() != null))
groupBuilder.WithOverload(new CommandOverloadBuilder(mi));
break;
case AliasesAttribute a:
foreach (var xalias in a.Aliases)
groupBuilder.WithAlias(this.Config.CaseSensitive ? xalias : xalias.ToLowerInvariant());
break;
case HiddenAttribute h:
groupBuilder.WithHiddenStatus(true);
moduleHidden = true;
break;
case DescriptionAttribute d:
groupBuilder.WithDescription(d.Description);
break;
case CheckBaseAttribute c:
moduleChecks.Add(c);
groupBuilder.WithExecutionCheck(c);
break;
default:
groupBuilder.WithCustomAttribute(xa);
break;
}
}
if (!isModule)
{
groupBuilder = null;
if (inheritedChecks != null)
moduleChecks.AddRange(inheritedChecks);
}
// candidate methods
var methods = ti.DeclaredMethods;
var commands = new List<CommandBuilder>();
var commandBuilders = new Dictionary<string, CommandBuilder>();
foreach (var m in methods)
{
if (!m.IsCommandCandidate(out _))
continue;
var attrs = m.GetCustomAttributes();
if (attrs.FirstOrDefault(xa => xa is CommandAttribute) is not CommandAttribute cattr)
continue;
var commandName = cattr.Name;
if (commandName == null)
{
commandName = m.Name;
if (commandName.EndsWith("Async") && commandName != "Async")
commandName = commandName.Substring(0, commandName.Length - 5);
}
if (!this.Config.CaseSensitive)
commandName = commandName.ToLowerInvariant();
if (!commandBuilders.TryGetValue(commandName, out var commandBuilder))
{
commandBuilders.Add(commandName, commandBuilder = new CommandBuilder(module).WithName(commandName));
if (!isModule)
if (currentParent != null)
currentParent.WithChild(commandBuilder);
else
commands.Add(commandBuilder);
else
groupBuilder.WithChild(commandBuilder);
}
commandBuilder.WithOverload(new CommandOverloadBuilder(m));
if (!isModule && moduleChecks.Any())
foreach (var chk in moduleChecks)
commandBuilder.WithExecutionCheck(chk);
foreach (var xa in attrs)
{
switch (xa)
{
case AliasesAttribute a:
foreach (var xalias in a.Aliases)
commandBuilder.WithAlias(this.Config.CaseSensitive ? xalias : xalias.ToLowerInvariant());
break;
case CheckBaseAttribute p:
commandBuilder.WithExecutionCheck(p);
break;
case DescriptionAttribute d:
commandBuilder.WithDescription(d.Description);
break;
case HiddenAttribute h:
commandBuilder.WithHiddenStatus(true);
break;
default:
commandBuilder.WithCustomAttribute(xa);
break;
}
}
if (!isModule && moduleHidden)
commandBuilder.WithHiddenStatus(true);
}
// candidate types
var types = ti.DeclaredNestedTypes
.Where(xt => xt.IsModuleCandidateType() && xt.DeclaredConstructors.Any(xc => xc.IsPublic));
foreach (var type in types)
{
this.RegisterCommands(type.AsType(),
groupBuilder,
!isModule ? moduleChecks : null,
out var tempCommands);
if (isModule)
foreach (var chk in moduleChecks)
groupBuilder.WithExecutionCheck(chk);
if (isModule && tempCommands != null)
foreach (var xtcmd in tempCommands)
groupBuilder.WithChild(xtcmd);
else if (tempCommands != null)
commands.AddRange(tempCommands);
}
if (isModule && currentParent == null)
commands.Add(groupBuilder);
else if (isModule)
currentParent.WithChild(groupBuilder);
foundCommands = commands;
}
19
Source : EnumConverter.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
Task<Optional<T>> IArgumentConverter<T>.ConvertAsync(string value, CommandContext ctx)
{
var t = typeof(T);
var ti = t.GetTypeInfo();
return !ti.IsEnum
? throw new InvalidOperationException("Cannot convert non-enum value to an enum.")
: Enum.TryParse(value, !ctx.Config.CaseSensitive, out T ev)
? Task.FromResult(Optional.FromValue(ev))
: Task.FromResult(Optional.FromNoValue<T>());
}
19
Source : CommandsNextUtilities.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
internal static bool IsModuleCandidateType(this Type type)
=> type.GetTypeInfo().IsModuleCandidateType();
19
Source : CommandsNextUtilities.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
internal static object CreateInstance(this Type t, IServiceProvider services)
{
var ti = t.GetTypeInfo();
var constructors = ti.DeclaredConstructors
.Where(xci => xci.IsPublic)
.ToArray();
if (constructors.Length != 1)
throw new ArgumentException("Specified type does not contain a public constructor or contains more than one public constructor.");
var constructor = constructors[0];
var constructorArgs = constructor.GetParameters();
var args = new object[constructorArgs.Length];
if (constructorArgs.Length != 0 && services == null)
throw new InvalidOperationException("Dependency collection needs to be specified for parameterized constructors.");
// inject via constructor
if (constructorArgs.Length != 0)
for (var i = 0; i < args.Length; i++)
args[i] = services.GetRequiredService(constructorArgs[i].ParameterType);
var moduleInstance = Activator.CreateInstance(t, args);
// inject into properties
var props = t.GetRuntimeProperties().Where(xp => xp.CanWrite && xp.SetMethod != null && !xp.SetMethod.IsStatic && xp.SetMethod.IsPublic);
foreach (var prop in props)
{
if (prop.GetCustomAttribute<DontInjectAttribute>() != null)
continue;
var service = services.GetService(prop.PropertyType);
if (service == null)
continue;
prop.SetValue(moduleInstance, service);
}
// inject into fields
var fields = t.GetRuntimeFields().Where(xf => !xf.IsInitOnly && !xf.IsStatic && xf.IsPublic);
foreach (var field in fields)
{
if (field.GetCustomAttribute<DontInjectAttribute>() != null)
continue;
var service = services.GetService(field.FieldType);
if (service == null)
continue;
field.SetValue(moduleInstance, service);
}
return moduleInstance;
}
19
Source : ImageResourceExtension.cs
with MIT License
from aimore
with MIT License
from aimore
public static string ImageNameFromResource(string u)
{
var replacedembly = typeof(App).GetTypeInfo().replacedembly;
foreach (var res in replacedembly.GetManifestResourceNames())
{
// System.Diagnostics.Debug.WriteLine("found resource: " + res);
if (res.Contains(u))
{
return res;
}
}
return null;
}
19
Source : NavigationService.cs
with MIT License
from aimore
with MIT License
from aimore
private Type GetPageTypeForViewModel(Type viewModelType)
{
var viewName = viewModelType.FullName.Replace("Model", string.Empty);
var viewModelreplacedemblyName = viewModelType.GetTypeInfo().replacedembly.FullName;
var viewreplacedemblyName = string.Format(CultureInfo.InvariantCulture, "{0}, {1}", viewName, viewModelreplacedemblyName);
var viewType = Type.GetType(viewreplacedemblyName);
return viewType;
}
19
Source : TestHelper.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
public static async ValueTask replacedertFailure<T>(this IAsyncEnumerator<T> source, Type exception,
params T[] values)
{
var idx = 0;
try
{
while (await source.MoveNextAsync())
{
replacedert.True(idx < values.Length, "Source has more than the expected " + values.Length + " items");
replacedert.Equal(source.Current, values[idx]);
idx++;
}
replacedert.True(false, "Did not throw any exception but expected: " + exception);
}
catch (TrueException)
{
throw;
}
catch (Exception ex)
{
replacedert.True(values.Length == idx, "Source has less items than expected: " + values.Length + ", actual: " + idx);
replacedert.True(exception.GetTypeInfo().IsreplacedignableFrom(ex.GetType().GetTypeInfo()), "Wrong exception, Expected: " + exception + ", Actual: " + ex);
}
finally
{
await source.DisposeAsync();
}
}
19
Source : TestObserver.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
public TestObserver<T> replacedertError(Type expectedType, string message = null, bool messageContains = false)
{
var c = Volatile.Read(ref errorCount);
if (c == 0)
{
throw Fail("No error.");
}
var members = expectedType.GetTypeInfo();
var found = 0;
var foundRaw = 0;
for (int i = 0; i < c; i++)
{
if (members.IsreplacedignableFrom(errors[i].GetType().GetTypeInfo()))
{
if (message != null)
{
if (messageContains)
{
if (errors[i].Message.Contains(message))
{
found++;
}
}
else
{
if (errors[i].Message.Equals(message))
{
found++;
}
}
} else {
found++;
}
foundRaw++;
}
}
if (found == 1 && c > 1)
{
throw Fail("Exception present but others as well");
}
if (found > 1)
{
throw Fail("The Exception appears multiple times");
}
if (found == 0)
{
if (foundRaw != 0)
{
throw Fail("Exception type present but not with the specified message" + (messageContains ? " part: " : ": ") + message);
}
throw Fail("Exception not present");
}
return this;
}
19
Source : TestObserver.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
public TestObserver<T> replacedertCompositeError(int index, Type errorType, string message = null, bool messageContains = false)
{
replacedertError(typeof(AggregateException));
var exs = (errors[0] as AggregateException).InnerExceptions;
if (index < 0 || index >= exs.Count)
{
throw Fail("The AggregateException index out of bounds. Expected: " + index + ", Actual: " + exs.Count);
}
if (errorType.GetTypeInfo().IsreplacedignableFrom(exs[index].GetType().GetTypeInfo()))
{
if (message != null)
{
if (messageContains)
{
if (!exs[index].Message.Contains(message))
{
throw Fail("Error found with a different message part. Expected: " + message + ", Actual: " + exs[index].Message);
}
}
else
{
if (!exs[index].Message.Equals(message))
{
throw Fail("Error found with a different message. Expected: " + message + ", Actual: " + exs[index].Message);
}
}
}
return this;
}
throw Fail("Wrong error type @ " + index + ". Expected: " + errorType + ", Actual: " + exs[index].GetType());
}
19
Source : TestObserver.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
public TestObserver<T> replacedertCompositeError(Type errorType, string message = null, bool messageContains = false)
{
replacedertError(typeof(AggregateException));
var exs = (errors[0] as AggregateException).InnerExceptions;
TypeInfo typeInfo = errorType.GetTypeInfo();
foreach (var ex in exs)
{
if (typeInfo.IsreplacedignableFrom(ex.GetType().GetTypeInfo()))
{
if (message != null)
{
if (messageContains)
{
if (!ex.Message.Contains(message))
{
throw Fail("Error found with a different message part. Expected: " + message + ", Actual: " + ex.Message);
}
}
else
{
if (!ex.Message.Equals(message))
{
throw Fail("Error found with a different message. Expected: " + message + ", Actual: " + ex.Message);
}
}
}
return this;
}
}
throw Fail("Error not found inside the AggregateException: " + errorType);
}
19
Source : TestHelper.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
public static bool IsreplacedignableFrom<T>(this Type type, T item)
{
return type.GetTypeInfo().IsreplacedignableFrom(item.GetType().GetTypeInfo());
}
19
Source : TestSubscriber.cs
with Apache License 2.0
from akarnokd
with Apache License 2.0
from akarnokd
public TestSubscriber<T> replacedertError(Type errorType)
{
long ec = Volatile.Read(ref errorCount);
if (ec == 0)
{
throw Fail("No errors present");
}
if (ec == 1)
{
if (!errorType.GetTypeInfo().IsInstanceOfType(errors[0]))
{
throw Fail("Different error present");
}
}
else
{
for (int i = 0; i < ec; i++)
{
if (!errorType.GetTypeInfo().IsInstanceOfType(errors[i]))
{
throw Fail("Error found but there are others");
}
}
throw Fail("Different errors present");
}
return this;
}
19
Source : MediatorModule.cs
with MIT License
from akinix
with MIT License
from akinix
protected override void Load(ContainerBuilder builder)
{
builder.RegisterreplacedemblyTypes(typeof(IMediator).GetTypeInfo().replacedembly)
.AsImplementedInterfaces();
var mediatrOpenTypes = new[]
{
typeof(IRequestHandler<,>),
typeof(IRequestHandler<>),
typeof(INotificationHandler<>),
};
foreach (var mediatrOpenType in mediatrOpenTypes)
{
builder
.RegisterreplacedemblyTypes(typeof(MediatorModule).GetTypeInfo().replacedembly)
.AsClosedTypesOf(mediatrOpenType)
.AsImplementedInterfaces();
}
// 参照官网
builder.Register<SingleInstanceFactory>(context =>
{
var componentContext = context.Resolve<IComponentContext>();
return t => { object o; return componentContext.TryResolve(t, out o) ? o : null; };
});
builder.Register<MultiInstanceFactory>(context =>
{
var componentContext = context.Resolve<IComponentContext>();
return t =>
{
var resolved = (IEnumerable<object>)componentContext.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
return resolved;
};
});
builder.RegisterGeneric(typeof(LoggingBehavior<,>)).As(typeof(IPipelineBehavior<,>));
}
See More Examples