public void Test_GetDescription() { Assert.Equal("", Reflections.GetDescription <EnumSample>("X")); Assert.Equal("A", Reflections.GetDescription <EnumSample>("A")); Assert.Equal("B2", Reflections.GetDescription <EnumSample>("B")); Assert.Equal("IntValue", Reflections.GetDescription <Sample>("IntValue")); }
public List <Person> GetAnonymizedData(IEnumerable <Person> people) { List <Person> anonymzedData; if (_propertyName == null) { var propertyInfo = Reflections.GetPropertyInfo(new Person(), _anonimizedExpression); anonymzedData = people.Select(p => { var clone = p.Clone(); propertyInfo.SetValue(clone, Convert.ChangeType("*", propertyInfo.PropertyType), null); return(clone); }) .ToList(); } else { anonymzedData = people.Select(p => { var clone = p.Clone(); clone.GetType().GetProperty(_propertyName)?.SetValue(clone, "*"); return(clone); }) .ToList(); } return(anonymzedData); }
[Test] public void GetInvokerOrNull_FiltersMethod() { Base b = new Base(); var dProtected = Reflections.GetInvokerOrNull <Func <T> >( b, b.GetType(), "ProtectedVirtualInstance", BindingFlags.Instance | BindingFlags.NonPublic, null); Assert.NotNull(dProtected); var dPrivate = Reflections.GetInvokerOrNull <Action <T> >( b, b.GetType(), "PrivateInstance", BindingFlags.Instance | BindingFlags.NonPublic, null); Assert.NotNull(dPrivate); dProtected = Reflections.GetInvokerOrNull <Func <T> >( b, b.GetType(), "ProtectedVirtualInstance", BindingFlags.Instance | BindingFlags.NonPublic, m => m.IsFamily); Assert.NotNull(dProtected); dPrivate = Reflections.GetInvokerOrNull <Action <T> >( b, b.GetType(), "PrivateInstance", BindingFlags.Instance | BindingFlags.NonPublic, m => m.IsFamily); Assert.Null(dPrivate); }
public Task StartAsync(CancellationToken cancellationToken) { this.logger.LogInformation("Creating RabbitMQ connection."); var factory = RabbitConnectionFactory(); this.connection = factory.CreateConnection(CreateConnectionId()); var model = this.connection.CreateModel(); this.declarationService.DeclareAll(model); // Find all controllers and wire them up foreach (var consumerMethod in Reflections.GetControllerConsumerMethods()) { this.consumers.Add( new RabbitConsumer( consumerMethod, model, this.configuration, this.serviceProvider, this.loggerFactory.CreateLogger <RabbitConsumer>())); } return(Task.CompletedTask); }
void ExtractDragDrop(object obj) { var paths = Reflections.GetTypes(obj); var binary = paths.FirstOrDefault(e => e.Value == typeof(byte[])); if (string.IsNullOrWhiteSpace(binary.Key)) { splitContainer1.Panel2Collapsed = true; dragDropControl1.Mode = DragDropMode.None; dragDropControl1.Visible = false; dragDropControl1.Title = string.Empty; } else { splitContainer1.Panel2Collapsed = false; dragDropControl1.Mode = DragDropMode.Output; dragDropControl1.Visible = true; dragDropControl1.Title = string.Empty; var chunks = Reflections.Extract <byte[]>(obj, binary.Key); var i = 0; foreach (var bytes in chunks) { var ext = MimeType.GetFileType(bytes); var key = binary.Key.Replace("/Item/", $"/{++i}/"); var count = key.LastIndexOf('/') - 1; if (count < 1) { count = key.Length - 1; } key = key.Substring(1, count); var name = $"{key.Replace('/', '_')}.{ext}"; dragDropControl1.AddFile(name, bytes); } } }
/// <summary> /// Bing框架初始化,适用于AspNetCore环境 /// </summary> /// <param name="app">应用程序构建器</param> public static IApplicationBuilder UseBing(this IApplicationBuilder app) { var provider = app.ApplicationServices; var logger = provider.GetLogger(FrameworkLog); logger.LogInformation("Bing框架初始化开始"); // 输出注入服务的日志 //var startupLogger = provider.GetService<StartupLogger>(); //startupLogger.Output(provider); var watch = Stopwatch.StartNew(); var modules = provider.GetAllModules(); foreach (var module in modules) { var moduleName = Reflections.GetDescription(module.GetType()); logger.LogInformation($"正在初始化模块 “{moduleName}”"); if (module is AspNetCoreBingModule netCoreModule) { netCoreModule.UseModule(app); } else { module.UseModule(provider); } logger.LogInformation($"模块 “{moduleName}” 初始化完成"); } watch.Stop(); logger.LogInformation($"Bing框架初始化完成,耗时:{watch.Elapsed}"); return(app); }
[Test] public void GetInvoker_FiltersMethod() { Base b = new Base(); var message = "protected methods only"; var dProtected = Reflections.GetInvoker <Func <T> >( b, b.GetType(), "ProtectedVirtualInstance", BindingFlags.Instance | BindingFlags.NonPublic, null, null); Assert.NotNull(dProtected); var dPrivate = Reflections.GetInvoker <Action <T> >( b, b.GetType(), "PrivateInstance", BindingFlags.Instance | BindingFlags.NonPublic, null, null); Assert.NotNull(dPrivate); dProtected = Reflections.GetInvoker <Func <T> >( b, b.GetType(), "ProtectedVirtualInstance", BindingFlags.Instance | BindingFlags.NonPublic, m => m.IsFamily, message); Assert.NotNull(dProtected); var e = Assert.Throws <MissingMethodException>( delegate { Reflections.GetInvoker <Action <T> >( b, b.GetType(), "PrivateInstance", BindingFlags.Instance | BindingFlags.NonPublic, m => m.IsFamily, message); }); StringAssert.Contains(message, e.Message); }
/// <summary> /// Get English name<br /> /// 获取英文名称 /// </summary> /// <param name="chineseSolarTerms"></param> /// <returns></returns> public static string GetEnglishName(this ChineseSolarTerms chineseSolarTerms) { var fieldName = EnumsNET.Enums.GetName(chineseSolarTerms); var typeInfo = typeof(ChineseSolarTerms).GetTypeInfo(); var fieldInfo = typeInfo.GetField(fieldName); return(Reflections.GetDescriptionOrDisplayName(fieldInfo)); }
public void ShouldReturnCurrentType() { // when var currentType = Reflections.CurrentType(); // then Check.That(currentType).IsEqualTo(GetType()); }
public static ProgrammableBlockProxy Wrap(MyProgrammableBlock programmableBlock) { if (_reflections == null) { _reflections = new Reflections(typeof(MyProgrammableBlock)); } return(new ProgrammableBlockProxy(programmableBlock)); }
/// <summary> /// Add /// </summary> /// <param name="expression"></param> /// <param name="newValue"></param> /// <typeparam name="TObject"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <typeparam name="TValue"></typeparam> public void Add <TObject, TProperty, TValue>(Expression <Func <TObject, TProperty> > expression, TValue newValue) where TObject : IDomainObject { var name = Lambdas.GetName(expression); var desc = Reflections.GetDescription(Lambdas.GetMember(expression)); var value = Lambdas.GetValue(expression); Add(name, desc, value.CastTo <TValue>(), newValue); }
// END CUT HERE // BEGIN CUT HERE public static void Main() { try { Reflections ___test = new Reflections(); ___test.run_test(-1); } catch (Exception e) { //Console.WriteLine(e.StackTrace); Console.WriteLine(e.ToString()); } }
// END CUT HERE // BEGIN CUT HERE public static void Main() { try { Reflections ___test = new Reflections(); ___test.run_test(-1); } catch(Exception e) { //Console.WriteLine(e.StackTrace); Console.WriteLine(e.ToString()); } }
/// <summary> /// 添加模块 /// </summary> /// <param name="type">类型</param> private IBingBuilder AddModule(Type type) { if (!type.IsBaseOn(typeof(BingModule))) { throw new BingFrameworkException($"要加载的模块类型“{type}”不派生于基类 {nameof(BingModule)}"); } if (_modules.Any(m => m.GetType() == type)) { return(this); } var tmpModules = new BingModule[_modules.Count]; _modules.CopyTo(tmpModules); var module = _sourceModules.FirstOrDefault(x => x.GetType() == type); if (module == null) { throw new BingFrameworkException($"类型为“{type.FullName}”的模块实例无法找到"); } _modules.AddIfNotContains(module); // 添加依赖模块 var dependTypes = module.GetDependModuleTypes(); foreach (var dependType in dependTypes) { var dependModule = _sourceModules.Find(m => m.GetType() == dependType); if (dependModule == null) { throw new BingFrameworkException($"加载模块{module.GetType().FullName}时无法找到依赖模块{dependType.FullName}"); } _modules.AddIfNotContains(dependModule); } // 按先层级后顺序的规则进行排序 _modules = _modules.OrderBy(m => m.Level).ThenBy(m => m.Order).ToList(); var logName = typeof(BingBuilder).FullName; tmpModules = _modules.Except(tmpModules).ToArray(); foreach (var tmpModule in tmpModules) { var moduleType = tmpModule.GetType(); var moduleName = Reflections.GetDescription(moduleType); Services.LogInformation($"添加模块 “{moduleName} ({moduleType.Name})” 的服务", logName); var tmp = Services.ToArray(); AddModule(Services, tmpModule); Services.ServiceLogDebug(tmp, moduleType.FullName); Services.LogInformation($"模块 “{moduleName} ({moduleType.Name})” 的服务添加完毕,添加了 {Services.Count - tmp.Length} 个服务\n", logName); } return(this); }
public void ShouldReturnObjectFieldsExcludingBaseType() { // given var obj = new ComplexObjectWithFields(id: 1, name: "Test", value: 15, date: new DateTime(2015, 4, 21, 0, 0, 0)); // when var fields = Reflections.Fields(obj: obj, includeBase: false); // then Check.That(fields.OrderedKeys).ContainsExactly("id"); Check.That(fields.Get("id")).IsEqualTo(1); }
private bool AreGroupAnonymzedMaximally(IEnumerable <PeopleGroup <string> > groups, int commonLength) { var result = groups.Any(g => g.Count < ParameterK || g.People.Any(p => { var propertyInfo = Reflections.GetPropertyInfo(p, _anonimizedExpression); return(propertyInfo.GetValue(p).ToString().Length < commonLength); }) ); return(result); }
/// <summary> /// 启用Aop /// </summary> /// <param name="services">服务集合</param> /// <param name="configAction">Aop配置</param> public static void EnableAop(this IServiceCollection services, Action <IAspectConfiguration> configAction = null) { services.ConfigureDynamicProxy(config => { config.EnableParameterAspect(); config.NonAspectPredicates.Add(t => Reflections.GetTopBaseType(t.DeclaringType).SafeString() == "Microsoft.EntityFrameworkCore.DbContext"); configAction?.Invoke(config); }); services.EnableAspectScoped(); }
public static int PropertiesHash(this object obj) { var properties = Reflections.Properties(obj); var hashCode = 1; foreach (var key in properties.OrderedKeys) { var value = properties.GetIfPresent(key); hashCode = 31 * hashCode + Objects.HashCode(value); } return(hashCode); }
public static int FieldsHash(this object obj) { var fields = Reflections.Fields(obj); var hashCode = 1; foreach (var key in fields.OrderedKeys) { var value = fields.GetIfPresent(key); hashCode = 31 * hashCode + Objects.HashCode(value); } return(hashCode); }
public void ChangeAlgorithmConfiguration(Type algorithm, AlgorithmConfiguration config) { Guard.Argument(algorithm).Require(Reflections.IsAlgorithm, x => $"{x} is not an algorithm"); if (!Reflections.AlgorithmMatchesConfiguration(algorithm, config.GetType())) { throw new InvalidOperationException($"Cannot set algorithm to {algorithm} with config {config} because they are not compatible."); } __algorithm = algorithm.Name; _enabledAlgorithmConstructor.Invalidate(); AlgorithmConfiguration = config; }
/// <summary> /// Generates object hashCode from properties. /// Collections are supported. /// </summary> /// <param name="source">this</param> /// <returns>hashCode</returns> public static int PropertiesHash(this object source) { Preconditions.IsNotNull(source, () => new ArgumentNullException("source")); var properties = Reflections.Properties(source); var hashCode = 1; foreach (var key in properties.OrderedKeys) { var value = properties.GetIfPresent(key); hashCode = 31 * hashCode + Objects.HashCode(value); } return(hashCode); }
public void ReadChildData(BinaryReader reader) { _bitmap.ReadString(reader); for (int x = 0; x < _reflections.Count; x++) { Reflections.AddNew(); Reflections[x].Read(reader); } for (int x = 0; x < _reflections.Count; x++) { Reflections[x].ReadChildData(reader); } }
/// <summary> /// 设置保留小数位数 /// </summary> /// <param name="propertyInfo">属性信息</param> /// <param name="setting">属性设置</param> private static void SetScale(PropertyInfo propertyInfo, PropertySetting setting) { if (!Types.IsNumericType(Reflections.GetUnderlyingType(propertyInfo.PropertyType))) { return; } var attribute = propertyInfo.GetCustomAttribute <DecimalScaleAttribute>(); if (attribute != null) { setting.DecimalScale = attribute.Scale; } }
/// <summary> /// Builds container by evaluation the Trading command line argument. /// </summary> /// <param name="algorithmConfiguration">The configuration of the algorithm.</param> /// <typeparam name="T">The type of the algorithm.</typeparam> /// <returns>Binance container with providers.</returns> public ExchangeProvidersContainer BuildContainer <T>(AlgorithmConfiguration algorithmConfiguration) where T : IBaseAlgorithm { if (!Reflections.AlgorithmMatchesConfiguration(typeof(T), algorithmConfiguration.GetType())) { throw new InvalidOperationException( $"Cannot build container for {typeof(T).Name} using a {algorithmConfiguration.GetType().Name} object"); } return(Program.CommandLineArgs.Trading ? BuildBinanceContainer <T>(algorithmConfiguration) : BuildBacktestingContainer <T>(algorithmConfiguration)); }
public static ReflectedInfo For(Type T) { lock (Reflections) { if (Reflections.ContainsKey(T)) { return(Reflections[T]); } var newInfo = new ReflectedInfo(T); Reflections.Add(T, newInfo); return(newInfo); } }
public void ShouldReturnObjectFields() { // given var obj = new ObjectWithFields(name: "Test", value: 15, date: new DateTime(2015, 4, 21, 0, 0, 0)); // when var fields = Reflections.Fields(obj); // then Check.That(fields.OrderedKeys).ContainsExactly("name", "value", "date"); Check.That(fields.Get("name")).IsEqualTo("Test"); Check.That(fields.Get("value")).IsEqualTo(15); Check.That(fields.Get("date")).IsEqualTo(new DateTime(2015, 4, 21, 0, 0, 0)); }
public List <Person> GetAnonymizedData(IEnumerable <Person> people) { if (people == null || !people.Any()) { return(new List <Person>()); } var groupsOrderedByLength = people.GroupBy(p => { var propertyInfo = Reflections.GetPropertyInfo(p, _anonimizedExpression); return(propertyInfo.GetValue(p).ToString().Length); }) .Select(gPeople => new { Value = gPeople.Select(_anonimizedProperty).First().ToString().Length, People = gPeople.ToList(), Count = gPeople.Count() }) .OrderBy(p => p.Value); var result = new List <List <Person> >(); var currentIntervalGroup = new List <Person>(); foreach (var group in groupsOrderedByLength) { if (currentIntervalGroup.Count < ParameterK) { currentIntervalGroup.AddRange(group.People); } else { result.Add(currentIntervalGroup); currentIntervalGroup = new List <Person>(group.People); } } //Handle last left group if (currentIntervalGroup.Count < ParameterK && result.Any()) { result.Last().AddRange(currentIntervalGroup); } else { result.Add(currentIntervalGroup); } var flattenedResult = result.Select(GetPeopleWithAnnonymazedAgeRange).SelectMany(x => x).ToList(); return(flattenedResult); }
public void ShouldReturnObjectFieldsIncludingBaseType() { // given var obj = new ComplexObjectWithFields(id: 1, name: "Test", value: 15, date: null); // when var fields = Reflections.Fields(obj: obj, includeBase: true); // then Check.That(fields.OrderedKeys).ContainsExactly("id", "name", "value", "date"); Check.That(fields.Get("id")).IsEqualTo(1); Check.That(fields.Get("name")).IsEqualTo("Test"); Check.That(fields.Get("value")).IsEqualTo(15); Check.That(fields.GetIfPresent("date")).IsNull(); }
/// <summary> /// 获取市政路灯扩展信息 /// </summary> public object GetInfo(string where = "", object objModel = null, int flag = 0) { //路灯信息 RoadLampMDL = (new BLL.T_Project_RoadLamp_BLL().QueryRoadLamp_ByProjID(where)); //工程信息 objModel = Reflections.Control_Reflection(typeof(T_Projects), objModel, this.Controls, "txt_ld_", flag) as T_Projects; if (RoadLampMDL == null) { RoadLampMDL = new T_Project_RoadLamp(); } Reflections.Control_Reflection(typeof(T_Project_RoadLamp), RoadLampMDL, this.Controls, "txt_ld_", flag); return(objModel); }
/// <summary> /// 获取方法调用表达式的成员名称 /// </summary> /// <param name="expression">表达式</param> private static MemberExpression GetMethodCallExpressionName(Expression expression) { var methodCallExpression = (MethodCallExpression)expression; var left = (MemberExpression)methodCallExpression.Object; if (Reflections.IsGenericCollection(left?.Type)) { var argumentExpression = methodCallExpression.Arguments.FirstOrDefault(); if (argumentExpression != null && argumentExpression.NodeType == ExpressionType.MemberAccess) { return((MemberExpression)argumentExpression); } } return(left); }
public virtual void ReadChildData(BinaryReader reader) { int x = 0; _bitmap.ReadString(reader); for (x = 0; (x < _reflections.Count); x = (x + 1)) { Reflections.Add(new LensFlareReflectionBlock()); Reflections[x].Read(reader); } for (x = 0; (x < _reflections.Count); x = (x + 1)) { Reflections[x].ReadChildData(reader); } }
/// <summary> /// 打印出StoreMap的数据 /// </summary> public static void printStoreMap(Reflections reflections) { LOGGER.info("Now we will print store map......"); Store store = reflections.Store; IDictionary<string, Multimap<string, string>> storeMap = store.StoreMap; // indexName foreach (string indexName in storeMap.Keys) { LOGGER.info("===================================="); LOGGER.info("indexName:" + indexName); Multimap<string, string> multimap = storeMap[indexName]; foreach (string firstName in multimap.Keys) { ICollection<string> lastNames = multimap.get(firstName); LOGGER.info("\t\t" + firstName + ": " + lastNames); } } }
/// <summary> /// 通过扫描,获取反射对象 /// </summary> private Reflections getReflection(IList<string> packNameList) { // // filter // FilterBuilder filterBuilder = (new FilterBuilder()).includePackage(Constants.DISCONF_PACK_NAME); foreach (string packName in packNameList) { filterBuilder = filterBuilder.includePackage(packName); } Predicate<string> filter = filterBuilder; // // urls // ICollection<URL> urlTotals = new List<URL>(); foreach (string packName in packNameList) { ISet<URL> urls = ClasspathHelper.forPackage(packName); urlTotals.addAll(urls); } // Reflections reflections = new Reflections((new ConfigurationBuilder()).filterInputsBy(filter).setScanners((new SubTypesScanner()).filterResultsBy(filter), new TypeAnnotationsScanner() .filterResultsBy(filter), (new FieldAnnotationsScanner()).filterResultsBy(filter), (new MethodAnnotationsScanner()).filterResultsBy(filter), new MethodParameterScanner()).setUrls(urlTotals)); return reflections; }