public static string ContactPageIdentifier(this HtmlHelper helper) { var filter = new TypeFilter(typeof(ContactFormPage)); var page = Find.StartPage.GetChildren(filter).FirstOrDefault(); return page != null ? page.Name : string.Empty; }
public static void Run() { //FirstMember TypeFilter filt = new TypeFilter(DbElementTypeInstance.NOZZLE); DbElement nozz1 = filt.FirstMember(Example.Instance.mEqui); DbElementType type = nozz1.GetElementType(); //NextMember DbElement nozz2 = filt.Next(nozz1); //NextMember DbElement[] members = filt.Members(Example.Instance.mEqui); //parent TypeFilter filt2 = new TypeFilter(DbElementTypeInstance.SITE); DbElement site = filt2.Parent(nozz1); type = site.GetElementType(); //Valid AndFilter andFilt4 = new AndFilter(); andFilt4.Add(new TypeFilter(DbElementTypeInstance.EQUIPMENT)); andFilt4.Add(new TrueFilter()); bool valid = andFilt4.Valid(Example.Instance.mEqui); // attribute true AttributeTrueFilter filt1 = new AttributeTrueFilter(DbAttributeInstance.ISNAME); //should be true for named element bool named = filt1.Valid(Example.Instance.mEqui); //for first member it is also true named = filt1.Valid(Example.Instance.mEqui.FirstMember()); //Element type at or below BelowOrAtType filt3 = new BelowOrAtType(DbElementTypeInstance.EQUIPMENT); bool below = filt3.ScanBelow(Example.Instance.mEqui); }
static Module() { __Filters _fltObj; _fltObj = new __Filters(); FilterTypeName = new TypeFilter(_fltObj.FilterTypeName); FilterTypeNameIgnoreCase = new TypeFilter(_fltObj.FilterTypeNameIgnoreCase); }
public static Type[] FindInterfaces(this Type type, TypeFilter filter, object filterCriteria) { if (filter == null) { throw new ArgumentNullException("filter"); } var interfaces = type.GetInterfaces(); var count = 0; for (var i = 0; i < interfaces.Length; i++) { if (!filter(interfaces[i], filterCriteria)) { interfaces[i] = null; } else { count++; } } if (count == interfaces.Length) { return interfaces; } var array = new Type[count]; count = 0; foreach (var t in interfaces.Where(t => t != null)) { array[count++] = t; } return array; }
public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) { Type[] types = this.GetTypes(); int num = 0; for (int i = 0; i < types.Length; i++) { if ((filter != null) && !filter(types[i], filterCriteria)) { types[i] = null; } else { num++; } } if (num == types.Length) { return types; } Type[] typeArray2 = new Type[num]; num = 0; for (int j = 0; j < types.Length; j++) { if (types[j] != null) { typeArray2[num++] = types[j]; } } return typeArray2; }
public virtual Type[] FindInterfaces(TypeFilter filter, object filterCriteria) { if (filter == null) { throw new ArgumentNullException("filter"); } Type[] interfaces = this.GetInterfaces(); int num = 0; for (int i = 0; i < interfaces.Length; i++) { if (!filter(interfaces[i], filterCriteria)) { interfaces[i] = null; } else { num++; } } if (num == interfaces.Length) { return interfaces; } Type[] typeArray2 = new Type[num]; num = 0; for (int j = 0; j < interfaces.Length; j++) { if (interfaces[j] != null) { typeArray2[num++] = interfaces[j]; } } return typeArray2; }
public static void Run() { // Set up a navigator which looks at sites/pipes/Nozzles/Tee only TypeFilter filt = new TypeFilter(); filt.Add(DbElementTypeInstance.SITE); filt.Add(DbElementTypeInstance.PIPE); filt.Add(DbElementTypeInstance.NOZZLE); filt.Add(DbElementTypeInstance.TEE); CompoundFilter filt2 = new CompoundFilter(); filt2.AddShow(filt); ElementTreeNavigator navi = new ElementTreeNavigator(DbElement.GetElement("/*"), filt2); // Test FirstMember DbElement site = navi.FirstMemberInScan(Example.Instance.mWorld); DbElement nozz = navi.FirstMemberInScan(Example.Instance.mZone); nozz = navi.FirstMemberInScan(Example.Instance.mEqui); DbElement ele = navi.FirstMemberInScan(nozz); // Next DbElement zone = site.FirstMember(); DbElement next = navi.NextInScan(zone); // parent DbElement parent = navi.Parent(Example.Instance.mEqui); parent = navi.Parent(nozz); parent = navi.Parent(parent); //All Members DbElement[] tees = navi.MembersInScan(Example.Instance.mPipe); }
public void CanFilterTwoItemsWithFilterInstance() { ItemFilter filter = new TypeFilter(typeof(FirstItem)); ItemList list = CreateList(); filter.Filter(list); Assert.AreEqual(1, list.Count); }
public void PASS_Serialize() { TypeFilter filter = new TypeFilter("type"); string json = JsonConvert.SerializeObject(filter); Assert.IsNotNull(json); string expectedJson = "{\"type\":{\"value\":\"type\"}}"; Assert.AreEqual(expectedJson, json); }
public RoleSet(Type _Class) { TypeFilter filter = new TypeFilter(RoleFilter); Type[] Roles = _Class.FindInterfaces(filter, (object)__RoleTypes); _Set = new HashSet<Type>(); foreach (Type r in Roles) { _Set.Add(r); } }
public override object ReadJson(JsonReader reader, System.Type objectType, object existingValue, JsonSerializer serializer) { Dictionary<string, object> fieldDict = serializer.Deserialize<Dictionary<string, object>>(reader); if (fieldDict.ContainsKey(FilterTypeEnum.Type.ToString())) fieldDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(fieldDict.First().Value.ToString()); TypeFilter filter = new TypeFilter(fieldDict.GetString(_TYPE)); filter.FilterName = fieldDict.GetStringOrDefault(FilterSerializer._FILTER_NAME); return filter; }
public void FAIL_CreateFilter() { try { TypeFilter filter = new TypeFilter(null); Assert.Fail(); } catch (ArgumentNullException ex) { Assert.AreEqual("documentType", ex.ParamName); } }
public static string RenderMainMenu(this HtmlHelper helper) { var builder = new StringBuilder(); var formatString = "<li> <a href=\"#{0}\" class=\"jump {1}\">{2}</a>"; var filter = new TypeFilter(typeof(AbstractPage)); foreach (var child in Find.StartPage.GetChildren(filter)) { builder.Append(string.Format(formatString, child.Name, child is ContactFormPage ? "contact-page" : string.Empty, child.Title)); } return builder.ToString(); }
public static Type[] FindInterfaces(this Type type, TypeFilter filter, object filterCriteria) { if (filter == null) throw new ArgumentNullException("filter"); List<Type> ifaces = new List<Type>(); foreach (Type iface in type.GetInterfaces()) { if (filter(iface, filterCriteria)) ifaces.Add(iface); } return ifaces.ToArray(); }
public static Type[] FindInterfaces(this Type myType, TypeFilter TypeFilter, Object FilterCriteria) { if (TypeFilter == null) throw new ArgumentNullException("filter"); var Interfaces = new List<Type>(); foreach (var Interface in myType.GetInterfaces()) { if (TypeFilter(Interface, FilterCriteria)) Interfaces.Add(Interface); } return Interfaces.ToArray(); }
public static string RenderPagesHtml(this HtmlHelper helper) { var builder = new StringBuilder(); var formatString = "<div class=\"sub\" id=\"{0}\"><h1>{1}</h1>{2}</div>"; var filter = new TypeFilter(typeof(ContentPage)); foreach (ContentPage child in Find.StartPage.GetChildren(filter).OrderBy(x => x.SortOrder)) { builder.Append(string.Format(formatString, child.Name, child.Title, child.Text)); } filter = new TypeFilter(typeof(ContactFormPage)); foreach (ContactFormPage child in Find.StartPage.GetChildren(filter)) { builder.Append(string.Format(formatString, child.Name, child.Title, child.Text)); } return builder.ToString(); }
internal static void InitLibs() { // load dumplib for reflection Assembly dumplib3 = Assembly.ReflectionOnlyLoadFrom("DumpLib.dll"); Assembly dumplibasm = Assembly.LoadFile(Path.Combine(Program.WorkDir, "DumpLib.dll")); // get a list of all the external assemblies and load them AssemblyName[] dumplib_refs = dumplibasm.GetReferencedAssemblies(); for (int h = 0; h < dumplib_refs.Length; h++) Assembly.ReflectionOnlyLoad(dumplib_refs[h].FullName); var filter = new TypeFilter(InterfaceFilter); var j = dumplibasm.GetTypes(); Type[] ifaces = null; foreach (var type in j) { ifaces = type.FindInterfaces(filter, "dumplib.Gfx.IColorConverter"); if (ifaces.Length > 0) { dumplib.Gfx.IColorConverter newinstance = (dumplib.Gfx.IColorConverter)Activator.CreateInstance(type); Program.ColorConverters.Add(newinstance.ID, newinstance); } ifaces = type.FindInterfaces(filter, "dumplib.Gfx.ITileConverter"); if (ifaces.Length > 0) { dumplib.Gfx.ITileConverter newinstance = (dumplib.Gfx.ITileConverter)Activator.CreateInstance(type); Program.TileConverters.Add(newinstance.ID, newinstance); } ifaces = type.FindInterfaces(filter, "dumplib.Gfx.IPaletteConverter"); if (ifaces.Length > 0) { dumplib.Gfx.IPaletteConverter newinstance = (dumplib.Gfx.IPaletteConverter)Activator.CreateInstance(type); Program.PaletteConverters.Add(newinstance.ID, newinstance); } //if (type.BaseType != null && type.BaseType.FullName == "dumplib.Image.MediaImage") Program.MediaImages.Add((dumplib.Image.MediaImage)Activator.CreateInstance(type)); } Console.WriteLine(ifaces.ToString()); // load teh same from other DLLs }
/// <summary> /// Get all types of object that implement the type <typeparamref name="T"/> inside the assembly /// </summary> /// <typeparam name="T">Interface type</typeparam> /// <param name="filename">File path of the assembly</param> /// <returns>An enumerable of type <see cref="Type"/> that implements <typeparamref name="T"/></returns> public static IEnumerable <Type> GetTypesFromAssembly <T>(string filename) { if (!File.Exists(filename)) { throw new FileNotFoundException($"DLL file not found. File path: {filename}"); } var asm = Assembly.LoadFrom(filename); var types = asm.GetTypes(); var typeFilter = new TypeFilter(InterfaceFilter); foreach (var type in types) { var interfaces = type.FindInterfaces(typeFilter, typeof(T).ToString()); if (interfaces.Length > 0) { // We found the type that implements the interface yield return(type); } } }
internal ExtractedEnumType(INamedType namedType, string typeNamespace, TypeFilter dispNameFilter) : base(namedType, typeNamespace) { // Use extended string attributeName = typeof(ScriptEnumAttribute).FullName; string useExtendedName = nameof(ScriptEnumAttribute.UseExtendedSyntax); foreach (IAttributeData attrData in namedType.Attributes) { if (attrData.AttributeType.FullName == attributeName) { if (attrData.NamedArguments.ContainsKey(useExtendedName)) { UseExtendedSyntax = (bool)attrData.NamedArguments[useExtendedName]; } } } // Members Members = namedType.Fields.Select(field => new EnumMemberInfo(field, dispNameFilter)).ToList().AsReadOnly(); }
protected static bool TestCompatibleTypes(IEnumerable target, object data) { TypeFilter filter = (t, o) => { return(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable <>)); }; var enumerableInterfaces = target.GetType().FindInterfaces(filter, null); var enumerableTypes = from i in enumerableInterfaces select i.GetGenericArguments().Single(); if (enumerableTypes.Count() > 0) { Type dataType = TypeUtilities.GetCommonBaseClass(ExtractData(data)); return(enumerableTypes.Any(t => t.IsAssignableFrom(dataType))); } else { return(target is IList); } }
/// <summary> /// Returns the "T" in the IQueryable of T implementation of type. /// </summary> /// <param name="type">Type to check.</param> /// <param name="typeFilter">filter against which the type is checked</param> /// <returns> /// The element type for the generic IQueryable interface of the type, /// or null if it has none or if it's ambiguous. /// </returns> private static Type GetGenericInterfaceElementType(Type type, TypeFilter typeFilter) { Debug.Assert(type != null, "type != null"); Debug.Assert(!type.IsGenericTypeDefinition, "!type.IsGenericTypeDefinition"); if (typeFilter(type, null)) { return(type.GetGenericArguments()[0]); } Type[] queriables = type.FindInterfaces(typeFilter, null); if (queriables != null && queriables.Length == 1) { return(queriables[0].GetGenericArguments()[0]); } else { return(null); } }
/// <summary> /// Returns the list of collections associated to a provided index. /// The returned list is sorted in alphanumerical order. /// </summary> public async Task <JObject> ListAsync( string index, int?from = null, int?size = null, TypeFilter type = TypeFilter.All ) { var request = new JObject { { "controller", "collection" }, { "action", "list" }, { "index", index } }; string listType = ""; switch (type) { case TypeFilter.All: listType = "all"; break; case TypeFilter.Realtime: listType = "realtime"; break; case TypeFilter.Stored: listType = "stored"; break; } if (from != null) { request.Add("from", from); } if (size != null) { request.Add("size", size); } request.Add("type", listType); Response response = await api.QueryAsync(request); return((JObject)response.Result); }
/// <summary> /// Gets info about the code examples defined in the calling assembly. /// </summary> /// <param name="callingAssembly">The calling assembly.</param> /// <returns>The collection of examples defined in the calling assembly.</returns> private List <CodeExampleInfo> GetCodeExamples(Assembly callingAssembly) { var exportedTypes = callingAssembly.ExportedTypes; List <CodeExampleInfo> examples = new List <CodeExampleInfo>(); Func <Type, object, bool> iExampleFilter = (interfaceType, fullName) => { return(String.CompareOrdinal( interfaceType.FullName, fullName.ToString()) == 0); }; TypeFilter typeFilter = new TypeFilter(iExampleFilter); foreach (var type in exportedTypes) { // Check if the exported type derives from ICodeExample Type[] interfaces = type.FindInterfaces( typeFilter, ICodeExampleFullName); bool isExample = interfaces.Length > 0; // if so, use its full name to identify its source code file. if (isExample) { if (type.FullName.StartsWith(this.DefaultNamespace)) { this.GetSourceCodeInfo( type, out string path, out ProgrammingLanguage language); examples.Add(new CodeExampleInfo(type, path, language)); } } } return(examples); }
private IEnumerable <string> test(string path, Type checkType) { List <string> foundPlugins = new List <string>(); string[] mfiles = Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly); for (int i = 0; i < mfiles.Length; i++) { try { Assembly current = Assembly.LoadFile(mfiles[i]); Type[] types = current.GetExportedTypes(); foreach (Type type in current.GetExportedTypes()) { TypeFilter b = delegate(Type filterType, object filter) { return(filterType.FullName == checkType.FullName); }; Type[] arr = type.FindInterfaces(b, null); if (arr.Length > 0) { foundPlugins.Add(string.Format("{0}, {1}", type.Assembly.Location, type.FullName)); } } } catch (TypeLoadException) { //do nothing } catch (BadImageFormatException) { //do nothing; } } for (int i = 0; i < foundPlugins.Count; i++) { yield return(foundPlugins[i]); } }
/// <summary> /// Retrieve the translation models with optional filters. /// </summary> /// <param name="callback">The callback to invoke with the array of models.</param> /// <param name="sourceFilter">Optional source language filter.</param> /// <param name="targetFilter">Optional target language filter.</param> /// <param name="defaults">Controls if we get default, non-default, or all models.</param> /// <returns>Returns a true on success, false if it failed to submit the request.</returns> public bool GetModels(GetModelsCallback callback, string sourceFilter = null, string targetFilter = null, TypeFilter defaults = TypeFilter.ALL) { if (callback == null) { throw new ArgumentNullException("callback"); } RESTConnector connector = RESTConnector.GetConnector(SERVICE_ID, "/v2/models"); if (connector == null) { return(false); } GetModelsReq req = new GetModelsReq(); req.Callback = callback; req.OnResponse = GetModelsResponse; if (!string.IsNullOrEmpty(sourceFilter)) { req.Parameters["source"] = sourceFilter; } if (!string.IsNullOrEmpty(targetFilter)) { req.Parameters["target"] = targetFilter; } if (defaults == TypeFilter.DEFAULT) { req.Parameters["default"] = "true"; } else if (defaults == TypeFilter.NON_DEFAULT) { req.Parameters["default"] = "false"; } return(connector.Send(req)); }
public Hashtable GetVolumeWithinElement(string elementname, Hashtable dbtypeArray, Boolean completelycover) { //DbElementType[] dbtypes = new DbElementType[] { DbElementTypeInstance.PSPOOL }; string samplerow = ((string)dbtypeArray[1.0]); List<DbElementType> dbtypeslist = new List<DbElementType>(); foreach (var item in dbtypeArray.Keys) { dbtypeslist.Add(DbElementType.GetElementType(dbtypeArray[item].ToString())); } DbElementType[] dbtypes = dbtypeslist.ToArray(); DbElement Outfit_Elements = MDB.CurrentMDB.GetFirstWorld(Aveva.Pdms.Database.DbType.Design); DBElementCollection result_collection = null; TypeFilter filter = new TypeFilter(dbtypes); AndFilter finalfilter = new AndFilter(); InVolumeFilter volfilter = new InVolumeFilter(CurrentElement.Element,dbtypes, true); finalfilter.Add(filter); finalfilter.Add(volfilter); result_collection = new DBElementCollection(Outfit_Elements, finalfilter); Hashtable resultHs = new Hashtable(); double idx = 1.0; foreach (DbElement item in result_collection) { resultHs.Add(idx, item.GetAsString(DbAttributeInstance.NAME)); idx = idx + 1.0; } return resultHs; }
/// <summary> /// Get an instance using reflection from deployed assemblies /// </summary> /// <param name="fullyQualifiedName"></param> /// <param name="cacheName"></param> /// <returns></returns> public static IPersistenceProvider CreateInstanceWithReflection(string fullyQualifiedName, string cacheName) { const string qualifiedInterfaceName = "PersistenceProviders.IPersistenceProvider"; var interfaceFilter = new TypeFilter(InterfaceFilter); var path = Path.Combine(AppUtil.DeployedAssemblyDir, cacheName); var directoryInfo = new DirectoryInfo(path); foreach (var file in directoryInfo.GetFiles("*.dll")) { try { //ReflectionOnlyLoadFrom var nextAssembly = Assembly.LoadFrom(file.FullName); try { foreach (var type in nextAssembly.GetTypes()) { var myInterfaces = type.FindInterfaces(interfaceFilter, qualifiedInterfaceName); foreach (var intrfce in myInterfaces) { if (type.AssemblyQualifiedName.Equals(fullyQualifiedName)) { return((IPersistenceProvider)Activator.CreateInstance(type)); } } } } catch { //ignore and wait for loading other files } } catch (BadImageFormatException) { throw; } } throw new FileNotFoundException("No dll loaded with FQN provided in cache configuration"); }
public static bool TypeIsInterface(this Type type, Type interfaceType) { if (interfaceType.IsGenericType) { Type[] genericArguments = interfaceType.GetGenericArguments(); foreach (var intf in type.GetInterfaces().Where(i => i.IsGenericType)) { var intfGenericArguments = intf.GetGenericArguments(); if (genericArguments .Where((t, i) => intfGenericArguments[i] == t || intfGenericArguments[i].IsSubclassOf(t)) .Count() == genericArguments.Length) { return(true); } } return(false); } TypeFilter typeFilter = InterfaceFilter; return(type.FindInterfaces(typeFilter, interfaceType).Length > 0); }
//Create and iterate through collections public static void Run() { //Scan Nozzles below equi TypeFilter filt = new TypeFilter(DbElementTypeInstance.NOZZLE); DBElementCollection collection = new DBElementCollection(Example.Instance.mEqui, filt); DbAttribute att = DbAttributeInstance.FLNN; foreach (DbElement ele in collection) { Console.WriteLine(ele.GetAsString(att)); } //Scan branches below site DBElementCollection coll = new DBElementCollection(Example.Instance.mSite); coll.IncludeRoot = true; coll.Filter = new TypeFilter(DbElementTypeInstance.BRANCH); DBElementEnumerator iter = (DBElementEnumerator)coll.GetEnumerator(); while (iter.MoveNext()) { Console.WriteLine(iter.Current.ToString()); } }
public IEnumerable <Buildable> GetBuildables(DbElement owner) { TypeFilter box = new TypeFilter(DbElementTypeInstance.BOX); TypeFilter cone = new TypeFilter(DbElementTypeInstance.CONE); TypeFilter cylinder = new TypeFilter(DbElementTypeInstance.CYLINDER); TypeFilter dish = new TypeFilter(DbElementTypeInstance.DISH); TypeFilter extr = new TypeFilter(DbElementTypeInstance.EXTRUSION); TypeFilter nozz = new TypeFilter(DbElementTypeInstance.NOZZLE); TypeFilter ctorus = new TypeFilter(DbElementTypeInstance.CTORUS); TypeFilter pyramid = new TypeFilter(DbElementTypeInstance.PYRAMID); OrFilter orFilter = new OrFilter(new BaseFilter[] { box, cone, cylinder, dish, extr, nozz, ctorus, pyramid }); DBElementCollection elements = new DBElementCollection(owner, orFilter); foreach (DbElement element in elements) { yield return(Converter.ElementToBuildable(element)); } }
/// <summary> /// Searches for requested type in all available components DLLs /// The searched type could be a class, an abstract class or an interface /// </summary> public Type[] SearchForTypes(Type search) { TypeFilter TypeFilter = new TypeFilter(InterfaceFilterCallback); List <Type> theList = new List <Type>(); foreach (Type type in mTypes) { if (!type.IsAbstract && type.IsClass) { // check if requested interface implemented if (search.IsInterface) { if (type.FindInterfaces(TypeFilter, search).Length > 0) { if (!theList.Contains(type)) // avoid duplicates { theList.Add(type); } } } // test current type and search also in the base class tree else { for (Type t = type; t != null; t = t.BaseType) { if (t.Name == search.Name) { if (!theList.Contains(type)) // avoid duplicates { theList.Add(type); } break; } } } } } return(theList.ToArray()); }
private static MethodInfo FindInterfaceMethod(Type targetType, Type interfaceType, string name, Type[] parameterTypes) { TypeFilter filter = null; if (targetType.GetIsInterface()) { if (filter == null) { filter = (type, _) => type == interfaceType; } return(targetType.FindInterfaces(filter, null).Single <Type>().GetMethod(name, parameterTypes)); } InterfaceMapping interfaceMap = targetType.GetInterfaceMap(interfaceType); int index = Array.FindIndex <MethodInfo>(interfaceMap.InterfaceMethods, method => (method.Name == name) && (from p in method.GetParameters() select p.ParameterType).SequenceEqual <Type>(parameterTypes)); if (index < 0) { Contract.Assert(false, string.Concat(new object[] { interfaceType, "::", name, "(", string.Join(", ", (from t in parameterTypes select t.ToString()).ToArray <string>()), ") is not found in ", targetType })); return(null); } return(interfaceMap.TargetMethods[index]); }
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) { // Dynamic Modules are copied to a directory as part of a post-build step. // These modules are not referenced in the startup project and are discovered // by examining the assemblies in a directory. The module projects have the // following post-build step in order to copy themselves into that directory: // // xcopy "$(TargetDir)$(TargetFileName)" "$(TargetDir)modules\" /y // // WARNING! Do not forget to build the solution (F6) before each running // so the modules are copied into the modules folder. var directoryCatalog = (DirectoryModuleCatalog)moduleCatalog; directoryCatalog.Initialize(); linkGroupCollection = new LinkGroupCollection(); var typeFilter = new TypeFilter(InterfaceFilter); foreach (var module in directoryCatalog.Items) { var mi = (ModuleInfo)module; var asm = Assembly.LoadFrom(mi.Ref); foreach (Type t in asm.GetTypes()) { var myInterfaces = t.FindInterfaces(typeFilter, typeof(ILinkGroupService).ToString()); if (myInterfaces.Length > 0) { // We found the type that implements the ILinkGroupService interface var linkGroupService = (ILinkGroupService)asm.CreateInstance(t.FullName); var linkGroup = linkGroupService.GetLinkGroup(); linkGroupCollection.Add(linkGroup); } } } moduleCatalog.AddModule(typeof(Core.CoreModule)); }
public async Task ItemsChanged_TestAsync() { var authentication = await this.TestContext.LoginRandomAsync(Authority.Admin); var typeFilter = new TypeFilter(); var type = await typeFilter.GetTypeAsync(dataBase); var actualValue = string.Empty; var expectedValue = type.TypeInfo.HashValue; var template = type.Template; await typeContext.AddItemsChangedEventHandlerAsync(TypeContext_ItemsChanged); await template.BeginEditAsync(authentication); await template.ModifyRandomMembersAsync(authentication, 5); await template.EndEditAsync(authentication); Assert.AreNotEqual(expectedValue, actualValue); expectedValue = actualValue; await typeContext.RemoveItemsChangedEventHandlerAsync(TypeContext_ItemsChanged); await template.BeginEditAsync(authentication); await template.ModifyRandomMembersAsync(authentication, 5); await template.EndEditAsync(authentication); Assert.AreEqual(expectedValue, actualValue); void TypeContext_ItemsChanged(object sender, ItemsEventArgs <ITypeItem> e) { if (e.Items.Single() is IType type) { actualValue = type.TypeInfo.HashValue; } } }
public static void Run() { //FirstMember TypeFilter filt = new TypeFilter(DbElementTypeInstance.NOZZLE); DbElement nozz1 = filt.FirstMember(Example.Instance.mEqui); DbElementType type = nozz1.GetElementType(); //NextMember DbElement nozz2 = filt.Next(nozz1); //NextMember DbElement[] members = filt.Members(Example.Instance.mEqui); //parent TypeFilter filt2 = new TypeFilter(DbElementTypeInstance.SITE); DbElement site = filt2.Parent(nozz1); type = site.GetElementType(); //Valid AndFilter andFilt4 = new AndFilter(); andFilt4.Add(new TypeFilter(DbElementTypeInstance.EQUIPMENT)); andFilt4.Add(new TrueFilter()); bool valid = andFilt4.Valid(Example.Instance.mEqui); // attribute true AttributeTrueFilter filt1 = new AttributeTrueFilter(DbAttributeInstance.ISNAME); //should be true for named element bool named = filt1.Valid(Example.Instance.mEqui); //for first member it is also true named = filt1.Valid(Example.Instance.mEqui.FirstMember()); //Element type at or below BelowOrAtType filt3 = new BelowOrAtType(DbElementTypeInstance.EQUIPMENT); bool below = filt3.ScanBelow(Example.Instance.mEqui); }
public static TypeFilter ParsFilter(PropertiesFilter filters) { var result = new TypeFilter(new Dictionary <string, TypeFilter>(filters.Count)); foreach (var filter in filters.Values.Where(f => f.Value != null)) { switch (filter.Value) { case PropertiesFilter innerFilter: result.PropertyFilters.Add(filter.Key.Name, ParsFilter(innerFilter)); break; case Delegate predecate: result.PropertyFilters.Add(filter.Key.Name, new TypeFilter(predecate)); break; default: result.PropertyFilters.Add(filter.Key.Name, new TypeFilter(filter.Value.ToString())); break; } } return(result.PropertyFilters.Count > 0 ? result : null); }
public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) { Type[] c = GetTypes(); int cnt = 0; for (int i = 0; i < c.Length; i++) { if (filter != null && !filter(c[i], filterCriteria)) c[i] = null; else cnt++; } if (cnt == c.Length) return c; Type[] ret = new Type[cnt]; cnt = 0; for (int i = 0; i < c.Length; i++) { if (c[i] != null) ret[cnt++] = c[i]; } return ret; }
protected static bool TestCompatibleTypes(IEnumerable pTarget, object pData) { if (pTarget == null) { return(false); } TypeFilter lFilter = (lType, lObject) => (lType.IsGenericType && lType.GetGenericTypeDefinition() == typeof(IEnumerable <>)); var lEnumerableInterfaces = pTarget.GetType().FindInterfaces(lFilter, null); var lEnumerableTypes = from i in lEnumerableInterfaces select i.GetGenericArguments().Single(); var enumerableTypes = lEnumerableTypes as IList <Type> ?? lEnumerableTypes.ToList(); if (!enumerableTypes.Any()) { return(pTarget is IList); } var lDataType = TypeHelper.GetCommonBaseClass(ExtractData(pData)); return(enumerableTypes.Any(t => t.IsAssignableFrom(lDataType))); }
// FindInterfaces // This method will filter the interfaces supported the class public static Type[] FindInterfaces(this Type type, TypeFilter filter, Object filterCriteria) { if (filter == null) { throw new ArgumentNullException("filter"); } Contract.EndContractBlock(); Type[] c = type.GetInterfaces(); int cnt = 0; for (int i = 0; i < c.Length; i++) { if (!filter(c[i], filterCriteria)) { c[i] = null; } else { cnt++; } } if (cnt == c.Length) { return(c); } Type[] ret = new Type[cnt]; cnt = 0; for (int i = 0; i < c.Length; i++) { if (c[i] != null) { ret[cnt++] = c[i]; } } return(ret); }
public List <IProcedureTransformation> AvailableProcTemplates() { List <IProcedureTransformation> lstRet = new List <IProcedureTransformation>(); const string qualifiedInterfaceName = "SWBrasil.ORM.Common.IProcedureTransformation"; var interfaceFilter = new TypeFilter(InterfaceFilter); AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve); var di = new DirectoryInfo(ORM.Default.TemplatesPath); foreach (FileInfo file in di.GetFiles("*.dll")) { try { var nextAssembly = Assembly.UnsafeLoadFrom(file.FullName); foreach (var type in nextAssembly.GetTypes()) { var myInterfaces = type.FindInterfaces(interfaceFilter, qualifiedInterfaceName); if (myInterfaces.Length > 0) { for (int i = 0; i < myInterfaces.Length; i++) { lstRet.Add((IProcedureTransformation)Activator.CreateInstance(type)); } } } } catch (BadImageFormatException) { // Not a .net assembly - ignore } } return(lstRet); }
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) { DirectoryModuleCatalog directoryCatalog = (DirectoryModuleCatalog)moduleCatalog; directoryCatalog.Initialize(); moduleCollection = new ObservableCollection <ModuleModel>(); TypeFilter typeFilter = new TypeFilter(InterfaceFilter); try { foreach (IModuleCatalogItem item in directoryCatalog.Items) { ModuleInfo mi = (ModuleInfo)item; // in .NetFrameWork we dont need to replace Assembly asm = Assembly.LoadFrom(mi.Ref.Replace(@"file:///", "")); foreach (Type t in asm.GetTypes()) { Type[] myInterfaces = t.FindInterfaces(typeFilter, typeof(IModuleService).ToString()); if (myInterfaces.Length > 0) { IModuleService moduleService = (IModuleService)asm.CreateInstance(t.FullName); ModuleModel module = moduleService.GetModule(); moduleCollection.Add(module); } } } } catch (Exception ex) { HandyControl.Controls.MessageBox.Error(ex.Message); } }
public virtual Type[] FindInterfaces(TypeFilter filter, object filterCriteria) { if (filter == null) { throw new ArgumentNullException(nameof(filter)); } Type[] c = GetInterfaces(); int cnt = 0; for (int i = 0; i < c.Length; i++) { if (!filter(c[i], filterCriteria)) { c[i] = null; } else { cnt++; } } if (cnt == c.Length) { return(c); } Type[] ret = new Type[cnt]; cnt = 0; for (int i = 0; i < c.Length; i++) { if (c[i] != null) { ret[cnt++] = c[i]; } } return(ret); }
private static IList <Type> FindTypes(Assembly assembly, Type baseType, TypeFilter filter) { ArgumentValidator.EnsureArgumentNotNull(assembly, "assembly"); ArgumentValidator.EnsureArgumentNotNull(baseType, "baseType"); Type[] allTypes; try { allTypes = assembly.GetTypes(); } catch (Exception e) { throw new InvalidOperationException( string.Format(Strings.ExCouldNotLoadTypesFromAssembly, assembly.FullName), e); } List <Type> types = new List <Type>(allTypes.Length); for (int index = 0; index < allTypes.Length; index++) { Type type = allTypes[index]; if (type != baseType && !(type.IsSubclassOf(baseType) || (baseType.IsInterface && baseType.IsAssignableFrom(type)))) { continue; } if (baseType.IsAssignableFrom(type)) { if (filter != null && !filter(type, null)) { continue; } types.Add(type); } } return(types); }
public static Type[] FindInterfaces(this Type type, TypeFilter filter, object filterCriteria) { if (filter == null) { throw new ArgumentNullException("filter"); } var interfaces = type.GetInterfaces(); var count = 0; for (var i = 0; i < interfaces.Length; i++) { if (!filter(interfaces[i], filterCriteria)) { interfaces[i] = null; } else { count++; } } if (count == interfaces.Length) { return(interfaces); } var array = new Type[count]; count = 0; foreach (var t in interfaces.Where(t => t != null)) { array[count++] = t; } return(array); }
private bool FilterIdols(object obj) { var idol = obj as IIdol; var ok = TypeFilter.HasFlag(idol.Category); if (FilterOwned) { ok &= !m_config.OwnedIdols.Any(x => x.Iid == idol.Iid); } if (!string.IsNullOrEmpty(NameFilter)) { ok &= idol.Name.ToLower().Contains(NameFilter.ToLower()) || (idol.Label != null && idol.Label.ToLower().Contains(NameFilter.ToLower())); } if (RarityFilter != null) { ok &= idol.Rarity == RarityFilter; } if (CenterEffectFilter != null) { ok &= idol.CenterEffect != null && idol.CenterEffect.GetType() == CenterEffectFilter; } if (SkillFilter != null) { ok &= idol.Skill != null && idol.Skill.GetType() == SkillFilter; } if(ShowOwnedOnly) { ok &= m_config.OwnedIdols.Any(x => x.Name == idol.Name); } return ok; }
public string Type(string type, string[] genericArgs, bool includeNested = false) { var useType = TypeFilter?.Invoke(type, genericArgs); if (useType != null) { return(useType); } if (genericArgs != null) { if (type == "Nullable`1") { return($"{TypeAlias(genericArgs[0], includeNested: includeNested)}?"); } var parts = type.Split('`'); if (parts.Length > 1) { var args = StringBuilderCacheAlt.Allocate(); foreach (var arg in genericArgs) { if (args.Length > 0) { args.Append(", "); } args.Append(TypeAlias(arg.SanitizeType(), includeNested: includeNested)); } var typeName = NameOnly(type, includeNested: includeNested).SanitizeType(); return($"{typeName}<{StringBuilderCacheAlt.ReturnAndFree(args)}>"); } } return(TypeAlias(type, includeNested: includeNested)); }
public static void WriteLine(Message message) { if (!String.IsNullOrEmpty(CallerFilter) && !CallerFilter.Contains(message.Caller.ToString())) { return; } if (!String.IsNullOrEmpty(TypeFilter) && !TypeFilter.Contains(message.Type.ToString())) { return; } //Dispatcher.CurrentDispatcher.Invoke((Action)(() => //{ lock (MessageList) { MessageList.Item.Add(message); } //})); if (MessageReceived != null) { MessageReceived(new MessagingEventArgs(message)); } }
// http://msdn2.microsoft.com/en-us/library/system.type.findinterfaces.aspx private static List <string> GetImplementedInterfaces(TypeItem typeItem) { List <string> result = new List <string>(); try { TypeFilter myFilter = new TypeFilter(MyInterfaceFilter); Type[] myInterfaces = typeItem.TypeRef.FindInterfaces(myFilter, null); for (int i = 0; i < myInterfaces.Length; i++) { result.Add(myInterfaces[i].ToString()); } } catch (ArgumentNullException) { //Console.WriteLine("ArgumentNullException: " + e.Message); } catch (TargetInvocationException) { //Console.WriteLine("TargetInvocationException: " + e.Message); } return(result); }
//since the game jam is over, im allowed to write clean code public static void LoadItems() { //fill up the nameDirectory using reflection var mods = Assembly.GetExecutingAssembly().Modules; foreach (var m in mods) { TypeFilter isAnItem = (i, o) => typeof(Item).IsAssignableFrom(i) && !i.IsAbstract; //initialize itemNames and itemList itemList = m.FindTypes(isAnItem, null); itemNames = new string[itemList.Length]; for (int i = 0; i < itemList.Length; i++) { Type type = itemList[i]; var name = type.GetField(nameField, BindingFlags.Public | BindingFlags.Static); //id is no longer needed if (name == null) { UnityEngine.Debug.LogError($"field {nameField} of {type} is missing"); continue; } else { //item with valid name string itemName = (string)name.GetValue(null); itemList[i] = type; itemNames[i] = itemName; //nameDictionary.Add((ItemID)id.GetValue(null), (string)name.GetValue(null)); } } } LoadItemResources(); }
public Type[] FindInterfaces(TypeFilter filter, object filterCriteria) { List<Type> list = new List<Type>(); foreach (Type type in GetInterfaces()) { if (filter(type, filterCriteria)) { list.Add(type); } } return list.ToArray(); }
/// <summary> /// Returns an array of <see cref="T:System.Type"/> objects representing a filtered list of interfaces implemented or inherited by the current <see cref="T:System.Type"/>. /// </summary> /// <returns> /// An array of <see cref="T:System.Type"/> objects representing a filtered list of the interfaces implemented or inherited by the current <see cref="T:System.Type"/>, or an empty array of type <see cref="T:System.Type"/> if no interfaces matching the filter are implemented or inherited by the current <see cref="T:System.Type"/>. /// </returns> /// <param name="filter"> /// The <see cref="T:System.Reflection.TypeFilter"/> delegate that compares the interfaces against <paramref name="filterCriteria"/>. /// </param> /// <param name="filterCriteria"> /// The search criteria that determines whether an interface should be included in the returned array. /// </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="filter"/> is null. /// </exception> /// <exception cref="T:System.Reflection.TargetInvocationException"> /// A static initializer is invoked and throws an exception. /// </exception> /// <filterpriority>2</filterpriority> public Type[] FindInterfaces(TypeFilter filter, object filterCriteria) { return _type.FindInterfaces(filter, filterCriteria); }
public override Type[] FindInterfaces(TypeFilter filter, object filterCriteria) { Debug.Assert(false, "NYI"); return base.FindInterfaces(filter, filterCriteria); }
public virtual Type[] FindInterfaces (TypeFilter filter, object filterCriteria) { if (filter == null) throw new ArgumentNullException ("filter"); ArrayList ifaces = new ArrayList (); foreach (Type iface in GetInterfaces ()) { if (filter (iface, filterCriteria)) ifaces.Add (iface); } return (Type []) ifaces.ToArray (typeof (Type)); }
public void NoTypeNamePicksFirstType() { Type forwardingLoggerType = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger); string forwardingLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location; TypeFilter forwardingLoggerfilter = new TypeFilter(IsForwardingLoggerClass); Type firstPublicType = FirstPublicDesiredType(forwardingLoggerfilter, forwardingLoggerAssemblyLocation); TypeLoader loader = new TypeLoader(forwardingLoggerfilter); LoadedType loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, forwardingLoggerAssemblyLocation)); Assert.IsNotNull(loadedType); Assert.IsTrue(loadedType.Assembly.AssemblyLocation.Equals(forwardingLoggerAssemblyLocation, StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(loadedType.Type.Equals(firstPublicType)); Type fileLoggerType = typeof(Microsoft.Build.Logging.FileLogger); string fileLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location; TypeFilter fileLoggerfilter = new TypeFilter(IsLoggerClass); firstPublicType = FirstPublicDesiredType(fileLoggerfilter, fileLoggerAssemblyLocation); loader = new TypeLoader(fileLoggerfilter); loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, fileLoggerAssemblyLocation)); Assert.IsNotNull(loadedType); Assert.IsTrue(loadedType.Assembly.AssemblyLocation.Equals(fileLoggerAssemblyLocation, StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(loadedType.Type.Equals(firstPublicType)); }
private static Type FirstPublicDesiredType(TypeFilter filter, string assemblyLocation) { Assembly loadedAssembly = Assembly.UnsafeLoadFrom(assemblyLocation); // only look at public types Type[] allPublicTypesInAssembly = loadedAssembly.GetExportedTypes(); foreach (Type publicType in allPublicTypesInAssembly) { if (filter(publicType, null)) { return publicType; } } return null; }
Type[] FindTypes(TypeFilter filter, object filterCriteria) { var filtered = new List<Type> (); Type[] types = GetTypes (); foreach (Type t in types) if (filter (t, filterCriteria)) filtered.Add (t); return filtered.ToArray (); }
/// <summary> /// Constructor. /// </summary> internal TypeLoader(TypeFilter isDesiredType) { ErrorUtilities.VerifyThrow(isDesiredType != null, "need a type filter"); _isDesiredType = isDesiredType; }
/// <summary> /// Given a type filter, and an assembly to load the type information from determine if a given type name is in the assembly or not. /// </summary> internal AssemblyInfoToLoadedTypes(TypeFilter typeFilter, AssemblyLoadInfo loadInfo) { ErrorUtilities.VerifyThrowArgumentNull(typeFilter, "typefilter"); ErrorUtilities.VerifyThrowArgumentNull(loadInfo, "loadInfo"); _isDesiredType = typeFilter; _assemblyLoadInfo = loadInfo; _typeNameToType = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); _publicTypeNameToType = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); }
public virtual Type[] FindTypes(TypeFilter filter, object filterCriteria) { throw CreateNIE (); }
// Find the interfaces that match a set of filter criteria. public virtual Type[] FindInterfaces(TypeFilter filter, Object filterCriteria) { if(filter == null) { throw new ArgumentNullException("filter"); } Type[] interfaces = GetInterfaces(); if(interfaces == null) { return EmptyTypes; } int posn, posn2; posn = 0; posn2 = 0; while(posn < interfaces.Length) { if(filter(interfaces[posn], filterCriteria)) { interfaces[posn2++] = interfaces[posn]; } ++posn; } if(posn2 == interfaces.Length) { return interfaces; } else { Type[] list = new Type [posn2]; Array.Copy(interfaces, 0, list, 0, posn2); return list; } }