public void TestGetCompositeObjects() { var testReflect = new ReflectUtil<string>(); ISet<string> set = testReflect.GetCompositeObjects(new TestClass(0, new HashSet<string>() { "1" }, new string[] {"2"})); Assert.NotNull(set); CollectionAssert.IsNotEmpty(set); CollectionAssert.AllItemsAreNotNull(set); CollectionAssert.AllItemsAreInstancesOfType(set, typeof(string)); Assert.AreEqual(2, set.Count); CollectionAssert.Contains(set, "1"); CollectionAssert.Contains(set, "2"); }
public void TestGetCompositeObjectsIgnore() { PropertyInfo propertyInfo = typeof(TestClass).GetProperty("Field2"); var testReflect = new ReflectUtil<string>(); ISet<string> set = testReflect.GetCompositeObjects(new TestClass(0, new HashSet<string>() { "1" }, new string[] {"2"}), propertyInfo); Assert.NotNull(set); CollectionAssert.IsNotEmpty(set); CollectionAssert.AllItemsAreNotNull(set); CollectionAssert.AllItemsAreInstancesOfType(set, typeof(string)); Assert.AreEqual(1, set.Count); CollectionAssert.Contains(set, "1"); }
private void RegisterAllWhere(Assembly asm, Predicate <Type> filter) { // Register classes that represents commands ( from type in asm.GetTypes() where !type.IsAbstract && typeof(ICommand).IsAssignableFrom(type) && type != typeof(MethodCommand) where filter(type) select(ICommand) EssCore.Instance.CommonInstancePool.GetOrCreate(type) ).ForEach(Register); // Register methods that represents commands T createDelegate <T>(object obj, MethodInfo method) where T : class { return(obj == null ? Delegate.CreateDelegate(typeof(T), method) as T : Delegate.CreateDelegate(typeof(T), obj, method.Name) as T); } ; ( from type in asm.GetTypes() where filter(type) from method in type.GetMethods(ReflectUtil.STATIC_INSTANCE_FLAGS) where ReflectUtil.GetAttributeFrom <CommandInfoAttribute>(method) != null select method ).ForEach(method => { var inst = method.IsStatic ? null : EssCore.Instance.CommonInstancePool.GetOrCreate(method.DeclaringType); var methodParams = method.GetParameters(); if (method.ReturnType != typeof(CommandResult)) { UEssentials.Logger.LogError($"Invalid method signature in '{method}'. " + "Expected CommandResult as return type"); return; } // CommandResult methodName(ICommandSource, ICommandArgs) if ( methodParams.Length == 2 && methodParams[0].ParameterType == typeof(ICommandSource) && methodParams[1].ParameterType == typeof(ICommandArgs) ) { Register(createDelegate <Func <ICommandSource, ICommandArgs, CommandResult> >(inst, method)); return; } // CommandResult methodName(ICommandSource, ICommandArgs, ICommand) if ( methodParams.Length == 3 && methodParams[0].ParameterType == typeof(ICommandSource) && methodParams[1].ParameterType == typeof(ICommandArgs) && methodParams[2].ParameterType == typeof(ICommand) ) { Register(createDelegate <Func <ICommandSource, ICommandArgs, ICommand, CommandResult> >(inst, method)); return; } UEssentials.Logger.LogError($"Invalid method signature in '{method}'. " + "Expected parameters (ICommandSource, ICommandArgs) or (ICommandSource, ICommandArgs, ICommand)"); }); }
private void B_ReadRAM_Click(object sender, EventArgs e) { var txt = RamOffset.Text; var offset = Util.GetHexValue64(txt); var valid = int.TryParse(RamSize.Text, out int size); if (offset.ToString("X16") != txt.ToUpper().PadLeft(16, '0') || !valid) { WinFormsUtil.Alert("Make sure that the RAM offset is a hex string and the size is a valid integer"); return; } try { byte[] result; if (Remote.Bot.com is not ICommunicatorNX cnx) { result = Remote.ReadRAM(offset, size); } else { if (RB_Main.Checked) { result = cnx.ReadBytesMain(offset, size); } else if (RB_Absolute.Checked) { result = cnx.ReadBytesAbsolute(offset, size); } else { result = Remote.ReadRAM(offset, size); } } bool blockview = (ModifierKeys & Keys.Control) == Keys.Control; PKM? pkm = null; if (blockview) { pkm = SAV.SAV.GetDecryptedPKM(result); if (!pkm.ChecksumValid || pkm == null) { blockview = false; } } using (var form = new SimpleHexEditor(result, Remote.Bot, offset, GetRWMethod())) { #pragma warning disable CS8602 // Dereference of a possibly null reference. var loadgrid = blockview && ReflectUtil.GetPropertiesCanWritePublicDeclared(pkm.GetType()).Count() > 1; #pragma warning restore CS8602 // Dereference of a possibly null reference. if (loadgrid) { form.PG_BlockView.Visible = true; form.PG_BlockView.SelectedObject = pkm; } var res = form.ShowDialog(); if (res == DialogResult.OK) { if (loadgrid && pkm != null) { var pkmbytes = RamOffsets.WriteBoxData(Remote.Bot.Version) ? pkm.EncryptedBoxData : pkm.EncryptedPartyData; if (pkmbytes.Count() == Remote.Bot.SlotSize) { form.Bytes = pkmbytes; } else { form.Bytes = result; WinFormsUtil.Error("Size mismatch. Please report this issue on the discord server."); } } var modifiedRAM = form.Bytes; if (Remote.Bot.com is not ICommunicatorNX nx) { Remote.WriteRAM(offset, modifiedRAM); } else { if (RB_Main.Checked) { nx.WriteBytesMain(modifiedRAM, offset); } else if (RB_Absolute.Checked) { nx.WriteBytesAbsolute(modifiedRAM, offset); } else { Remote.WriteRAM(offset, modifiedRAM); } } } }
/// <summary> /// 创建实例 /// </summary> /// <typeparam name="T">实例类型</typeparam> /// <param name="classFullPath">类全路径</param> /// <returns>实例</returns> public T CreateInstance <T>(string classFullPath) where T : class { return(ReflectUtil.CreateInstance <T>(classFullPath)); }
private static ModifyResult tryModifyPKM(PKM PKM, IEnumerable <StringInstruction> Filters, IEnumerable <StringInstruction> Instructions) { if (!PKM.ChecksumValid || PKM.Species == 0) { return(ModifyResult.Invalid); } Type pkm = PKM.GetType(); PKMInfo info = new PKMInfo(PKM); foreach (var cmd in Filters) { try { if (cmd.PropertyName == PROP_LEGAL) { bool legal; if (!bool.TryParse(cmd.PropertyValue, out legal)) { return(ModifyResult.Error); } if (legal == info.Legal == cmd.Evaluator) { continue; } return(ModifyResult.Filtered); } if (!pkm.HasProperty(cmd.PropertyName)) { return(ModifyResult.Filtered); } if (ReflectUtil.GetValueEquals(PKM, cmd.PropertyName, cmd.PropertyValue) != cmd.Evaluator) { return(ModifyResult.Filtered); } } catch { Console.WriteLine($"Unable to compare {cmd.PropertyName} to {cmd.PropertyValue}."); return(ModifyResult.Filtered); } } ModifyResult result = ModifyResult.Error; foreach (var cmd in Instructions) { try { if (cmd.PropertyValue == CONST_SUGGEST) { result = setSuggestedProperty(PKM, cmd, info) ? ModifyResult.Modified : ModifyResult.Error; } else { setProperty(PKM, cmd); result = ModifyResult.Modified; } } catch { Console.WriteLine($"Unable to set {cmd.PropertyName} to {cmd.PropertyValue}."); } } return(result); }
/// <summary> /// 监听 /// </summary> public void Listen() { RpcServer.Receive(inData => { object result = null; try { var rpcDataInfo = BytesSerialization.Deserialize <RpcDataInfo>(inData); if (rpcDataInfo == null) { OnReceivingError("传过来的数据不是RpcDataInfo类型的"); } else if (string.IsNullOrWhiteSpace(rpcDataInfo.MethodFullPath)) { OnReceivingError("方法全路径不能为空"); } else { string classFullName; var methodName = ReflectUtil.GetMethodName(rpcDataInfo.MethodFullPath, out classFullName); var implClassFullName = InterfaceMapImpl.Reader(classFullName); MethodInfo method; var methodReturnValue = MethodCall.Invoke(string.Format("{0}.{1}", implClassFullName, methodName), out method, rpcDataInfo.MethodParams); // 如果方法返回是Void,则直接返回null if (method.IsMethodReturnVoid()) { return(null); } // 如果方法是异步方法,则转换为Task并等待执行结束后返回Result给客户端 else if (method.ReturnType.IsTypeTask()) { // 如果带泛型,则返回任务的Result给客户端 if (method.ReturnType.IsTypeGenericityTask()) { var resultProperty = method.ReturnType.GetProperty("Result"); result = resultProperty.GetValue(methodReturnValue); } else { var methodReturnTask = methodReturnValue as Task; methodReturnTask.Wait(); } } else { result = methodReturnValue; } } if (result == null) { return(null); } return(BytesSerialization.Serialize(result)); } catch (Exception ex) { try { OnReceivingError(ex.Message, ex); } catch { } return(null); } }); }
protected PropertyInfoEntry GetPropertyEntry(Type type, SmartCopyMap <Type, PropertyInfoEntry> map, bool isOldIocMode, bool isIocMode) { ParamChecker.AssertParamNotNull(type, "type"); PropertyInfoEntry propertyEntry = map.Get(type); if (propertyEntry != null) { return(propertyEntry); } Object writeLock = map.GetWriteLock(); lock (writeLock) { propertyEntry = map.Get(type); if (propertyEntry != null) { // Concurrent thread might have been faster return(propertyEntry); } HashMap <String, HashMap <Type, HashMap <String, MethodInfo> > > sortedMethods = new HashMap <String, HashMap <Type, HashMap <String, MethodInfo> > >(); MethodInfo[] methods = ReflectUtil.GetDeclaredMethodsInHierarchy(type); foreach (MethodInfo method in methods) { if (method.DeclaringType.Equals(typeof(Object))) { continue; } if (method.IsStatic) { continue; } try { String propName = GetPropertyNameFor(method); if (propName.Length == 0) { continue; } HashMap <Type, HashMap <String, MethodInfo> > sortedMethod = sortedMethods.Get(propName); if (sortedMethod == null) { sortedMethod = HashMap <Type, HashMap <String, MethodInfo> > .Create(1); sortedMethods.Put(propName, sortedMethod); } ParameterInfo[] parameterInfos = method.GetParameters(); Type propertyType; String prefix; if (parameterInfos.Length == 1) { propertyType = parameterInfos[0].ParameterType; prefix = "set"; } else if (parameterInfos.Length == 0) { propertyType = method.ReturnType; prefix = "get"; } else { throw new Exception("Method is not an accessor: " + method); } HashMap <String, MethodInfo> methodPerType = sortedMethod.Get(propertyType); if (methodPerType == null) { methodPerType = HashMap <String, MethodInfo> .Create(2); sortedMethod.Put(propertyType, methodPerType); } methodPerType.Put(prefix, method); } catch (Exception e) { throw RuntimeExceptionUtil.Mask(e, "Error occured while processing " + method); } } HashMap <String, HashMap <String, MethodInfo> > filteredMethods = FilterOverriddenMethods(sortedMethods, type); HashMap <String, IPropertyInfo> propertyMap = new HashMap <String, IPropertyInfo>(0.5f); foreach (MapEntry <String, HashMap <String, MethodInfo> > propertyData in filteredMethods) { String propertyName = propertyData.Key; HashMap <String, MethodInfo> propertyMethods = propertyData.Value; MethodInfo getter = propertyMethods.Get("get"); MethodInfo setter = propertyMethods.Get("set"); if (isIocMode) { if (setter == null || (!setter.IsPublic && !AnnotationUtil.IsAnnotationPresent <AutowiredAttribute>(setter, false) && !AnnotationUtil.IsAnnotationPresent <PropertyAttribute>(setter, false))) { continue; } } MethodPropertyInfo propertyInfo = new MethodPropertyInfo(type, propertyName, getter, setter); propertyMap.Put(propertyInfo.Name, propertyInfo); } Type[] interfaces = type.GetInterfaces(); List <Type> typesToSearch = new List <Type>(interfaces); typesToSearch.Add(type); foreach (Type typeToSearch in typesToSearch) { PropertyInfo[] properties = typeToSearch.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo property in properties) { if (property.GetGetMethod() != null && property.GetGetMethod().GetParameters().Length != 0) { continue; } if (property.GetSetMethod() != null && property.GetSetMethod().GetParameters().Length != 1) { continue; } MethodInfo getter = null; MethodInfo setter = null; MethodPropertyInfo propertyInfo = (MethodPropertyInfo)propertyMap.Get(property.Name); if (propertyInfo != null) { getter = propertyInfo.Getter; setter = propertyInfo.Setter; } if (getter == null) { getter = property.GetGetMethod(); } if (setter == null) { setter = property.GetSetMethod(); } if (isIocMode && setter == null) { continue; } propertyInfo = new MethodPropertyInfo(type, property.Name, getter, setter); propertyInfo.PutAnnotations(property); propertyMap.Put(propertyInfo.Name, propertyInfo); } } FieldInfo[] fields = ReflectUtil.GetDeclaredFieldsInHierarchy(type); foreach (FieldInfo field in fields) { if (field.IsStatic) { continue; } if (isOldIocMode) { if (!AnnotationUtil.IsAnnotationPresent <AutowiredAttribute>(field, false) && !AnnotationUtil.IsAnnotationPresent <PropertyAttribute>(field, false)) { continue; } } String propertyName = GetPropertyNameFor(field); IPropertyInfo existingProperty = propertyMap.Get(propertyName); if (existingProperty != null && existingProperty.IsWritable) { // Ignore field injection if the already resolved (method-)property is writable continue; } IPropertyInfo propertyInfo = new FieldPropertyInfo(type, propertyName, field); propertyMap.Put(propertyInfo.Name, propertyInfo); } propertyEntry = new PropertyInfoEntry(propertyMap); map.Put(type, propertyEntry); return(propertyEntry); } }
private void OverrideCommands() { R.Plugins.OnPluginsLoaded -= OverrideCommands; var commandsField = ReflectUtil.GetField(R.Commands.GetType(), "commands"); var rocketCommands = (List <RocketCommandManager.RegisteredRocketCommand>)commandsField.GetValue(R.Commands); var essCommands = new HashSet <string>(CommandManager.Commands.Select(c => c.Name.ToLowerInvariant())); // Used to check which commands are not "owned' by uEssentials var mappedRocketCommands = new Dictionary <string, RocketCommandManager.RegisteredRocketCommand>(); if (rocketCommands == null) { Logger.LogError("Could not override Rocket commands."); return; } rocketCommands.RemoveAll(command => { var name = command.Name.ToLowerInvariant(); var wrapper = command.Command; // Override default commands from Rocket and Unturned if (wrapper.GetType().FullName.StartsWith("Rocket.Unturned.Commands") && essCommands.Contains(name)) { Logger.LogInfo($"Overriding Unturned/Rocket command ({command.Name.ToLowerInvariant()})"); return(true); } // It will override a command from another plugin only if specified in the config.json if (Config.CommandsToOverride.Contains(name) && !(command.Command is CommandAdapter)) { var pluginName = command.Command.GetType().Assembly.GetName().Name; Logger.LogInfo($"Overriding command \"{command.Name.ToLowerInvariant()}\" from the plugin: {pluginName}"); return(true); } if (!mappedRocketCommands.ContainsKey(name)) { mappedRocketCommands.Add(name, command); } return(false); }); // Check commands that are not "owned" by uEssentials. var commandsNotOwnedByEss = CommandManager.Commands .Select(command => { var rocketCommand = mappedRocketCommands[command.Name.ToLowerInvariant()]; if (rocketCommand.Command is CommandAdapter) { return(null); } return(rocketCommand); }) .Where(command => command != null) .ToList(); if (commandsNotOwnedByEss.Count == 0) { return; } lock (Console.Out) { Logger.LogWarning("The following commands cannot be used by uEssentials because them already exists in another plugin."); commandsNotOwnedByEss.ForEach(command => { var pluginName = command.Command.GetType().Assembly.GetName().Name; Logger.LogWarning($" The command \"{command.Name}\" is owned by the plugin: {pluginName}"); }); Logger.LogWarning("If you want to use a command from uEssentials instead of another plugin, add it in \"CommandsToOverride\" in the config.json"); } }
/// <summary> /// 获取对应的尺码的数量值 /// </summary> /// <param name="sizeName"></param> /// <returns></returns> private Int16 GetSizeCount(string sizeName, BoundDetail detail) { return(Int16.Parse(ReflectUtil.GetModelValue(sizeName, detail))); }
// View Updates private IEnumerable <PKM> SearchDatabase() { // Populate Search Query Result IEnumerable <PKM> res = RawDB; // Filter for Selected Source if (!Menu_SearchBoxes.Checked) { res = res.Where(pk => pk.Identifier.StartsWith(DatabasePath + Path.DirectorySeparatorChar, StringComparison.Ordinal)); } if (!Menu_SearchDatabase.Checked) { res = res.Where(pk => !pk.Identifier.StartsWith(DatabasePath + Path.DirectorySeparatorChar, StringComparison.Ordinal)); #if DEBUG res = res.Where(pk => !pk.Identifier.StartsWith(EXTERNAL_SAV, StringComparison.Ordinal)); #endif } int format = MAXFORMAT + 1 - CB_Format.SelectedIndex; switch (CB_FormatComparator.SelectedIndex) { case 0: /* Do nothing */ break; case 1: res = res.Where(pk => pk.Format >= format); break; case 2: res = res.Where(pk => pk.Format == format); break; case 3: res = res.Where(pk => pk.Format <= format); break; } if (CB_FormatComparator.SelectedIndex != 0) { if (format <= 2) // 1-2 { res = res.Where(pk => pk.Format <= 2); } if (format >= 3 && format <= 6) // 3-6 { res = res.Where(pk => pk.Format >= 3); } if (format >= 7) // 1,3-6,7 { res = res.Where(pk => pk.Format != 2); } } switch (CB_Generation.SelectedIndex) { case 0: /* Do nothing */ break; case 1: res = res.Where(pk => pk.Gen7); break; case 2: res = res.Where(pk => pk.Gen6); break; case 3: res = res.Where(pk => pk.Gen5); break; case 4: res = res.Where(pk => pk.Gen4); break; case 5: res = res.Where(pk => pk.Gen3); break; } // Primary Searchables int species = WinFormsUtil.GetIndex(CB_Species); int ability = WinFormsUtil.GetIndex(CB_Ability); int nature = WinFormsUtil.GetIndex(CB_Nature); int item = WinFormsUtil.GetIndex(CB_HeldItem); if (species != -1) { res = res.Where(pk => pk.Species == species); } if (ability != -1) { res = res.Where(pk => pk.Ability == ability); } if (nature != -1) { res = res.Where(pk => pk.Nature == nature); } if (item != -1) { res = res.Where(pk => pk.HeldItem == item); } // Secondary Searchables int move1 = WinFormsUtil.GetIndex(CB_Move1); int move2 = WinFormsUtil.GetIndex(CB_Move2); int move3 = WinFormsUtil.GetIndex(CB_Move3); int move4 = WinFormsUtil.GetIndex(CB_Move4); if (move1 != -1) { res = res.Where(pk => pk.Moves.Contains(move1)); } if (move2 != -1) { res = res.Where(pk => pk.Moves.Contains(move2)); } if (move3 != -1) { res = res.Where(pk => pk.Moves.Contains(move3)); } if (move4 != -1) { res = res.Where(pk => pk.Moves.Contains(move4)); } int vers = WinFormsUtil.GetIndex(CB_GameOrigin); if (vers != -1) { res = res.Where(pk => pk.Version == vers); } int hptype = WinFormsUtil.GetIndex(CB_HPType); if (hptype != -1) { res = res.Where(pk => pk.HPType == hptype); } if (CHK_Shiny.CheckState == CheckState.Checked) { res = res.Where(pk => pk.IsShiny); } if (CHK_Shiny.CheckState == CheckState.Unchecked) { res = res.Where(pk => !pk.IsShiny); } if (CHK_IsEgg.CheckState == CheckState.Checked) { res = res.Where(pk => pk.IsEgg); } if (CHK_IsEgg.CheckState == CheckState.Unchecked) { res = res.Where(pk => !pk.IsEgg); } if (CHK_IsEgg.CheckState == CheckState.Checked && MT_ESV.Text != "") { res = res.Where(pk => pk.PSV == Convert.ToInt16(MT_ESV.Text)); } // Tertiary Searchables if (TB_Level.Text != "") // Level { int level = Convert.ToInt16(TB_Level.Text); if (level <= 100) { switch (CB_Level.SelectedIndex) { case 0: break; // Any case 1: // <= res = res.Where(pk => pk.Stat_Level <= level); break; case 2: // == res = res.Where(pk => pk.Stat_Level == level); break; case 3: // >= res = res.Where(pk => pk.Stat_Level >= level); break; } } } switch (CB_IV.SelectedIndex) { case 0: break; // Do nothing case 1: // <= 90 res = res.Where(pk => pk.IVs.Sum() <= 90); break; case 2: // 91-120 res = res.Where(pk => pk.IVs.Sum() > 90 && pk.IVs.Sum() <= 120); break; case 3: // 121-150 res = res.Where(pk => pk.IVs.Sum() > 120 && pk.IVs.Sum() <= 150); break; case 4: // 151-179 res = res.Where(pk => pk.IVs.Sum() > 150 && pk.IVs.Sum() < 180); break; case 5: // 180+ res = res.Where(pk => pk.IVs.Sum() >= 180); break; case 6: // == 186 res = res.Where(pk => pk.IVs.Sum() == 186); break; } switch (CB_EVTrain.SelectedIndex) { case 0: break; // Do nothing case 1: // None (0) res = res.Where(pk => pk.EVs.Sum() == 0); break; case 2: // Some (127-0) res = res.Where(pk => pk.EVs.Sum() < 128); break; case 3: // Half (128-507) res = res.Where(pk => pk.EVs.Sum() >= 128 && pk.EVs.Sum() < 508); break; case 4: // Full (508+) res = res.Where(pk => pk.EVs.Sum() >= 508); break; } slotSelected = -1; // reset the slot last viewed if (Menu_SearchLegal.Checked && !Menu_SearchIllegal.Checked) { res = res.Where(pk => new LegalityAnalysis(pk).ParsedValid); } if (!Menu_SearchLegal.Checked && Menu_SearchIllegal.Checked) { res = res.Where(pk => new LegalityAnalysis(pk).ParsedInvalid); } if (RTB_Instructions.Lines.Any(line => line.Length > 0)) { var filters = BatchEditor.StringInstruction.GetFilters(RTB_Instructions.Lines).ToArray(); BatchEditor.ScreenStrings(filters); res = res.Where(pkm => // Compare across all filters { foreach (var cmd in filters) { if (cmd.PropertyName == nameof(PKM.Identifier) + "Contains") { return(pkm.Identifier.Contains(cmd.PropertyValue)); } if (!pkm.GetType().HasPropertyAll(cmd.PropertyName)) { return(false); } try { if (ReflectUtil.IsValueEqual(pkm, cmd.PropertyName, cmd.PropertyValue) == cmd.Evaluator) { continue; } } catch { Debug.WriteLine($"Unable to compare {cmd.PropertyName} to {cmd.PropertyValue}."); } return(false); } return(true); }); } if (Menu_SearchClones.Checked) { res = res.GroupBy(Hash).Where(group => group.Count() > 1).SelectMany(z => z); } return(res); }
public static object GetMemberValueByPath(this object obj, string content, bool returndisplayifenum = false) { content = content.Trim(); if (string.IsNullOrEmpty(content)) { return(null); } string[] splitContents = content.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (splitContents == null || splitContents.Length <= 0) { return(null); } Object currentobj = obj; if (currentobj == null) { return(null); } Type currentype = currentobj.GetType(); for (int i = 0; i < splitContents.Length; i++) { PropertyInfo PI = currentype.GetProperty(splitContents[i]); if (PI != null) { currentobj = PI.GetValue(currentobj, null); if (currentobj == null) { return(null); } currentype = currentobj.GetType(); } FieldInfo FI = null; if (PI == null) { FI = currentype.GetField(splitContents[i]); if (FI != null) { currentobj = FI.GetValue(currentobj); if (currentobj == null) { return(null); } currentype = currentobj.GetType(); } } if (FI == null && PI == null) { return(null); } if (i == splitContents.Length - 1) { if (returndisplayifenum && currentobj is Enum) { string disp = null; if (OnEnumGetDisplayName != null) { disp = OnEnumGetDisplayName(currentobj); } if (disp != null) { return(disp); } var desc = ReflectUtil.GetEnumDescription(currentobj); if (desc != null) { return(desc); } } return(currentobj); } } return(null); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: protected Class resolveClass(java.io.ObjectStreamClass desc) throws java.io.IOException, ClassNotFoundException protected internal virtual Type resolveClass(ObjectStreamClass desc) { return(ReflectUtil.loadClass(desc.Name)); }
/// <summary> /// 创建实例对象 /// </summary> /// <param name="classFullPath">类全路径</param> /// <returns>实例</returns> private object CreateInstanceObj(string classFullPath) { return(AutofacTool.Resolve(ReflectUtil.GetClassType(classFullPath))); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @SuppressWarnings("unchecked") public GenericManagerFactory(String classname) public GenericManagerFactory(string classname) { managerImplementation = (Type)ReflectUtil.loadClass(classname); }
/// <summary> /// Produces an instance of the given single-method interface which redirects /// its calls to the given method handle. /// <para> /// A single-method interface is an interface which declares a uniquely named method. /// When determining the uniquely named method of a single-method interface, /// the public {@code Object} methods ({@code toString}, {@code equals}, {@code hashCode}) /// are disregarded. For example, <seealso cref="java.util.Comparator"/> is a single-method interface, /// even though it re-declares the {@code Object.equals} method. /// </para> /// <para> /// The interface must be public. No additional access checks are performed. /// </para> /// <para> /// The resulting instance of the required type will respond to /// invocation of the type's uniquely named method by calling /// the given target on the incoming arguments, /// and returning or throwing whatever the target /// returns or throws. The invocation will be as if by /// {@code target.invoke}. /// The target's type will be checked before the /// instance is created, as if by a call to {@code asType}, /// which may result in a {@code WrongMethodTypeException}. /// </para> /// <para> /// The uniquely named method is allowed to be multiply declared, /// with distinct type descriptors. (E.g., it can be overloaded, /// or can possess bridge methods.) All such declarations are /// connected directly to the target method handle. /// Argument and return types are adjusted by {@code asType} /// for each individual declaration. /// </para> /// <para> /// The wrapper instance will implement the requested interface /// and its super-types, but no other single-method interfaces. /// This means that the instance will not unexpectedly /// pass an {@code instanceof} test for any unrequested type. /// <p style="font-size:smaller;"> /// <em>Implementation Note:</em> /// Therefore, each instance must implement a unique single-method interface. /// Implementations may not bundle together /// multiple single-method interfaces onto single implementation classes /// in the style of <seealso cref="java.awt.AWTEventMulticaster"/>. /// </para> /// <para> /// The method handle may throw an <em>undeclared exception</em>, /// which means any checked exception (or other checked throwable) /// not declared by the requested type's single abstract method. /// If this happens, the throwable will be wrapped in an instance of /// <seealso cref="java.lang.reflect.UndeclaredThrowableException UndeclaredThrowableException"/> /// and thrown in that wrapped form. /// </para> /// <para> /// Like <seealso cref="java.lang.Integer#valueOf Integer.valueOf"/>, /// {@code asInterfaceInstance} is a factory method whose results are defined /// by their behavior. /// It is not guaranteed to return a new instance for every call. /// </para> /// <para> /// Because of the possibility of <seealso cref="java.lang.reflect.Method#isBridge bridge methods"/> /// and other corner cases, the interface may also have several abstract methods /// with the same name but having distinct descriptors (types of returns and parameters). /// In this case, all the methods are bound in common to the one given target. /// The type check and effective {@code asType} conversion is applied to each /// method type descriptor, and all abstract methods are bound to the target in common. /// Beyond this type check, no further checks are made to determine that the /// abstract methods are related in any way. /// </para> /// <para> /// Future versions of this API may accept additional types, /// such as abstract classes with single abstract methods. /// Future versions of this API may also equip wrapper instances /// with one or more additional public "marker" interfaces. /// </para> /// <para> /// If a security manager is installed, this method is caller sensitive. /// During any invocation of the target method handle via the returned wrapper, /// the original creator of the wrapper (the caller) will be visible /// to context checks requested by the security manager. /// /// </para> /// </summary> /// @param <T> the desired type of the wrapper, a single-method interface </param> /// <param name="intfc"> a class object representing {@code T} </param> /// <param name="target"> the method handle to invoke from the wrapper </param> /// <returns> a correctly-typed wrapper for the given target </returns> /// <exception cref="NullPointerException"> if either argument is null </exception> /// <exception cref="IllegalArgumentException"> if the {@code intfc} is not a /// valid argument to this method </exception> /// <exception cref="WrongMethodTypeException"> if the target cannot /// be converted to the type required by the requested interface </exception> // Other notes to implementors: // <p> // No stable mapping is promised between the single-method interface and // the implementation class C. Over time, several implementation // classes might be used for the same type. // <p> // If the implementation is able // to prove that a wrapper of the required type // has already been created for a given // method handle, or for another method handle with the // same behavior, the implementation may return that wrapper in place of // a new wrapper. // <p> // This method is designed to apply to common use cases // where a single method handle must interoperate with // an interface that implements a function-like // API. Additional variations, such as single-abstract-method classes with // private constructors, or interfaces with multiple but related // entry points, must be covered by hand-written or automatically // generated adapter classes. // //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @CallerSensitive public static <T> T asInterfaceInstance(final Class intfc, final MethodHandle target) //JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET: public static T asInterfaceInstance <T>(Class intfc, MethodHandle target) { if (!intfc.Interface || !Modifier.IsPublic(intfc.Modifiers)) { throw newIllegalArgumentException("not a public interface", intfc.Name); } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final MethodHandle mh; MethodHandle mh; if (System.SecurityManager != null) { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Class caller = sun.reflect.Reflection.getCallerClass(); Class caller = Reflection.CallerClass; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final ClassLoader ccl = caller != null ? caller.getClassLoader() : null; ClassLoader ccl = caller != null ? caller.ClassLoader : null; ReflectUtil.checkProxyPackageAccess(ccl, intfc); mh = ccl != null?BindCaller(target, caller) : target; } else { mh = target; } ClassLoader proxyLoader = intfc.ClassLoader; if (proxyLoader == null) { ClassLoader cl = Thread.CurrentThread.ContextClassLoader; // avoid use of BCP proxyLoader = cl != null ? cl : ClassLoader.SystemClassLoader; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Method[] methods = getSingleNameMethods(intfc); Method[] methods = GetSingleNameMethods(intfc); if (methods == null) { throw newIllegalArgumentException("not a single-method interface", intfc.Name); } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final MethodHandle[] vaTargets = new MethodHandle[methods.length]; MethodHandle[] vaTargets = new MethodHandle[methods.Length]; for (int i = 0; i < methods.Length; i++) { Method sm = methods[i]; MethodType smMT = MethodType.MethodType(sm.ReturnType, sm.ParameterTypes); MethodHandle checkTarget = mh.AsType(smMT); // make throw WMT checkTarget = checkTarget.AsType(checkTarget.Type().ChangeReturnType(typeof(Object))); vaTargets[i] = checkTarget.AsSpreader(typeof(Object[]), smMT.ParameterCount()); } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final InvocationHandler ih = new InvocationHandler() InvocationHandler ih = new InvocationHandlerAnonymousInnerClassHelper(intfc, target, methods, vaTargets); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final Object proxy; Object proxy; if (System.SecurityManager != null) { // sun.invoke.WrapperInstance is a restricted interface not accessible // by any non-null class loader. //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final ClassLoader loader = proxyLoader; ClassLoader loader = proxyLoader; proxy = AccessController.doPrivileged(new PrivilegedActionAnonymousInnerClassHelper(intfc, ih, loader)); } else { proxy = Proxy.NewProxyInstance(proxyLoader, new Class[] { intfc, typeof(WrapperInstance) }, ih); } return(intfc.Cast(proxy)); }
/// <summary> /// Get ribbon names of a pkm /// </summary> /// <param name="pk">pokemon</param> /// <returns></returns> private static IEnumerable <string> GetRibbonNames(PKM pk) => ReflectUtil.GetPropertiesStartWithPrefix(pk.GetType(), "Ribbon").Distinct();
public static void TransferTo(this object source, object target, string[] excludingorincluding = null, bool listisexcluding = true, bool crossNullvalue = true) { ReflectUtil.SetSameClassValue(source, target, variants: excludingorincluding, listisdisallow: listisexcluding, crossnullvalue: crossNullvalue); }
private bool CommonErrorHandling2(PKM pk) { string hp = pk.IV_HP.ToString(); string atk = pk.IV_ATK.ToString(); string def = pk.IV_DEF.ToString(); string spa = pk.IV_SPA.ToString(); string spd = pk.IV_SPD.ToString(); string spe = pk.IV_SPE.ToString(); bool HTworkaround = false; LegalityAnalysis la = new LegalityAnalysis(pk); var report = la.Report(false); var updatedReport = report; if (report.Contains("Ability mismatch for encounter")) { pk.RefreshAbility(pk.AbilityNumber < 6 ? pk.AbilityNumber >> 1 : 0); } if (report.Contains("Invalid Met Location, expected Transporter.")) { pk.Met_Location = 30001; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("Can't have ball for encounter type.")) { if (pk.B2W2) { pk.Ball = 25; //Dream Ball LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } else { pk.Ball = 0; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } } if (report.Contains("Non japanese Mew from Faraway Island. Unreleased event.")) { pk.Language = 1; pk.FatefulEncounter = true; pk.Nickname = PKX.GetSpeciesNameGeneration(pk.Species, pk.Language, 3); pk.PID = PKX.GetRandomPID(pk.Species, pk.Gender, pk.Version, pk.Nature, pk.Format, (uint)(pk.AbilityNumber * 0x10001)); LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("PID should be equal to EC!")) { pk.EncryptionConstant = pk.PID; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("PID should be equal to EC [with top bit flipped]!")) { pk.PID = PKX.GetRandomPID(pk.Species, pk.Gender, pk.Version, pk.Nature, pk.Format, (uint)(pk.AbilityNumber * 0x10001)); if (pk.IsShiny) { pk.SetShinyPID(); } LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("PID-Gender mismatch.")) { if (pk.Gender == 0) { pk.Gender = 1; } else { pk.Gender = 0; } LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("Missing Ribbons: National")) { ReflectUtil.SetValue(pk, "RibbonNational", -1); LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("Invalid Ribbons: National")) { ReflectUtil.SetValue(pk, "RibbonNational", 0); LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("OT Name too long.")) { pk.OT_Name = "ARCH"; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("GeoLocation Memory: Memories should be present.")) { pk.Geo1_Country = 1; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("Can't have ball for encounter type.")) { pk.Ball = 4; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("Can't have any OT Memory.")) { pk.OT_Memory = 0; pk.OT_Intensity = 0; pk.OT_Feeling = 0; pk.OT_TextVar = 0; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("OT Memory: Should be index 0.")) { pk.OT_Memory = 0; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("OT Memory: Intensity should be index 0.")) { pk.OT_Intensity = 0; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("OT Memory: Feeling should be index 0.")) { pk.OT_Feeling = 0; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("OT Memory: TextVar should be index 0.")) { pk.OT_TextVar = 0; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("Form cannot exist outside of a battle.")) { pk.AltForm = 0; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("Special ingame Fateful Encounter flag missing")) { pk.FatefulEncounter = true; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Contains("Fateful Encounter should not be checked.")) { pk.FatefulEncounter = false; LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; } if (report.Equals("Invalid: Encounter Type PID mismatch.")) { //return true; if (pk.Version == (int)GameVersion.CXD) { pk = setPIDSID(pk, pk.IsShiny, true); } else { pk = setPIDSID(pk, pk.IsShiny); } if (new LegalityAnalysis(pk).Valid) { return(false); } if (pk.HT_HP) { HTworkaround = true; } LegalityAnalysis recheckLA = new LegalityAnalysis(pk); updatedReport = recheckLA.Report(false); report = updatedReport; if (report.Equals("Invalid: Encounter Type PID mismatch.")) { return(true); } else if (report.Contains("PID-Gender mismatch.")) { if (pk.Gender == 0) { pk.Gender = 1; } else { pk.Gender = 0; } LegalityAnalysis recheckLA2 = new LegalityAnalysis(pk); updatedReport = recheckLA2.Report(false); report = updatedReport; if (new LegalityAnalysis(pk).Valid) { return(false); } } } return(false); }
public static void TransferValuesTo(this object source, object target, params string[] including) { ReflectUtil.SetSameClassValue(source, target, variants: including, listisdisallow: false); }
private void RegisterAllWhere(Assembly asm, Predicate <Type> filter) { Predicate <Type> defaultPredicate = type => { return(typeof(ICommand).IsAssignableFrom(type) && !type.IsAbstract && type != typeof(MethodCommand)); }; var commonInstPoll = EssCore.Instance.CommonInstancePool; /* * Register classes */ ( from type in asm.GetTypes() where defaultPredicate(type) where filter(type) select(ICommand) commonInstPoll.GetOrCreate(type) ).ForEach(Register); /* * Register methods */ Func <Type, object, MethodInfo, Delegate> createDelegate = (type, obj, method) => { return(obj == null ? Delegate.CreateDelegate(type, method) : Delegate.CreateDelegate(type, obj, method.Name)); }; foreach (var type in asm.GetTypes().Where(filter.Invoke)) { foreach (var method in type.GetMethods((BindingFlags)0x3C)) { if (ReflectUtil.GetAttributeFrom <CommandInfo>(method) == null) { continue; } var inst = method.IsStatic ? null : EssCore.Instance.CommonInstancePool.GetOrCreate(type); var paramz = method.GetParameters(); if (method.ReturnType != typeof(CommandResult)) { UEssentials.Logger.LogError($"Invalid method signature in '{method}'. " + "Expected 'CommandResult methodName(ICommandSource, ICommandArgs)'"); continue; } if (paramz.Length == 2 && paramz[0].ParameterType == typeof(ICommandSource) && paramz[1].ParameterType == typeof(ICommandArgs)) { Register((Func <ICommandSource, ICommandArgs, CommandResult>)createDelegate( typeof(Func <ICommandSource, ICommandArgs, CommandResult>), inst, method)); } else if (paramz.Length == 3 && paramz[0].ParameterType == typeof(ICommandSource) && paramz[1].ParameterType == typeof(ICommandArgs) && paramz[2].ParameterType == typeof(ICommand)) { Register((Func <ICommandSource, ICommandArgs, ICommand, CommandResult>)createDelegate( typeof(Func <ICommandSource, ICommandArgs, ICommand, CommandResult>), inst, method)); } else { UEssentials.Logger.LogError($"Invalid method signature in '{method}'. " + "Expected 'CommandResult methodName(ICommandSource, ICommandArgs)'"); } } } }
public static bool IsNumericType(this object source) { return(ReflectUtil.IsNumericType(source)); }
/// <summary> /// 创建实例 /// </summary> /// <param name="classFullPath">类全路径</param> /// <returns>实例</returns> public object CreateInstance(string classFullPath) { return(ReflectUtil.CreateInstance(classFullPath)); }
public static bool IsEnum(this object source) { return(ReflectUtil.IsEnum(source)); }
// View Updates private void B_Search_Click(object sender, EventArgs e) { // Populate Search Query Result IEnumerable <PKM> res = RawDB; int format = MAXFORMAT + 1 - CB_Format.SelectedIndex; switch (CB_FormatComparator.SelectedIndex) { case 0: /* Do nothing */ break; case 1: res = res.Where(pk => pk.Format >= format); break; case 2: res = res.Where(pk => pk.Format == format); break; case 3: res = res.Where(pk => pk.Format <= format); break; } if (CB_FormatComparator.SelectedIndex != 0) { if (format <= 2) // 1-2 { res = res.Where(pk => pk.Format <= 2); } if (format >= 3 && format <= 6) // 3-6 { res = res.Where(pk => pk.Format >= 3); } if (format >= 7) // 1,3-6,7 { res = res.Where(pk => pk.Format != 2); } } switch (CB_Generation.SelectedIndex) { case 0: /* Do nothing */ break; case 1: res = res.Where(pk => pk.Gen7); break; case 2: res = res.Where(pk => pk.Gen6); break; case 3: res = res.Where(pk => pk.Gen5); break; case 4: res = res.Where(pk => pk.Gen4); break; case 5: res = res.Where(pk => pk.Gen3); break; } // Primary Searchables int species = WinFormsUtil.getIndex(CB_Species); int ability = WinFormsUtil.getIndex(CB_Ability); int nature = WinFormsUtil.getIndex(CB_Nature); int item = WinFormsUtil.getIndex(CB_HeldItem); if (species != -1) { res = res.Where(pk => pk.Species == species); } if (ability != -1) { res = res.Where(pk => pk.Ability == ability); } if (nature != -1) { res = res.Where(pk => pk.Nature == nature); } if (item != -1) { res = res.Where(pk => pk.HeldItem == item); } // Secondary Searchables int move1 = WinFormsUtil.getIndex(CB_Move1); int move2 = WinFormsUtil.getIndex(CB_Move2); int move3 = WinFormsUtil.getIndex(CB_Move3); int move4 = WinFormsUtil.getIndex(CB_Move4); if (move1 != -1) { res = res.Where(pk => pk.Moves.Contains(move1)); } if (move2 != -1) { res = res.Where(pk => pk.Moves.Contains(move2)); } if (move3 != -1) { res = res.Where(pk => pk.Moves.Contains(move3)); } if (move4 != -1) { res = res.Where(pk => pk.Moves.Contains(move4)); } int vers = WinFormsUtil.getIndex(CB_GameOrigin); if (vers != -1) { res = res.Where(pk => pk.Version == vers); } int hptype = WinFormsUtil.getIndex(CB_HPType); if (hptype != -1) { res = res.Where(pk => pk.HPType == hptype); } if (CHK_Shiny.CheckState == CheckState.Checked) { res = res.Where(pk => pk.IsShiny); } if (CHK_Shiny.CheckState == CheckState.Unchecked) { res = res.Where(pk => !pk.IsShiny); } if (CHK_IsEgg.CheckState == CheckState.Checked) { res = res.Where(pk => pk.IsEgg); } if (CHK_IsEgg.CheckState == CheckState.Unchecked) { res = res.Where(pk => !pk.IsEgg); } if (CHK_IsEgg.CheckState == CheckState.Checked && MT_ESV.Text != "") { res = res.Where(pk => pk.PSV == Convert.ToInt16(MT_ESV.Text)); } // Tertiary Searchables if (TB_Level.Text != "") // Level { int level = Convert.ToInt16(TB_Level.Text); if (level <= 100) { switch (CB_Level.SelectedIndex) { case 0: break; // Any case 1: // <= res = res.Where(pk => pk.Stat_Level <= level); break; case 2: // == res = res.Where(pk => pk.Stat_Level == level); break; case 3: // >= res = res.Where(pk => pk.Stat_Level >= level); break; } } } switch (CB_IV.SelectedIndex) { case 0: break; // Do nothing case 1: // <= 90 res = res.Where(pk => pk.IVs.Sum() <= 90); break; case 2: // 91-120 res = res.Where(pk => pk.IVs.Sum() > 90 && pk.IVs.Sum() <= 120); break; case 3: // 121-150 res = res.Where(pk => pk.IVs.Sum() > 120 && pk.IVs.Sum() <= 150); break; case 4: // 151-179 res = res.Where(pk => pk.IVs.Sum() > 150 && pk.IVs.Sum() < 180); break; case 5: // 180+ res = res.Where(pk => pk.IVs.Sum() >= 180); break; case 6: // == 186 res = res.Where(pk => pk.IVs.Sum() == 186); break; } switch (CB_EVTrain.SelectedIndex) { case 0: break; // Do nothing case 1: // None (0) res = res.Where(pk => pk.EVs.Sum() == 0); break; case 2: // Some (127-0) res = res.Where(pk => pk.EVs.Sum() < 128); break; case 3: // Half (128-507) res = res.Where(pk => pk.EVs.Sum() >= 128 && pk.EVs.Sum() < 508); break; case 4: // Full (508+) res = res.Where(pk => pk.EVs.Sum() >= 508); break; } // Filter for Selected Source if (!Menu_SearchBoxes.Checked) { res = res.Where(pk => pk.Identifier.StartsWith(DatabasePath + Path.DirectorySeparatorChar, StringComparison.Ordinal)); } if (!Menu_SearchDatabase.Checked) { res = res.Where(pk => !pk.Identifier.StartsWith(DatabasePath + Path.DirectorySeparatorChar, StringComparison.Ordinal)); } slotSelected = -1; // reset the slot last viewed if (Menu_SearchLegal.Checked && !Menu_SearchIllegal.Checked) // Legal Only { res = res.Where(pk => pk.GenNumber >= 6 && new LegalityAnalysis(pk).Valid); } if (!Menu_SearchLegal.Checked && Menu_SearchIllegal.Checked) // Illegal Only { res = res.Where(pk => pk.GenNumber >= 6 && !new LegalityAnalysis(pk).Valid); } if (RTB_Instructions.Lines.Any(line => line.Length > 0)) { var raw = RTB_Instructions.Lines .Where(line => !string.IsNullOrWhiteSpace(line)) .Where(line => new[] { '!', '=' }.Contains(line[0])); var filters = (from line in raw let eval = line[0] == '=' let split = line.Substring(1).Split('=') where split.Length == 2 && !string.IsNullOrWhiteSpace(split[0]) select new BatchEditor.StringInstruction { PropertyName = split[0], PropertyValue = split[1], Evaluator = eval }).ToArray(); BatchEditor.screenStrings(filters); res = res.Where(pkm => // Compare across all filters { foreach (var cmd in filters) { if (!pkm.GetType().HasPropertyAll(cmd.PropertyName)) { return(false); } try { if (ReflectUtil.GetValueEquals(pkm, cmd.PropertyName, cmd.PropertyValue) == cmd.Evaluator) { continue; } } catch { Console.WriteLine($"Unable to compare {cmd.PropertyName} to {cmd.PropertyValue}."); } return(false); } return(true); }); } if (Menu_SearchClones.Checked) { var r = res.ToArray(); var hashes = r.Select(hash).ToArray(); res = r.Where((t, i) => hashes.Count(x => x == hashes[i]) > 1).OrderBy(hash); } var results = res.ToArray(); if (results.Length == 0) { if (!Menu_SearchBoxes.Checked && !Menu_SearchDatabase.Checked) { WinFormsUtil.Alert("No data source to search!", "No results found!"); } else { WinFormsUtil.Alert("No results found!"); } } setResults(new List <PKM>(results)); // updates Count Label as well. System.Media.SystemSounds.Asterisk.Play(); }
public static bool IsArray(this object source) { return(ReflectUtil.IsArray(source)); }
public static void set(object arrayObj, int index, object value) { if (arrayObj == null) { throw new java.lang.NullPointerException(); } Type type = arrayObj.GetType(); if (ReflectUtil.IsVector(type) && ClassLoaderWrapper.GetWrapperFromType(type.GetElementType()).IsPrimitive) { java.lang.Boolean booleanValue = value as java.lang.Boolean; if (booleanValue != null) { setBoolean(arrayObj, index, booleanValue.booleanValue()); return; } java.lang.Byte byteValue = value as java.lang.Byte; if (byteValue != null) { setByte(arrayObj, index, byteValue.byteValue()); return; } java.lang.Character charValue = value as java.lang.Character; if (charValue != null) { setChar(arrayObj, index, charValue.charValue()); return; } java.lang.Short shortValue = value as java.lang.Short; if (shortValue != null) { setShort(arrayObj, index, shortValue.shortValue()); return; } java.lang.Integer intValue = value as java.lang.Integer; if (intValue != null) { setInt(arrayObj, index, intValue.intValue()); return; } java.lang.Float floatValue = value as java.lang.Float; if (floatValue != null) { setFloat(arrayObj, index, floatValue.floatValue()); return; } java.lang.Long longValue = value as java.lang.Long; if (longValue != null) { setLong(arrayObj, index, longValue.longValue()); return; } java.lang.Double doubleValue = value as java.lang.Double; if (doubleValue != null) { setDouble(arrayObj, index, doubleValue.doubleValue()); return; } } try { CheckArray(arrayObj).SetValue(value, index); } catch (InvalidCastException) { throw new java.lang.IllegalArgumentException("argument type mismatch"); } catch (IndexOutOfRangeException) { throw new java.lang.ArrayIndexOutOfBoundsException(); } }
public static bool IsDictionary(this object source) { return(ReflectUtil.IsDictionary(source)); }
protected PropertyInstance ImplementPotentialPrimitive(PropertyInstance property, Member member) { if (member == null) { return(ImplementProperty(property, delegate(IMethodVisitor mg) { mg.PushNull(); mg.ReturnValue(); }, delegate(IMethodVisitor mg) { Label l_isNull = mg.NewLabel(); mg.LoadArg(0); mg.IfNull(l_isNull); mg.ThrowException(typeof(NotSupportedException), "Property is read-only"); mg.Mark(l_isNull); mg.ReturnValue(); })); } PropertyInstance p_conversionHelper = GetConversionHelperPI(this); MethodInstance m_convertValueToType = new MethodInstance(ReflectUtil.GetDeclaredMethod(false, typeof(IConversionHelper), typeof(Object), "ConvertValueToType", typeof(Type), typeof(Object))); Type type = member.RealType; FieldInstance field = ImplementField(new FieldInstance(FieldAttributes.Public, "f_" + property.Name, type)); return(ImplementProperty(property, delegate(IMethodVisitor mg) { if (field.Type.Type.IsPrimitive) { Label l_isNull = mg.NewLabel(); LocalVariableInfo loc_value = mg.NewLocal(field.Type); mg.GetThisField(field); mg.StoreLocal(loc_value); mg.LoadLocal(loc_value); mg.IfZCmp(field.Type, CompareOperator.EQ, l_isNull); mg.LoadLocal(loc_value); mg.Box(type); mg.ReturnValue(); mg.Mark(l_isNull); mg.PushNull(); } else if (field.Type.Type.IsValueType) { Type pType = field.Type.Type; mg.GetThisField(field); MethodInfo m_hasValue = pType.GetMethod("get_HasValue"); if (m_hasValue != null) { LocalVariableInfo loc_value = mg.NewLocal(pType); mg.StoreLocal(loc_value); mg.LoadLocal(loc_value); MethodInfo m_getValue = pType.GetMethod("get_Value"); LocalVariableInfo loc_realValue = mg.NewLocal(m_getValue.ReturnType); Label l_hasNoValue = mg.NewLabel(); mg.InvokeOnExactOwner(m_hasValue); mg.IfZCmp(CompareOperator.EQ, l_hasNoValue); mg.LoadLocal(loc_value); mg.InvokeOnExactOwner(m_getValue); mg.StoreLocal(loc_realValue); mg.LoadLocal(loc_realValue); mg.IfZCmp(CompareOperator.EQ, l_hasNoValue); mg.LoadLocal(loc_realValue); mg.ValueOf(m_getValue.ReturnType); mg.ReturnValue(); mg.Mark(l_hasNoValue); mg.PushNullOrZero(mg.Method.ReturnType); } else { mg.Box(pType); } } else { mg.GetThisField(field); } mg.ReturnValue(); }, delegate(IMethodVisitor mg) { mg.PutThisField(field, delegate(IMethodVisitor mg2) { Label l_isNull = mg2.NewLabel(); Label l_finish = mg2.NewLabel(); mg2.LoadArg(0); mg2.IfNull(l_isNull); mg.CallThisGetter(p_conversionHelper); mg.Push(type); mg.LoadArg(0); mg.InvokeVirtual(m_convertValueToType); mg2.Unbox(type); mg2.GoTo(l_finish); mg2.Mark(l_isNull); mg2.PushNullOrZero(field.Type); mg2.Mark(l_finish); }); mg.ReturnValue(); })); }
protected internal virtual void CreateMethodBindings() { StringFunctionMap["IsNullOrEmpty"] = ReflectUtil.GetMethod(typeof(string), "IsNullOrEmpty", new Type[] { typeof(string) }); }
// View Updates private void B_Search_Click(object sender, EventArgs e) { // Populate Search Query Result IEnumerable <MysteryGift> res = RawDB; int format = MAXFORMAT + 1 - CB_Format.SelectedIndex; switch (CB_FormatComparator.SelectedIndex) { case 0: /* Do nothing */ break; case 1: res = res.Where(mg => mg.Format >= format); break; case 2: res = res.Where(mg => mg.Format == format); break; case 3: res = res.Where(mg => mg.Format <= format); break; } // Primary Searchables int species = WinFormsUtil.getIndex(CB_Species); int item = WinFormsUtil.getIndex(CB_HeldItem); if (species != -1) { res = res.Where(pk => pk.Species == species); } if (item != -1) { res = res.Where(pk => pk.HeldItem == item); } // Secondary Searchables int move1 = WinFormsUtil.getIndex(CB_Move1); int move2 = WinFormsUtil.getIndex(CB_Move2); int move3 = WinFormsUtil.getIndex(CB_Move3); int move4 = WinFormsUtil.getIndex(CB_Move4); if (move1 != -1) { res = res.Where(pk => pk.Moves.Contains(move1)); } if (move2 != -1) { res = res.Where(pk => pk.Moves.Contains(move2)); } if (move3 != -1) { res = res.Where(pk => pk.Moves.Contains(move3)); } if (move4 != -1) { res = res.Where(pk => pk.Moves.Contains(move4)); } if (CHK_Shiny.CheckState == CheckState.Checked) { res = res.Where(pk => pk.IsShiny); } if (CHK_Shiny.CheckState == CheckState.Unchecked) { res = res.Where(pk => !pk.IsShiny); } if (CHK_IsEgg.CheckState == CheckState.Checked) { res = res.Where(pk => pk.IsEgg); } if (CHK_IsEgg.CheckState == CheckState.Unchecked) { res = res.Where(pk => !pk.IsEgg); } slotSelected = -1; // reset the slot last viewed if (RTB_Instructions.Lines.Any(line => line.Length > 0)) { var raw = RTB_Instructions.Lines .Where(line => !string.IsNullOrWhiteSpace(line)) .Where(line => new[] { '!', '=' }.Contains(line[0])); var filters = (from line in raw let eval = line[0] == '=' let split = line.Substring(1).Split('=') where split.Length == 2 && !string.IsNullOrWhiteSpace(split[0]) select new BatchEditor.StringInstruction { PropertyName = split[0], PropertyValue = split[1], Evaluator = eval }).ToArray(); if (filters.Any(z => string.IsNullOrWhiteSpace(z.PropertyValue))) { WinFormsUtil.Error("Empty Filter Value detected."); return; } res = res.Where(gift => // Compare across all filters { foreach (var cmd in filters) { if (!gift.GetType().HasPropertyAll(cmd.PropertyName)) { return(false); } try { if (ReflectUtil.GetValueEquals(gift, cmd.PropertyName, cmd.PropertyValue) == cmd.Evaluator) { continue; } } catch { Console.WriteLine($"Unable to compare {cmd.PropertyName} to {cmd.PropertyValue}."); } return(false); } return(true); }); } var results = res.ToArray(); if (results.Length == 0) { WinFormsUtil.Alert("No results found!"); } setResults(new List <MysteryGift>(results)); // updates Count Label as well. System.Media.SystemSounds.Asterisk.Play(); }
private static IEnumerable <string> DumpStrings(Type t) { var props = ReflectUtil.GetPropertiesStartWithPrefix(t, string.Empty); return(props.Select(p => $"{p}{TranslationSplitter}{ReflectUtil.GetValue(t, p)}")); }